TestCuraContainerRegistry.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os #To find the directory with test files and find the test files.
  4. import pytest #To parameterize tests.
  5. import unittest.mock #To mock and monkeypatch stuff.
  6. from cura.ReaderWriters.ProfileReader import NoProfileException
  7. from cura.Settings.ExtruderStack import ExtruderStack #Testing for returning the correct types of stacks.
  8. from cura.Settings.GlobalStack import GlobalStack #Testing for returning the correct types of stacks.
  9. import UM.Settings.InstanceContainer #Creating instance containers to register.
  10. import UM.Settings.ContainerRegistry #Making empty container stacks.
  11. import UM.Settings.ContainerStack #Setting the container registry here properly.
  12. import cura.CuraApplication
  13. def teardown():
  14. #If the temporary file for the legacy file rename test still exists, remove it.
  15. temporary_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stacks", "temporary.stack.cfg")
  16. if os.path.isfile(temporary_file):
  17. os.remove(temporary_file)
  18. def test_createUniqueName(container_registry):
  19. from cura.CuraApplication import CuraApplication
  20. assert container_registry.createUniqueName("user", "test", "test2", "nope") == "test2"
  21. # Make a conflict (so that "test2" will no longer be an unique name)
  22. instance = UM.Settings.InstanceContainer.InstanceContainer(container_id="test2")
  23. instance.setMetaDataEntry("type", "user")
  24. instance.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  25. container_registry.addContainer(instance)
  26. # It should add a #2 to test2
  27. assert container_registry.createUniqueName("user", "test", "test2", "nope") == "test2 #2"
  28. # The provided suggestion is already correct, so nothing to do
  29. assert container_registry.createUniqueName("user", "test", "test2 #2", "nope") == "test2 #2"
  30. # In case we don't provide a new name, use the fallback
  31. assert container_registry.createUniqueName("user", "test", "", "nope") == "nope"
  32. ## Tests whether addContainer properly converts to ExtruderStack.
  33. def test_addContainerExtruderStack(container_registry, definition_container, definition_changes_container):
  34. container_registry.addContainer(definition_container)
  35. container_registry.addContainer(definition_changes_container)
  36. container_stack = ExtruderStack("Test Extruder Stack") #A container we're going to convert.
  37. container_stack.setMetaDataEntry("type", "extruder_train") #This is now an extruder train.
  38. container_stack.setDefinition(definition_container) #Add a definition to it so it doesn't complain.
  39. container_stack.setDefinitionChanges(definition_changes_container)
  40. mock_super_add_container = unittest.mock.MagicMock() #Takes the role of the Uranium-ContainerRegistry where the resulting containers get registered.
  41. with unittest.mock.patch("UM.Settings.ContainerRegistry.ContainerRegistry.addContainer", mock_super_add_container):
  42. container_registry.addContainer(container_stack)
  43. assert len(mock_super_add_container.call_args_list) == 1 #Called only once.
  44. assert len(mock_super_add_container.call_args_list[0][0]) == 1 #Called with one parameter.
  45. assert type(mock_super_add_container.call_args_list[0][0][0]) == ExtruderStack
  46. ## Tests whether addContainer properly converts to GlobalStack.
  47. def test_addContainerGlobalStack(container_registry, definition_container, definition_changes_container):
  48. container_registry.addContainer(definition_container)
  49. container_registry.addContainer(definition_changes_container)
  50. container_stack = GlobalStack("Test Global Stack") #A container we're going to convert.
  51. container_stack.setMetaDataEntry("type", "machine") #This is now a global stack.
  52. container_stack.setDefinition(definition_container) #Must have a definition.
  53. container_stack.setDefinitionChanges(definition_changes_container) #Must have a definition changes.
  54. mock_super_add_container = unittest.mock.MagicMock() #Takes the role of the Uranium-ContainerRegistry where the resulting containers get registered.
  55. with unittest.mock.patch("UM.Settings.ContainerRegistry.ContainerRegistry.addContainer", mock_super_add_container):
  56. container_registry.addContainer(container_stack)
  57. assert len(mock_super_add_container.call_args_list) == 1 #Called only once.
  58. assert len(mock_super_add_container.call_args_list[0][0]) == 1 #Called with one parameter.
  59. assert type(mock_super_add_container.call_args_list[0][0][0]) == GlobalStack
  60. def test_addContainerGoodSettingVersion(container_registry, definition_container):
  61. from cura.CuraApplication import CuraApplication
  62. definition_container.getMetaData()["setting_version"] = CuraApplication.SettingVersion
  63. container_registry.addContainer(definition_container)
  64. instance = UM.Settings.InstanceContainer.InstanceContainer(container_id = "Test Instance Right Version")
  65. instance.setMetaDataEntry("setting_version", CuraApplication.SettingVersion)
  66. instance.setDefinition(definition_container.getId())
  67. mock_super_add_container = unittest.mock.MagicMock() #Take the role of the Uranium-ContainerRegistry where the resulting containers get registered.
  68. with unittest.mock.patch("UM.Settings.ContainerRegistry.ContainerRegistry.addContainer", mock_super_add_container):
  69. container_registry.addContainer(instance)
  70. mock_super_add_container.assert_called_once_with(instance) #The instance must have been registered now.
  71. def test_addContainerNoSettingVersion(container_registry, definition_container):
  72. from cura.CuraApplication import CuraApplication
  73. definition_container.getMetaData()["setting_version"] = CuraApplication.SettingVersion
  74. container_registry.addContainer(definition_container)
  75. instance = UM.Settings.InstanceContainer.InstanceContainer(container_id = "Test Instance No Version")
  76. #Don't add setting_version metadata.
  77. instance.setDefinition(definition_container.getId())
  78. mock_super_add_container = unittest.mock.MagicMock() #Take the role of the Uranium-ContainerRegistry where the resulting container should not get registered.
  79. with unittest.mock.patch("UM.Settings.ContainerRegistry.ContainerRegistry.addContainer", mock_super_add_container):
  80. container_registry.addContainer(instance)
  81. mock_super_add_container.assert_not_called() #Should not get passed on to UM.Settings.ContainerRegistry.addContainer, because the setting_version is interpreted as 0!
  82. def test_addContainerBadSettingVersion(container_registry, definition_container):
  83. from cura.CuraApplication import CuraApplication
  84. definition_container.getMetaData()["setting_version"] = CuraApplication.SettingVersion
  85. container_registry.addContainer(definition_container)
  86. instance = UM.Settings.InstanceContainer.InstanceContainer(container_id = "Test Instance Wrong Version")
  87. instance.setMetaDataEntry("setting_version", 9001) #Wrong version!
  88. instance.setDefinition(definition_container.getId())
  89. mock_super_add_container = unittest.mock.MagicMock() #Take the role of the Uranium-ContainerRegistry where the resulting container should not get registered.
  90. with unittest.mock.patch("UM.Settings.ContainerRegistry.ContainerRegistry.addContainer", mock_super_add_container):
  91. container_registry.addContainer(instance)
  92. mock_super_add_container.assert_not_called() #Should not get passed on to UM.Settings.ContainerRegistry.addContainer, because the setting_version doesn't match its definition!
  93. test_loadMetaDataValidation_data = [
  94. {
  95. "id": "valid_container",
  96. "is_valid": True,
  97. "metadata": {
  98. "id": "valid_container",
  99. "setting_version": None, #The tests sets this to the current version so it's always correct.
  100. "foo": "bar"
  101. }
  102. },
  103. {
  104. "id": "wrong_setting_version",
  105. "is_valid": False,
  106. "metadata": {
  107. "id": "wrong_setting_version",
  108. "setting_version": "5",
  109. "foo": "bar"
  110. }
  111. },
  112. {
  113. "id": "missing_setting_version",
  114. "is_valid": False,
  115. "metadata": {
  116. "id": "missing_setting_version",
  117. "foo": "bar"
  118. }
  119. },
  120. {
  121. "id": "unparsable_setting_version",
  122. "is_valid": False,
  123. "metadata": {
  124. "id": "unparsable_setting_version",
  125. "setting_version": "Not an integer!",
  126. "foo": "bar"
  127. }
  128. }
  129. ]
  130. @pytest.mark.parametrize("parameters", test_loadMetaDataValidation_data)
  131. def test_loadMetadataValidation(container_registry, definition_container, parameters):
  132. from cura.CuraApplication import CuraApplication
  133. definition_container.getMetaData()["setting_version"] = CuraApplication.SettingVersion
  134. container_registry.addContainer(definition_container)
  135. if "setting_version" in parameters["metadata"] and parameters["metadata"]["setting_version"] is None: #Signal that the setting_version must be set to the currently correct version.
  136. parameters["metadata"]["setting_version"] = CuraApplication.SettingVersion
  137. mock_provider = unittest.mock.MagicMock()
  138. mock_provider.getAllIds = unittest.mock.MagicMock(return_value = [parameters["id"]])
  139. mock_provider.loadMetadata = unittest.mock.MagicMock(return_value = parameters["metadata"])
  140. container_registry._providers = [mock_provider]
  141. container_registry.loadAllMetadata() #Run the test.
  142. if parameters["is_valid"]:
  143. assert parameters["id"] in container_registry.metadata
  144. assert container_registry.metadata[parameters["id"]] == parameters["metadata"]
  145. else:
  146. assert parameters["id"] not in container_registry.metadata
  147. class TestExportQualityProfile:
  148. # This class is just there to provide some grouping for the tests.
  149. def test_exportQualityProfileInvalidFileType(self, container_registry):
  150. # With an invalid file_type, we should get a false for success.
  151. assert not container_registry.exportQualityProfile([], "zomg", "invalid")
  152. def test_exportQualityProfileFailedWriter(self, container_registry):
  153. # Create a writer that always fails.
  154. mocked_writer = unittest.mock.MagicMock(name = "mocked_writer")
  155. mocked_writer.write = unittest.mock.MagicMock(return_value = False)
  156. container_registry._findProfileWriter = unittest.mock.MagicMock("findProfileWriter", return_value = mocked_writer)
  157. # Ensure that it actually fails if the writer did.
  158. with unittest.mock.patch("UM.Application.Application.getInstance"):
  159. assert not container_registry.exportQualityProfile([], "zomg", "test files (*.tst)")
  160. def test_exportQualityProfileExceptionWriter(self, container_registry):
  161. # Create a writer that always fails.
  162. mocked_writer = unittest.mock.MagicMock(name = "mocked_writer")
  163. mocked_writer.write = unittest.mock.MagicMock(return_value = True, side_effect = Exception("Failed :("))
  164. container_registry._findProfileWriter = unittest.mock.MagicMock("findProfileWriter", return_value = mocked_writer)
  165. # Ensure that it actually fails if the writer did.
  166. with unittest.mock.patch("UM.Application.Application.getInstance"):
  167. assert not container_registry.exportQualityProfile([], "zomg", "test files (*.tst)")
  168. def test_exportQualityProfileSuccessWriter(self, container_registry):
  169. # Create a writer that always fails.
  170. mocked_writer = unittest.mock.MagicMock(name="mocked_writer")
  171. mocked_writer.write = unittest.mock.MagicMock(return_value=True)
  172. container_registry._findProfileWriter = unittest.mock.MagicMock("findProfileWriter", return_value=mocked_writer)
  173. # Ensure that it actually fails if the writer did.
  174. with unittest.mock.patch("UM.Application.Application.getInstance"):
  175. assert container_registry.exportQualityProfile([], "zomg", "test files (*.tst)")
  176. def test__findProfileWriterNoPlugins(container_registry):
  177. # Mock it so that no IO plugins are found.
  178. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value = [])
  179. with unittest.mock.patch("UM.PluginRegistry.PluginRegistry.getInstance"):
  180. # Since there are no writers, don't return any
  181. assert container_registry._findProfileWriter(".zomg", "dunno") is None
  182. def test__findProfileWriter(container_registry):
  183. # Mock it so that no IO plugins are found.
  184. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value = [("writer_id", {"profile_writer": [{"extension": ".zomg", "description": "dunno"}]})])
  185. with unittest.mock.patch("UM.PluginRegistry.PluginRegistry.getInstance"):
  186. # In this case it's getting a mocked object (from the mocked_plugin_registry)
  187. assert container_registry._findProfileWriter(".zomg", "dunno") is not None
  188. def test_importProfileEmptyFileName(container_registry):
  189. result = container_registry.importProfile("")
  190. assert result["status"] == "error"
  191. mocked_application = unittest.mock.MagicMock(name = "application")
  192. mocked_plugin_registry = unittest.mock.MagicMock(name="mocked_plugin_registry")
  193. @unittest.mock.patch("UM.Application.Application.getInstance", unittest.mock.MagicMock(return_value = mocked_application))
  194. @unittest.mock.patch("UM.PluginRegistry.PluginRegistry.getInstance", unittest.mock.MagicMock(return_value = mocked_plugin_registry))
  195. class TestImportProfile:
  196. mocked_global_stack = unittest.mock.MagicMock(name="global stack")
  197. mocked_global_stack.extruders = {0: unittest.mock.MagicMock(name="extruder stack")}
  198. mocked_global_stack.getId = unittest.mock.MagicMock(return_value="blarg")
  199. mocked_profile_reader = unittest.mock.MagicMock()
  200. mocked_plugin_registry.getPluginObject = unittest.mock.MagicMock(return_value=mocked_profile_reader)
  201. def test_importProfileWithoutGlobalStack(self, container_registry):
  202. mocked_application.getGlobalContainerStack = unittest.mock.MagicMock(return_value = None)
  203. result = container_registry.importProfile("non_empty")
  204. assert result["status"] == "error"
  205. def test_importProfileNoProfileException(self, container_registry):
  206. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value=[("reader_id", {"profile_reader": [{"extension": "zomg", "description": "dunno"}]})])
  207. mocked_application.getGlobalContainerStack = unittest.mock.MagicMock(return_value=self.mocked_global_stack)
  208. self.mocked_profile_reader.read = unittest.mock.MagicMock(side_effect = NoProfileException)
  209. result = container_registry.importProfile("test.zomg")
  210. # It's not an error, but we also didn't find any profile to read.
  211. assert result["status"] == "ok"
  212. def test_importProfileGenericException(self, container_registry):
  213. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value=[("reader_id", {"profile_reader": [{"extension": "zomg", "description": "dunno"}]})])
  214. mocked_application.getGlobalContainerStack = unittest.mock.MagicMock(return_value=self.mocked_global_stack)
  215. self.mocked_profile_reader.read = unittest.mock.MagicMock(side_effect = Exception)
  216. result = container_registry.importProfile("test.zomg")
  217. assert result["status"] == "error"
  218. def test_importProfileNoDefinitionFound(self, container_registry):
  219. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value=[("reader_id", {"profile_reader": [{"extension": "zomg", "description": "dunno"}]})])
  220. mocked_application.getGlobalContainerStack = unittest.mock.MagicMock(return_value=self.mocked_global_stack)
  221. container_registry.findDefinitionContainers = unittest.mock.MagicMock(return_value = [])
  222. mocked_profile = unittest.mock.MagicMock(name = "Mocked_global_profile")
  223. self.mocked_profile_reader.read = unittest.mock.MagicMock(return_value = [mocked_profile])
  224. result = container_registry.importProfile("test.zomg")
  225. assert result["status"] == "error"
  226. @pytest.mark.skip
  227. def test_importProfileSuccess(self, container_registry):
  228. container_registry._getIOPlugins = unittest.mock.MagicMock(return_value=[("reader_id", {"profile_reader": [{"extension": "zomg", "description": "dunno"}]})])
  229. mocked_application.getGlobalContainerStack = unittest.mock.MagicMock(return_value=self.mocked_global_stack)
  230. mocked_definition = unittest.mock.MagicMock(name = "definition")
  231. container_registry.findContainers = unittest.mock.MagicMock(return_value=[mocked_definition])
  232. container_registry.findDefinitionContainers = unittest.mock.MagicMock(return_value = [mocked_definition])
  233. mocked_profile = unittest.mock.MagicMock(name = "Mocked_global_profile")
  234. self.mocked_profile_reader.read = unittest.mock.MagicMock(return_value = [mocked_profile])
  235. with unittest.mock.patch.object(container_registry, "createUniqueName", return_value="derp"):
  236. with unittest.mock.patch.object(container_registry, "_configureProfile", return_value=None):
  237. result = container_registry.importProfile("test.zomg")
  238. assert result["status"] == "ok"
  239. @pytest.mark.parametrize("metadata,result", [(None, False),
  240. ({}, False),
  241. ({"setting_version": cura.CuraApplication.CuraApplication.SettingVersion}, True),
  242. ({"setting_version": 0}, False)])
  243. def test_isMetaDataValid(container_registry, metadata, result):
  244. assert container_registry._isMetadataValid(metadata) == result
  245. def test_getIOPlugins(container_registry):
  246. plugin_registry = unittest.mock.MagicMock()
  247. plugin_registry.getActivePlugins = unittest.mock.MagicMock(return_value = ["lizard"])
  248. plugin_registry.getMetaData = unittest.mock.MagicMock(return_value = {"zomg": {"test": "test"}})
  249. with unittest.mock.patch("UM.PluginRegistry.PluginRegistry.getInstance", unittest.mock.MagicMock(return_value = plugin_registry)):
  250. assert container_registry._getIOPlugins("zomg") == [("lizard", {"zomg": {"test": "test"}})]