综合平台编程器项目的远程存储
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

737 righe
32 KiB

  1. #include "domain/project_storage.h"
  2. #include "infrastructure/json_project_storage.h"
  3. #include "services/register_comment_service.h"
  4. #include "services/project_service.h"
  5. #include <QFile>
  6. #include <QJsonArray>
  7. #include <QJsonDocument>
  8. #include <QJsonObject>
  9. #include <QTemporaryDir>
  10. #include <exception>
  11. #include <iostream>
  12. #include <stdexcept>
  13. #include <string>
  14. #include <utility>
  15. namespace {
  16. void require(bool condition, const std::string &message)
  17. {
  18. if (!condition)
  19. {
  20. throw std::runtime_error(message);
  21. }
  22. }
  23. Project makeExampleProject()
  24. {
  25. // 构造覆盖 HMI 控件和梯形图串并联结构的完整 JSON 往返样本
  26. HmiControl start_button;
  27. start_button.id = "start-button";
  28. start_button.type = HmiControlType::Button;
  29. start_button.bounds = {10, 20, 120, 48};
  30. start_button.text = "Start";
  31. start_button.binding = RegisterAddress{RegisterArea::M, 0};
  32. start_button.buttonOperation = HmiButtonOperation::SetOn;
  33. start_button.properties.emplace("color", "green");
  34. HmiControl running_indicator;
  35. running_indicator.id = "running-indicator";
  36. running_indicator.type = HmiControlType::Indicator;
  37. running_indicator.bounds = {150, 20, 64, 64};
  38. running_indicator.text = "Running";
  39. running_indicator.binding = RegisterAddress{RegisterArea::M, 1};
  40. running_indicator.properties.emplace("activeColor", "#24a148");
  41. HmiControl temperature_display;
  42. temperature_display.id = "temperature-display";
  43. temperature_display.type = HmiControlType::NumericDisplay;
  44. temperature_display.bounds = {10, 90, 120, 40};
  45. temperature_display.text = "Temperature";
  46. temperature_display.binding = RegisterAddress{RegisterArea::D, 2};
  47. temperature_display.properties.emplace("format", "decimal");
  48. HmiControl target_input;
  49. target_input.id = "target-input";
  50. target_input.type = HmiControlType::NumericInput;
  51. target_input.bounds = {150, 90, 120, 40};
  52. target_input.text = "Target";
  53. target_input.binding = RegisterAddress{RegisterArea::D, 3};
  54. target_input.properties.emplace("minimum", "-100");
  55. HmiControl title_label;
  56. title_label.id = "title-label";
  57. title_label.type = HmiControlType::Label;
  58. title_label.bounds = {10, 145, 180, 32};
  59. title_label.text = "Production line";
  60. HmiControl settings_jump;
  61. settings_jump.id = "settings-jump";
  62. settings_jump.type = HmiControlType::PageJump;
  63. settings_jump.bounds = {210, 145, 120, 40};
  64. settings_jump.text = "Settings";
  65. settings_jump.pageJump = HmiPageJumpConfig{"settings-page"};
  66. HmiControl alarm_list;
  67. alarm_list.id = "alarm-list";
  68. alarm_list.type = HmiControlType::AlarmList;
  69. alarm_list.bounds = {10, 200, 360, 180};
  70. alarm_list.text = "Alarms";
  71. HmiPage page;
  72. page.id = "main-page";
  73. page.name = "Main";
  74. page.controls.push_back(start_button);
  75. page.controls.push_back(running_indicator);
  76. page.controls.push_back(temperature_display);
  77. page.controls.push_back(target_input);
  78. page.controls.push_back(title_label);
  79. page.controls.push_back(settings_jump);
  80. page.controls.push_back(alarm_list);
  81. HmiPage settings_page;
  82. settings_page.id = "settings-page";
  83. settings_page.name = "Settings";
  84. LogicNode contact;
  85. contact.id = "start-contact";
  86. contact.config = ContactNodeConfig{
  87. RegisterAddress{RegisterArea::M, 0},
  88. ContactMode::NormallyOpen};
  89. LogicNode compare;
  90. compare.id = "temperature-check";
  91. compare.config = CompareNodeConfig{
  92. RegisterAddress{RegisterArea::D, 2},
  93. ComparisonOperator::GreaterThanOrEqual,
  94. static_cast<std::int16_t>(100)};
  95. LogicNode hold_contact;
  96. hold_contact.id = "hold-contact";
  97. hold_contact.config = ContactNodeConfig{
  98. RegisterAddress{RegisterArea::M, 1},
  99. ContactMode::NormallyOpen};
  100. LogicNode coil;
  101. coil.id = "run-coil";
  102. coil.config = CoilNodeConfig{
  103. RegisterAddress{RegisterArea::M, 1},
  104. CoilMode::Set};
  105. ControlLogic logic;
  106. logic.id = "start-logic";
  107. logic.name = "Start logic";
  108. logic.enabled = false;
  109. LadderRung rung;
  110. rung.id = "rung-1";
  111. rung.name = "Network 1";
  112. rung.comment = "启动条件与温度检查";
  113. ConditionExpression parallel;
  114. parallel.id = "parallel-start";
  115. parallel.kind = ConditionExpressionKind::Parallel;
  116. parallel.children = {
  117. ConditionExpression::fromNode(contact),
  118. ConditionExpression::fromNode(hold_contact)};
  119. ConditionExpression series;
  120. series.id = "series-root";
  121. series.kind = ConditionExpressionKind::Series;
  122. series.children = {
  123. std::move(parallel),
  124. ConditionExpression::fromNode(compare)};
  125. rung.condition = std::move(series);
  126. rung.output = coil;
  127. logic.rungs.push_back(rung);
  128. LogicNode rising_edge;
  129. rising_edge.id = "rising-edge";
  130. rising_edge.config = EdgeContactNodeConfig{
  131. RegisterAddress{RegisterArea::M, 4}, EdgeMode::Rising};
  132. LogicNode ton_output;
  133. ton_output.id = "ton-output";
  134. ton_output.config = TonNodeConfig{TimerAddress{7}, 2500};
  135. LadderRung ton_rung;
  136. ton_rung.id = "ton-rung";
  137. ton_rung.name = "TON network";
  138. ton_rung.comment = "延时启动";
  139. ton_rung.condition = ConditionExpression::fromNode(rising_edge);
  140. ton_rung.output = ton_output;
  141. logic.rungs.push_back(ton_rung);
  142. LogicNode falling_edge;
  143. falling_edge.id = "falling-edge";
  144. falling_edge.config = EdgeContactNodeConfig{
  145. RegisterAddress{RegisterArea::M, 5}, EdgeMode::Falling};
  146. LogicNode timer_contact;
  147. timer_contact.id = "timer-contact";
  148. timer_contact.config = TimerContactNodeConfig{
  149. TimerAddress{7}, ContactMode::NormallyOpen};
  150. LogicNode timer_coil;
  151. timer_coil.id = "timer-coil";
  152. timer_coil.config = CoilNodeConfig{
  153. RegisterAddress{RegisterArea::M, 6}, CoilMode::Normal};
  154. LadderRung timer_rung;
  155. timer_rung.id = "timer-rung";
  156. timer_rung.name = "Timer feedback";
  157. timer_rung.comment = "定时器完成反馈";
  158. ConditionExpression timer_series;
  159. timer_series.id = "timer-series";
  160. timer_series.kind = ConditionExpressionKind::Series;
  161. timer_series.children = {
  162. ConditionExpression::fromNode(falling_edge),
  163. ConditionExpression::fromNode(timer_contact)};
  164. timer_rung.condition = std::move(timer_series);
  165. timer_rung.output = timer_coil;
  166. logic.rungs.push_back(timer_rung);
  167. LogicNode counter_input;
  168. counter_input.id = "counter-input";
  169. counter_input.config = ContactNodeConfig{
  170. RegisterAddress{RegisterArea::M, 7}, ContactMode::NormallyOpen};
  171. LogicNode counter_output;
  172. counter_output.id = "counter-output";
  173. counter_output.config = CounterNodeConfig{
  174. CounterAddress{3},
  175. CounterMode::Up,
  176. RegisterAddress{RegisterArea::D, 10},
  177. WordOperand{
  178. WordOperandKind::Register,
  179. RegisterAddress{RegisterArea::D, 11},
  180. 0},
  181. RegisterAddress{RegisterArea::M, 8}};
  182. LadderRung counter_rung;
  183. counter_rung.id = "counter-rung";
  184. counter_rung.name = "Counter network";
  185. counter_rung.comment = "计数器上升沿计数";
  186. counter_rung.condition = ConditionExpression::fromNode(counter_input);
  187. counter_rung.output = counter_output;
  188. logic.rungs.push_back(counter_rung);
  189. LogicNode counter_contact;
  190. counter_contact.id = "counter-contact";
  191. counter_contact.config = CounterContactNodeConfig{
  192. CounterAddress{3}, ContactMode::NormallyOpen};
  193. LogicNode counter_coil;
  194. counter_coil.id = "counter-coil";
  195. counter_coil.config = CoilNodeConfig{
  196. RegisterAddress{RegisterArea::M, 9}, CoilMode::Normal};
  197. LadderRung counter_feedback_rung;
  198. counter_feedback_rung.id = "counter-feedback-rung";
  199. counter_feedback_rung.name = "Counter feedback";
  200. counter_feedback_rung.condition = ConditionExpression::fromNode(counter_contact);
  201. counter_feedback_rung.output = counter_coil;
  202. logic.rungs.push_back(counter_feedback_rung);
  203. const auto addDataRung = [&logic](
  204. const std::string &rung_id,
  205. const std::string &input_id,
  206. int input_address,
  207. LogicNode output)
  208. {
  209. LogicNode input;
  210. input.id = input_id;
  211. input.config = ContactNodeConfig{
  212. RegisterAddress{RegisterArea::M, input_address},
  213. ContactMode::NormallyOpen};
  214. LadderRung data_rung;
  215. data_rung.id = rung_id;
  216. data_rung.name = rung_id;
  217. data_rung.condition = ConditionExpression::fromNode(input);
  218. data_rung.output = std::move(output);
  219. logic.rungs.push_back(std::move(data_rung));
  220. };
  221. addDataRung(
  222. "move-rung",
  223. "move-input",
  224. 20,
  225. LogicNode{
  226. "move-output",
  227. MoveNodeConfig{
  228. WordOperand{
  229. WordOperandKind::Constant,
  230. RegisterAddress{RegisterArea::D, 0},
  231. 25},
  232. RegisterAddress{RegisterArea::D, 20}},
  233. true});
  234. addDataRung(
  235. "add-rung",
  236. "add-input",
  237. 21,
  238. LogicNode{
  239. "add-output",
  240. ArithmeticNodeConfig{
  241. ArithmeticOperation::Add,
  242. WordOperand{
  243. WordOperandKind::Register,
  244. RegisterAddress{RegisterArea::D, 20},
  245. 0},
  246. WordOperand{
  247. WordOperandKind::Constant,
  248. RegisterAddress{RegisterArea::D, 0},
  249. 1},
  250. RegisterAddress{RegisterArea::D, 21}},
  251. true});
  252. addDataRung(
  253. "sub-rung",
  254. "sub-input",
  255. 22,
  256. LogicNode{
  257. "sub-output",
  258. ArithmeticNodeConfig{
  259. ArithmeticOperation::Subtract,
  260. WordOperand{
  261. WordOperandKind::Register,
  262. RegisterAddress{RegisterArea::D, 21},
  263. 0},
  264. WordOperand{
  265. WordOperandKind::Constant,
  266. RegisterAddress{RegisterArea::D, 0},
  267. 1},
  268. RegisterAddress{RegisterArea::D, 22}},
  269. true});
  270. Project project;
  271. project.metadata = {"example-project", "Example project", "1.0"};
  272. project.hmiPages.push_back(page);
  273. project.hmiPages.push_back(settings_page);
  274. project.initialHmiPageId = page.id;
  275. project.alarmDefinitions.push_back(
  276. {"alarm-emergency",
  277. RegisterAddress{RegisterArea::M, 10},
  278. AlarmCondition::MOn,
  279. 0,
  280. "Emergency stop"});
  281. project.alarmDefinitions.push_back(
  282. {"alarm-temperature",
  283. RegisterAddress{RegisterArea::D, 2},
  284. AlarmCondition::DHigh,
  285. 80,
  286. "Temperature high"});
  287. project.registerComments = {
  288. {RegisterAddress{RegisterArea::M, 0}, "启动按钮"},
  289. {RegisterAddress{RegisterArea::D, 2}, "当前温度"}};
  290. project.controlLogics.push_back(logic);
  291. ControlLogic draft_logic;
  292. draft_logic.id = "draft-logic";
  293. draft_logic.name = "Draft logic";
  294. draft_logic.enabled = false;
  295. draft_logic.rungs.push_back(
  296. {"rung-1", "Draft network", {}, std::nullopt, std::nullopt});
  297. project.controlLogics.push_back(draft_logic);
  298. return project;
  299. }
  300. void writeText(const QString &path, const QByteArray &content)
  301. {
  302. // 直接写入故障样本文件,以验证加载失败时的保护行为
  303. QFile file(path);
  304. require(file.open(QIODevice::WriteOnly), "test file must be writable");
  305. require(file.write(content) == content.size(), "test file must be written completely");
  306. }
  307. QByteArray readBytes(const QString &path)
  308. {
  309. QFile file(path);
  310. require(file.open(QIODevice::ReadOnly), "saved project must be readable");
  311. return file.readAll();
  312. }
  313. void testEmptyProjectRoundTrip()
  314. {
  315. // 空工程是合法工程,保存再加载后不应凭空产生页面或逻辑
  316. QTemporaryDir directory;
  317. require(directory.isValid(), "temporary directory must be valid");
  318. JsonProjectStorage storage;
  319. ProjectService service(storage);
  320. require(service.createNewProject("Empty project").succeeded,
  321. "empty project creation must succeed");
  322. const QString path = directory.filePath("empty.json");
  323. require(service.saveAs(path.toStdString()).succeeded,
  324. "empty project save must succeed");
  325. require(!service.isModified(), "saved project must not be marked modified");
  326. require(service.load(path.toStdString()).succeeded,
  327. "empty project load must succeed");
  328. require(service.project().metadata.name == "Empty project",
  329. "empty project name must survive round trip");
  330. require(service.project().hmiPages.empty(), "empty project must have no HMI pages");
  331. require(service.project().controlLogics.empty(),
  332. "empty project must have no control logics");
  333. require(service.project().alarmDefinitions.empty(),
  334. "empty project must have no alarm definitions");
  335. }
  336. void testExampleProjectRoundTrip()
  337. {
  338. // 验证各层嵌套字段往返后保持不变且序列化结果稳定
  339. QTemporaryDir directory;
  340. require(directory.isValid(), "temporary directory must be valid");
  341. JsonProjectStorage storage;
  342. ProjectService service(storage);
  343. service.editProject() = makeExampleProject();
  344. const QString first_path = directory.filePath("example.json");
  345. const QString second_path = directory.filePath("example-copy.json");
  346. const QString invalid_operation_path = directory.filePath("invalid-operation.json");
  347. const QString missing_initial_path = directory.filePath("missing-initial.json");
  348. const QString missing_target_path = directory.filePath("missing-target.json");
  349. const QString missing_alarms_path = directory.filePath("missing-alarms.json");
  350. const QString missing_register_comments_path = directory.filePath(
  351. "missing-register-comments.json");
  352. const QString missing_rung_comment_path = directory.filePath(
  353. "missing-rung-comment.json");
  354. require(service.saveAs(first_path.toStdString()).succeeded,
  355. "example project save must succeed");
  356. const QByteArray saved_json = readBytes(first_path);
  357. require(saved_json.contains("\"rungs\"")
  358. && saved_json.contains("\"condition\"")
  359. && saved_json.contains("\"children\"")
  360. && saved_json.contains("\"output\""),
  361. "saved project must use structured ladder expressions");
  362. require(!saved_json.contains("\"dataPoints\""),
  363. "saved project must not contain the removed data point model");
  364. require(saved_json.contains("\"formatVersion\": \"1.0\"")
  365. && saved_json.contains("\"buttonOperation\": \"setOn\"")
  366. && saved_json.contains("\"initialHmiPageId\": \"main-page\"")
  367. && saved_json.contains("\"targetPageId\": \"settings-page\"")
  368. && saved_json.contains("\"alarmDefinitions\"")
  369. && saved_json.contains("\"registerComments\"")
  370. && saved_json.contains("\"text\": \"启动按钮\"")
  371. && saved_json.contains("\"type\": \"edgeContact\"")
  372. && saved_json.contains("\"type\": \"timerContact\"")
  373. && saved_json.contains("\"type\": \"ton\"")
  374. && saved_json.contains("\"type\": \"counterContact\"")
  375. && saved_json.contains("\"type\": \"counter\"")
  376. && saved_json.contains("\"type\": \"move\"")
  377. && saved_json.contains("\"type\": \"arithmetic\"")
  378. && saved_json.contains("\"operation\": \"add\"")
  379. && saved_json.contains("\"operation\": \"subtract\"")
  380. && saved_json.contains("\"comment\": \"启动条件与温度检查\"")
  381. && saved_json.contains("\"type\": \"alarmList\""),
  382. "version 1.0 projects must persist pages and alarm definitions");
  383. require(!saved_json.contains("\"stages\"")
  384. && !saved_json.contains("\"branches\""),
  385. "current project format must not contain the removed stage model");
  386. require(!saved_json.contains("\"position\"")
  387. && !saved_json.contains("\"connections\""),
  388. "saved ladder logic must not contain free-graph fields");
  389. require(service.load(first_path.toStdString()).succeeded,
  390. "example project load must succeed");
  391. const Project &project = service.project();
  392. require(project.metadata.id == "example-project", "project id must survive round trip");
  393. require(project.hmiPages.size() == 2, "HMI page count must survive round trip");
  394. require(project.initialHmiPageId == "main-page",
  395. "the initial HMI page id must survive round trip");
  396. require(project.hmiPages.front().controls.size() == 7,
  397. "register, navigation and AlarmList controls must survive round trip");
  398. require(project.hmiPages.front().controls.front().binding->area()
  399. == RegisterArea::M,
  400. "HMI M binding must survive round trip");
  401. require(project.hmiPages.front().controls.front().buttonOperation
  402. == HmiButtonOperation::SetOn,
  403. "HMI button operation must survive round trip");
  404. require(project.hmiPages.front().controls.front().properties.at("color") == "green",
  405. "HMI properties must survive round trip");
  406. require(project.hmiPages.front().controls.at(1).type == HmiControlType::Indicator,
  407. "indicator control type must survive round trip");
  408. require(project.hmiPages.front().controls.at(2).binding->area() == RegisterArea::D,
  409. "numeric display D binding must survive round trip");
  410. require(project.hmiPages.front().controls.at(3).bounds.x == 150,
  411. "numeric input bounds must survive round trip");
  412. require(project.hmiPages.front().controls.at(4).type == HmiControlType::Label
  413. && project.hmiPages.front().controls.at(5).pageJump->targetPageId
  414. == "settings-page",
  415. "Label and PageJump typed data must survive round trip");
  416. require(project.hmiPages.front().controls.at(6).type
  417. == HmiControlType::AlarmList,
  418. "AlarmList control type must survive round trip");
  419. require(project.alarmDefinitions.size() == 2
  420. && project.alarmDefinitions.front().condition
  421. == AlarmCondition::MOn
  422. && project.alarmDefinitions.at(1).threshold == 80,
  423. "M and D alarm definitions must survive round trip");
  424. require(project.registerComments.size() == 2
  425. && project.registerComments.front().address.area() == RegisterArea::M
  426. && project.registerComments.front().text == "启动按钮"
  427. && project.registerComments.at(1).address.area() == RegisterArea::D,
  428. "M/D register comments must survive round trip");
  429. require(project.controlLogics.size() == 2,
  430. "control logic count must survive round trip");
  431. require(!project.controlLogics.front().enabled,
  432. "control logic enabled state must survive round trip");
  433. const LadderRung &rung = project.controlLogics.front().rungs.front();
  434. require(rung.comment == "启动条件与温度检查",
  435. "rung comments must survive round trip");
  436. require(rung.condition.has_value()
  437. && rung.condition->kind == ConditionExpressionKind::Series,
  438. "series root expression must survive round trip");
  439. require(rung.condition->children.front().kind
  440. == ConditionExpressionKind::Parallel
  441. && rung.condition->children.front().children.size() == 2U,
  442. "parallel expression branches must survive round trip");
  443. require(rung.output.has_value(),
  444. "ladder output must survive round trip");
  445. const LadderRung &ton_rung = project.controlLogics.front().rungs.at(1);
  446. require(ton_rung.output.has_value()
  447. && std::holds_alternative<TonNodeConfig>(ton_rung.output->config)
  448. && std::get<TonNodeConfig>(ton_rung.output->config).address
  449. == TimerAddress{7}
  450. && std::get<TonNodeConfig>(ton_rung.output->config).presetMs == 2500,
  451. "TON timer address and preset must survive round trip");
  452. require(std::holds_alternative<EdgeContactNodeConfig>(
  453. ton_rung.condition->node->config)
  454. && std::get<EdgeContactNodeConfig>(ton_rung.condition->node->config).mode
  455. == EdgeMode::Rising,
  456. "rising edge configuration must survive round trip");
  457. const LadderRung &timer_rung = project.controlLogics.front().rungs.at(2);
  458. require(timer_rung.comment == "定时器完成反馈"
  459. && std::holds_alternative<TimerContactNodeConfig>(
  460. timer_rung.condition->children.at(1).node->config)
  461. && std::get<TimerContactNodeConfig>(
  462. timer_rung.condition->children.at(1).node->config).address
  463. == TimerAddress{7}
  464. && std::holds_alternative<EdgeContactNodeConfig>(
  465. timer_rung.condition->children.front().node->config)
  466. && std::get<EdgeContactNodeConfig>(
  467. timer_rung.condition->children.front().node->config).mode
  468. == EdgeMode::Falling,
  469. "falling edge and T contact configurations must survive round trip");
  470. const LadderRung &counter_rung = project.controlLogics.front().rungs.at(3);
  471. const auto &counter = std::get<CounterNodeConfig>(counter_rung.output->config);
  472. require(counter.address == CounterAddress{3}
  473. && counter.currentValueAddress == RegisterAddress{RegisterArea::D, 10}
  474. && counter.preset.kind == WordOperandKind::Register
  475. && counter.preset.address == RegisterAddress{RegisterArea::D, 11}
  476. && counter.resetAddress == RegisterAddress{RegisterArea::M, 8},
  477. "counter resource and external M/D addresses must survive round trip");
  478. const LadderRung &counter_feedback = project.controlLogics.front().rungs.at(4);
  479. require(std::holds_alternative<CounterContactNodeConfig>(
  480. counter_feedback.condition->node->config)
  481. && std::get<CounterContactNodeConfig>(
  482. counter_feedback.condition->node->config).address
  483. == CounterAddress{3},
  484. "counter contacts must survive round trip");
  485. require(std::get<MoveNodeConfig>(
  486. project.controlLogics.front().rungs.at(5).output->config)
  487. .source.constant == 25,
  488. "MOVE operands must survive round trip");
  489. require(std::get<ArithmeticNodeConfig>(
  490. project.controlLogics.front().rungs.at(6).output->config)
  491. .operation == ArithmeticOperation::Add
  492. && std::get<ArithmeticNodeConfig>(
  493. project.controlLogics.front().rungs.at(7).output->config)
  494. .operation == ArithmeticOperation::Subtract,
  495. "ADD and SUB operations must survive round trip");
  496. const auto &compare = std::get<CompareNodeConfig>(
  497. rung.condition->children.at(1).node->config);
  498. require(compare.address.index() == 2 && compare.value == 100,
  499. "comparison configuration must survive round trip");
  500. require(service.saveAs(second_path.toStdString()).succeeded,
  501. "save as must succeed after load");
  502. require(readBytes(first_path) == readBytes(second_path),
  503. "save and save as must produce stable JSON");
  504. QByteArray invalid_operation = saved_json;
  505. invalid_operation.replace(
  506. "\"buttonOperation\": \"setOn\"",
  507. "\"buttonOperation\": \"unsupported\"");
  508. writeText(invalid_operation_path, invalid_operation);
  509. require(!service.load(invalid_operation_path.toStdString()).succeeded,
  510. "unsupported HMI button operations must be rejected");
  511. QJsonObject missing_initial = QJsonDocument::fromJson(saved_json).object();
  512. missing_initial.remove(QStringLiteral("initialHmiPageId"));
  513. writeText(
  514. missing_initial_path,
  515. QJsonDocument(missing_initial).toJson(QJsonDocument::Compact));
  516. ProjectOperationResult missing_result = service.load(
  517. missing_initial_path.toStdString());
  518. require(!missing_result.succeeded
  519. && missing_result.storageError == ProjectStorageError::MissingField,
  520. "the 1.0 schema must require initialHmiPageId without migration defaults");
  521. QJsonObject missing_alarms = QJsonDocument::fromJson(saved_json).object();
  522. missing_alarms.remove(QStringLiteral("alarmDefinitions"));
  523. writeText(
  524. missing_alarms_path,
  525. QJsonDocument(missing_alarms).toJson(QJsonDocument::Compact));
  526. missing_result = service.load(missing_alarms_path.toStdString());
  527. require(!missing_result.succeeded
  528. && missing_result.storageError == ProjectStorageError::MissingField,
  529. "the 1.0 schema must require alarmDefinitions without migration defaults");
  530. QJsonObject missing_register_comments = QJsonDocument::fromJson(saved_json).object();
  531. missing_register_comments.remove(QStringLiteral("registerComments"));
  532. writeText(
  533. missing_register_comments_path,
  534. QJsonDocument(missing_register_comments).toJson(QJsonDocument::Compact));
  535. missing_result = service.load(missing_register_comments_path.toStdString());
  536. require(!missing_result.succeeded
  537. && missing_result.storageError == ProjectStorageError::MissingField,
  538. "the 1.0 schema must require registerComments without migration defaults");
  539. QJsonObject missing_rung_comment = QJsonDocument::fromJson(saved_json).object();
  540. QJsonArray missing_comment_logics = missing_rung_comment.value(
  541. QStringLiteral("controlLogics")).toArray();
  542. QJsonObject first_logic = missing_comment_logics.at(0).toObject();
  543. QJsonArray first_rungs = first_logic.value(QStringLiteral("rungs")).toArray();
  544. QJsonObject first_rung = first_rungs.at(0).toObject();
  545. first_rung.remove(QStringLiteral("comment"));
  546. first_rungs.replace(0, first_rung);
  547. first_logic.insert(QStringLiteral("rungs"), first_rungs);
  548. missing_comment_logics.replace(0, first_logic);
  549. missing_rung_comment.insert(QStringLiteral("controlLogics"), missing_comment_logics);
  550. writeText(
  551. missing_rung_comment_path,
  552. QJsonDocument(missing_rung_comment).toJson(QJsonDocument::Compact));
  553. missing_result = service.load(missing_rung_comment_path.toStdString());
  554. require(!missing_result.succeeded
  555. && missing_result.storageError == ProjectStorageError::MissingField,
  556. "the 1.0 schema must require rung comments without migration defaults");
  557. QJsonObject missing_target = QJsonDocument::fromJson(saved_json).object();
  558. QJsonArray pages = missing_target.value(QStringLiteral("hmiPages")).toArray();
  559. QJsonObject main_page = pages.at(0).toObject();
  560. QJsonArray controls = main_page.value(QStringLiteral("controls")).toArray();
  561. QJsonObject jump = controls.at(5).toObject();
  562. jump.remove(QStringLiteral("targetPageId"));
  563. controls.replace(5, jump);
  564. main_page.insert(QStringLiteral("controls"), controls);
  565. pages.replace(0, main_page);
  566. missing_target.insert(QStringLiteral("hmiPages"), pages);
  567. writeText(
  568. missing_target_path,
  569. QJsonDocument(missing_target).toJson(QJsonDocument::Compact));
  570. missing_result = service.load(missing_target_path.toStdString());
  571. require(!missing_result.succeeded
  572. && missing_result.storageError == ProjectStorageError::MissingField,
  573. "the 1.0 schema must require PageJump targetPageId");
  574. }
  575. void testInvalidFiles()
  576. {
  577. // 非法文件必须被拒绝,并且不得覆盖服务中当前工程
  578. QTemporaryDir directory;
  579. require(directory.isValid(), "temporary directory must be valid");
  580. JsonProjectStorage storage;
  581. ProjectService service(storage);
  582. service.editProject().metadata.name = "Current project";
  583. const QString invalid_json = directory.filePath("invalid-json.json");
  584. const QString missing_field = directory.filePath("missing-field.json");
  585. const QString unsupported_version = directory.filePath("unsupported-version.json");
  586. writeText(invalid_json, "{");
  587. auto result = service.load(invalid_json.toStdString());
  588. require(!result.succeeded
  589. && result.storageError == ProjectStorageError::InvalidJson,
  590. "invalid JSON must be rejected");
  591. require(service.project().metadata.name == "Current project",
  592. "invalid load must keep current project");
  593. writeText(missing_field, R"({"formatVersion":"1.0"})");
  594. result = service.load(missing_field.toStdString());
  595. require(!result.succeeded
  596. && result.storageError == ProjectStorageError::MissingField,
  597. "missing fields must be rejected");
  598. writeText(unsupported_version, R"({"formatVersion":"2.0"})");
  599. result = service.load(unsupported_version.toStdString());
  600. require(!result.succeeded
  601. && result.storageError == ProjectStorageError::UnsupportedVersion,
  602. "unsupported versions must be rejected");
  603. }
  604. void testServiceStateAndSaveErrors()
  605. {
  606. // 保存路径和修改标记只在成功持久化后更新
  607. QTemporaryDir directory;
  608. require(directory.isValid(), "temporary directory must be valid");
  609. JsonProjectStorage storage;
  610. ProjectService service(storage);
  611. require(service.save().error == ProjectServiceError::FilePathRequired,
  612. "save without a current path must be rejected");
  613. require(service.createNewProject(" ").error
  614. == ProjectServiceError::InvalidProjectName,
  615. "blank project names must be rejected");
  616. const QString path = directory.filePath("state.json");
  617. service.editProject().metadata.name = "State project";
  618. require(service.saveAs(path.toStdString()).succeeded,
  619. "state project save must succeed");
  620. service.editProject().metadata.name = "Changed project";
  621. require(service.isModified(), "editing the project must mark it modified");
  622. require(service.save().succeeded, "save must use the current file path");
  623. require(!service.isModified(), "successful save must clear modified state");
  624. const QString failed_path = directory.filePath("missing/subdir/state.json");
  625. require(!service.saveAs(failed_path.toStdString()).succeeded,
  626. "save to an unavailable path must fail");
  627. require(service.currentFilePath() == path.toStdString(),
  628. "failed save as must keep the previous current path");
  629. }
  630. void testRegisterCommentService()
  631. {
  632. JsonProjectStorage storage;
  633. ProjectService project_service(storage);
  634. RegisterCommentService service(project_service);
  635. require(service.setComment(
  636. RegisterAddress{RegisterArea::D, 3}, " 目标温度 ").succeeded,
  637. "register comment service must create a trimmed D comment");
  638. require(service.setComment(
  639. RegisterAddress{RegisterArea::M, 2}, "启动信号").succeeded,
  640. "register comment service must create an M comment");
  641. require(service.comments().size() == 2U
  642. && service.comments().front().address.area() == RegisterArea::M
  643. && service.comments().front().address.index() == 2
  644. && service.comments().back().text == "目标温度",
  645. "register comments must be sorted by area and address");
  646. require(service.setComment(
  647. RegisterAddress{RegisterArea::M, 2}, "新的启动信号").succeeded
  648. && service.comments().size() == 2U
  649. && service.findComment(RegisterAddress{RegisterArea::M, 2})->text
  650. == "新的启动信号",
  651. "setting an existing address must update instead of duplicating it");
  652. require(!service.setComment(RegisterAddress{RegisterArea::M, 4}, " \t").succeeded,
  653. "blank register comments must be rejected by the service");
  654. require(service.removeComment(RegisterAddress{RegisterArea::M, 2}).succeeded
  655. && service.findComment(RegisterAddress{RegisterArea::M, 2}) == nullptr,
  656. "register comments must be removable");
  657. require(!service.removeComment(RegisterAddress{RegisterArea::M, 2}).succeeded,
  658. "removing a missing register comment must fail explicitly");
  659. }
  660. } // namespace
  661. int main()
  662. {
  663. try
  664. {
  665. // 工程服务和 JSON 存储在同一测试进程中验证完整闭环
  666. testEmptyProjectRoundTrip();
  667. testExampleProjectRoundTrip();
  668. testRegisterCommentService();
  669. testInvalidFiles();
  670. testServiceStateAndSaveErrors();
  671. }
  672. catch (const std::exception &error)
  673. {
  674. std::cerr << "project management tests failed: " << error.what() << '\n';
  675. return 1;
  676. }
  677. std::cout << "project management tests passed\n";
  678. return 0;
  679. }