综合平台编程器项目的远程存储
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

281 Zeilen
11 KiB

  1. #include "domain/project_storage.h"
  2. #include "infrastructure/json_project_storage.h"
  3. #include "services/project_service.h"
  4. #include <QFile>
  5. #include <QTemporaryDir>
  6. #include <exception>
  7. #include <iostream>
  8. #include <stdexcept>
  9. #include <string>
  10. namespace {
  11. void require(bool condition, const std::string &message)
  12. {
  13. if (!condition)
  14. {
  15. throw std::runtime_error(message);
  16. }
  17. }
  18. Project makeExampleProject()
  19. {
  20. // 构造覆盖四种 HMI 控件和三种逻辑节点的完整 JSON 往返样本
  21. HmiControl start_button;
  22. start_button.id = "start-button";
  23. start_button.type = HmiControlType::Button;
  24. start_button.bounds = {10, 20, 120, 48};
  25. start_button.text = "Start";
  26. start_button.binding = RegisterAddress{RegisterArea::M, 0};
  27. start_button.properties.emplace("color", "green");
  28. HmiControl running_indicator;
  29. running_indicator.id = "running-indicator";
  30. running_indicator.type = HmiControlType::Indicator;
  31. running_indicator.bounds = {150, 20, 64, 64};
  32. running_indicator.text = "Running";
  33. running_indicator.binding = RegisterAddress{RegisterArea::M, 1};
  34. running_indicator.properties.emplace("activeColor", "#24a148");
  35. HmiControl temperature_display;
  36. temperature_display.id = "temperature-display";
  37. temperature_display.type = HmiControlType::NumericDisplay;
  38. temperature_display.bounds = {10, 90, 120, 40};
  39. temperature_display.text = "Temperature";
  40. temperature_display.binding = RegisterAddress{RegisterArea::D, 2};
  41. temperature_display.properties.emplace("format", "decimal");
  42. HmiControl target_input;
  43. target_input.id = "target-input";
  44. target_input.type = HmiControlType::NumericInput;
  45. target_input.bounds = {150, 90, 120, 40};
  46. target_input.text = "Target";
  47. target_input.binding = RegisterAddress{RegisterArea::D, 3};
  48. target_input.properties.emplace("minimum", "-100");
  49. HmiPage page;
  50. page.id = "main-page";
  51. page.name = "Main";
  52. page.controls.push_back(start_button);
  53. page.controls.push_back(running_indicator);
  54. page.controls.push_back(temperature_display);
  55. page.controls.push_back(target_input);
  56. LogicNode contact;
  57. contact.id = "start-contact";
  58. contact.config = ContactNodeConfig{
  59. RegisterAddress{RegisterArea::M, 0},
  60. ContactMode::NormallyOpen};
  61. contact.position = {80, 100};
  62. LogicNode compare;
  63. compare.id = "temperature-check";
  64. compare.config = CompareNodeConfig{
  65. RegisterAddress{RegisterArea::D, 2},
  66. ComparisonOperator::GreaterThanOrEqual,
  67. static_cast<std::int16_t>(100)};
  68. compare.position = {320, 100};
  69. LogicNode coil;
  70. coil.id = "run-coil";
  71. coil.config = CoilNodeConfig{
  72. RegisterAddress{RegisterArea::M, 1},
  73. CoilMode::Set};
  74. coil.position = {560, 100};
  75. ControlLogic logic;
  76. logic.id = "start-logic";
  77. logic.name = "Start logic";
  78. logic.enabled = false;
  79. logic.nodes = {contact, compare, coil};
  80. logic.connections.push_back({contact.id, compare.id});
  81. logic.connections.push_back({compare.id, coil.id});
  82. Project project;
  83. project.metadata = {"example-project", "Example project", "1.0"};
  84. project.hmiPages.push_back(page);
  85. project.controlLogics.push_back(logic);
  86. return project;
  87. }
  88. void writeText(const QString &path, const QByteArray &content)
  89. {
  90. // 直接写入故障样本文件,以验证加载失败时的保护行为
  91. QFile file(path);
  92. require(file.open(QIODevice::WriteOnly), "test file must be writable");
  93. require(file.write(content) == content.size(), "test file must be written completely");
  94. }
  95. QByteArray readBytes(const QString &path)
  96. {
  97. QFile file(path);
  98. require(file.open(QIODevice::ReadOnly), "saved project must be readable");
  99. return file.readAll();
  100. }
  101. void testEmptyProjectRoundTrip()
  102. {
  103. // 空工程是合法工程,保存再加载后不应凭空产生页面或逻辑
  104. QTemporaryDir directory;
  105. require(directory.isValid(), "temporary directory must be valid");
  106. JsonProjectStorage storage;
  107. ProjectService service(storage);
  108. require(service.createNewProject("Empty project").succeeded,
  109. "empty project creation must succeed");
  110. const QString path = directory.filePath("empty.json");
  111. require(service.saveAs(path.toStdString()).succeeded,
  112. "empty project save must succeed");
  113. require(!service.isModified(), "saved project must not be marked modified");
  114. require(service.load(path.toStdString()).succeeded,
  115. "empty project load must succeed");
  116. require(service.project().metadata.name == "Empty project",
  117. "empty project name must survive round trip");
  118. require(service.project().hmiPages.empty(), "empty project must have no HMI pages");
  119. require(service.project().controlLogics.empty(),
  120. "empty project must have no control logics");
  121. }
  122. void testExampleProjectRoundTrip()
  123. {
  124. // 验证各层嵌套字段往返后保持不变且序列化结果稳定
  125. QTemporaryDir directory;
  126. require(directory.isValid(), "temporary directory must be valid");
  127. JsonProjectStorage storage;
  128. ProjectService service(storage);
  129. service.editProject() = makeExampleProject();
  130. const QString first_path = directory.filePath("example.json");
  131. const QString second_path = directory.filePath("example-copy.json");
  132. require(service.saveAs(first_path.toStdString()).succeeded,
  133. "example project save must succeed");
  134. require(service.load(first_path.toStdString()).succeeded,
  135. "example project load must succeed");
  136. const Project &project = service.project();
  137. require(project.metadata.id == "example-project", "project id must survive round trip");
  138. require(project.hmiPages.size() == 1, "HMI page count must survive round trip");
  139. require(project.hmiPages.front().controls.size() == 4,
  140. "all basic HMI controls must survive round trip");
  141. require(project.hmiPages.front().controls.front().binding->area()
  142. == RegisterArea::M,
  143. "HMI M binding must survive round trip");
  144. require(project.hmiPages.front().controls.front().properties.at("color") == "green",
  145. "HMI properties must survive round trip");
  146. require(project.hmiPages.front().controls.at(1).type == HmiControlType::Indicator,
  147. "indicator control type must survive round trip");
  148. require(project.hmiPages.front().controls.at(2).binding->area() == RegisterArea::D,
  149. "numeric display D binding must survive round trip");
  150. require(project.hmiPages.front().controls.at(3).bounds.x == 150,
  151. "numeric input bounds must survive round trip");
  152. require(project.controlLogics.size() == 1,
  153. "control logic count must survive round trip");
  154. require(!project.controlLogics.front().enabled,
  155. "control logic enabled state must survive round trip");
  156. require(project.controlLogics.front().nodes.size() == 3,
  157. "logic node count must survive round trip");
  158. require(project.controlLogics.front().nodes.front().position.x == 80,
  159. "logic node position must survive round trip");
  160. const auto &compare = std::get<CompareNodeConfig>(
  161. project.controlLogics.front().nodes.at(1).config);
  162. require(compare.address.index() == 2 && compare.value == 100,
  163. "comparison configuration must survive round trip");
  164. require(service.saveAs(second_path.toStdString()).succeeded,
  165. "save as must succeed after load");
  166. require(readBytes(first_path) == readBytes(second_path),
  167. "save and save as must produce stable JSON");
  168. }
  169. void testInvalidFiles()
  170. {
  171. // 非法文件必须被拒绝,并且不得覆盖服务中当前工程
  172. QTemporaryDir directory;
  173. require(directory.isValid(), "temporary directory must be valid");
  174. JsonProjectStorage storage;
  175. ProjectService service(storage);
  176. service.editProject().metadata.name = "Current project";
  177. const QString invalid_json = directory.filePath("invalid-json.json");
  178. const QString missing_field = directory.filePath("missing-field.json");
  179. const QString unsupported_version = directory.filePath("unsupported-version.json");
  180. writeText(invalid_json, "{");
  181. auto result = service.load(invalid_json.toStdString());
  182. require(!result.succeeded
  183. && result.storageError == ProjectStorageError::InvalidJson,
  184. "invalid JSON must be rejected");
  185. require(service.project().metadata.name == "Current project",
  186. "invalid load must keep current project");
  187. writeText(missing_field, R"({"formatVersion":"1.0"})");
  188. result = service.load(missing_field.toStdString());
  189. require(!result.succeeded
  190. && result.storageError == ProjectStorageError::MissingField,
  191. "missing fields must be rejected");
  192. writeText(unsupported_version, R"({"formatVersion":"2.0"})");
  193. result = service.load(unsupported_version.toStdString());
  194. require(!result.succeeded
  195. && result.storageError == ProjectStorageError::UnsupportedVersion,
  196. "unsupported versions must be rejected");
  197. }
  198. void testServiceStateAndSaveErrors()
  199. {
  200. // 保存路径和修改标记只在成功持久化后更新
  201. QTemporaryDir directory;
  202. require(directory.isValid(), "temporary directory must be valid");
  203. JsonProjectStorage storage;
  204. ProjectService service(storage);
  205. require(service.save().error == ProjectServiceError::FilePathRequired,
  206. "save without a current path must be rejected");
  207. require(service.createNewProject(" ").error
  208. == ProjectServiceError::InvalidProjectName,
  209. "blank project names must be rejected");
  210. const QString path = directory.filePath("state.json");
  211. service.editProject().metadata.name = "State project";
  212. require(service.saveAs(path.toStdString()).succeeded,
  213. "state project save must succeed");
  214. service.editProject().metadata.name = "Changed project";
  215. require(service.isModified(), "editing the project must mark it modified");
  216. require(service.save().succeeded, "save must use the current file path");
  217. require(!service.isModified(), "successful save must clear modified state");
  218. const QString failed_path = directory.filePath("missing/subdir/state.json");
  219. require(!service.saveAs(failed_path.toStdString()).succeeded,
  220. "save to an unavailable path must fail");
  221. require(service.currentFilePath() == path.toStdString(),
  222. "failed save as must keep the previous current path");
  223. }
  224. } // namespace
  225. int main()
  226. {
  227. try
  228. {
  229. // 工程服务和 JSON 存储在同一测试进程中验证完整闭环
  230. testEmptyProjectRoundTrip();
  231. testExampleProjectRoundTrip();
  232. testInvalidFiles();
  233. testServiceStateAndSaveErrors();
  234. }
  235. catch (const std::exception &error)
  236. {
  237. std::cerr << "project management tests failed: " << error.what() << '\n';
  238. return 1;
  239. }
  240. std::cout << "project management tests passed\n";
  241. return 0;
  242. }