TestExtruderStack.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import os.path #To find the test stack files.
  4. import pytest #This module contains automated tests.
  5. import unittest.mock #For the mocking and monkeypatching functionality.
  6. import UM.Settings.ContainerRegistry #To create empty instance containers.
  7. import UM.Settings.ContainerStack #To set the container registry the container stacks use.
  8. from UM.Settings.DefinitionContainer import DefinitionContainer #To check against the class of DefinitionContainer.
  9. from UM.Settings.InstanceContainer import InstanceContainer #To check against the class of InstanceContainer.
  10. import cura.Settings.ExtruderStack #The module we're testing.
  11. from cura.Settings.Exceptions import InvalidContainerError, InvalidOperationError #To check whether the correct exceptions are raised.
  12. ## Fake container registry that always provides all containers you ask of.
  13. @pytest.yield_fixture()
  14. def container_registry():
  15. registry = unittest.mock.MagicMock()
  16. registry.return_value = unittest.mock.NonCallableMagicMock()
  17. registry.findInstanceContainers = lambda *args, registry = registry, **kwargs: [registry.return_value]
  18. registry.findDefinitionContainers = lambda *args, registry = registry, **kwargs: [registry.return_value]
  19. UM.Settings.ContainerRegistry.ContainerRegistry._ContainerRegistry__instance = registry
  20. UM.Settings.ContainerStack._containerRegistry = registry
  21. yield registry
  22. UM.Settings.ContainerRegistry.ContainerRegistry._ContainerRegistry__instance = None
  23. UM.Settings.ContainerStack._containerRegistry = None
  24. ## An empty extruder stack to test with.
  25. @pytest.fixture()
  26. def extruder_stack() -> cura.Settings.ExtruderStack.ExtruderStack:
  27. return cura.Settings.ExtruderStack.ExtruderStack("TestStack")
  28. ## Place-in function for findContainer that finds only containers that start
  29. # with "some_".
  30. def findSomeContainers(container_id = "*", container_type = None, type = None, category = "*"):
  31. if container_id.startswith("some_"):
  32. return UM.Settings.ContainerRegistry._EmptyInstanceContainer(container_id)
  33. if container_type == DefinitionContainer:
  34. definition_mock = unittest.mock.MagicMock()
  35. definition_mock.getId = unittest.mock.MagicMock(return_value = "some_definition") #getId returns some_definition.
  36. return definition_mock
  37. ## Helper function to read the contents of a container stack in the test
  38. # stack folder.
  39. #
  40. # \param filename The name of the file in the "stacks" folder to read from.
  41. # \return The contents of that file.
  42. def readStack(filename):
  43. with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "stacks", filename)) as file_handle:
  44. serialized = file_handle.read()
  45. return serialized
  46. ## Gets an instance container with a specified container type.
  47. #
  48. # \param container_type The type metadata for the instance container.
  49. # \return An instance container instance.
  50. def getInstanceContainer(container_type) -> InstanceContainer:
  51. container = InstanceContainer(container_id = "InstanceContainer")
  52. container.addMetaDataEntry("type", container_type)
  53. return container
  54. class DefinitionContainerSubClass(DefinitionContainer):
  55. def __init__(self):
  56. super().__init__(container_id = "SubDefinitionContainer")
  57. class InstanceContainerSubClass(InstanceContainer):
  58. def __init__(self, container_type):
  59. super().__init__(container_id = "SubInstanceContainer")
  60. self.addMetaDataEntry("type", container_type)
  61. #############################START OF TEST CASES################################
  62. ## Tests whether adding a container is properly forbidden.
  63. def test_addContainer(extruder_stack):
  64. with pytest.raises(InvalidOperationError):
  65. extruder_stack.addContainer(unittest.mock.MagicMock())
  66. #Tests setting user changes profiles to invalid containers.
  67. @pytest.mark.parametrize("container", [
  68. getInstanceContainer(container_type = "wrong container type"),
  69. getInstanceContainer(container_type = "material"), #Existing, but still wrong type.
  70. DefinitionContainer(container_id = "wrong class")
  71. ])
  72. def test_constrainUserChangesInvalid(container, extruder_stack):
  73. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  74. extruder_stack.userChanges = container
  75. #Tests setting user changes profiles.
  76. @pytest.mark.parametrize("container", [
  77. getInstanceContainer(container_type = "user"),
  78. InstanceContainerSubClass(container_type = "user")
  79. ])
  80. def test_constrainUserChangesValid(container, extruder_stack):
  81. extruder_stack.userChanges = container #Should not give an error.
  82. #Tests setting quality changes profiles to invalid containers.
  83. @pytest.mark.parametrize("container", [
  84. getInstanceContainer(container_type = "wrong container type"),
  85. getInstanceContainer(container_type = "material"), #Existing, but still wrong type.
  86. DefinitionContainer(container_id = "wrong class")
  87. ])
  88. def test_constrainQualityChangesInvalid(container, extruder_stack):
  89. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  90. extruder_stack.qualityChanges = container
  91. #Test setting quality changes profiles.
  92. @pytest.mark.parametrize("container", [
  93. getInstanceContainer(container_type = "quality_changes"),
  94. InstanceContainerSubClass(container_type = "quality_changes")
  95. ])
  96. def test_constrainQualityChangesValid(container, extruder_stack):
  97. extruder_stack.qualityChanges = container #Should not give an error.
  98. #Tests setting quality profiles to invalid containers.
  99. @pytest.mark.parametrize("container", [
  100. getInstanceContainer(container_type = "wrong container type"),
  101. getInstanceContainer(container_type = "material"), #Existing, but still wrong type.
  102. DefinitionContainer(container_id = "wrong class")
  103. ])
  104. def test_constrainQualityInvalid(container, extruder_stack):
  105. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  106. extruder_stack.quality = container
  107. #Test setting quality profiles.
  108. @pytest.mark.parametrize("container", [
  109. getInstanceContainer(container_type = "quality"),
  110. InstanceContainerSubClass(container_type = "quality")
  111. ])
  112. def test_constrainQualityValid(container, extruder_stack):
  113. extruder_stack.quality = container #Should not give an error.
  114. #Tests setting materials to invalid containers.
  115. @pytest.mark.parametrize("container", [
  116. getInstanceContainer(container_type = "wrong container type"),
  117. getInstanceContainer(container_type = "quality"), #Existing, but still wrong type.
  118. DefinitionContainer(container_id = "wrong class")
  119. ])
  120. def test_constrainMaterialInvalid(container, extruder_stack):
  121. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  122. extruder_stack.material = container
  123. #Test setting materials.
  124. @pytest.mark.parametrize("container", [
  125. getInstanceContainer(container_type = "material"),
  126. InstanceContainerSubClass(container_type = "material")
  127. ])
  128. def test_constrainMaterialValid(container, extruder_stack):
  129. extruder_stack.material = container #Should not give an error.
  130. #Tests setting variants to invalid containers.
  131. @pytest.mark.parametrize("container", [
  132. getInstanceContainer(container_type = "wrong container type"),
  133. getInstanceContainer(container_type = "material"), #Existing, but still wrong type.
  134. DefinitionContainer(container_id = "wrong class")
  135. ])
  136. def test_constrainVariantInvalid(container, extruder_stack):
  137. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  138. extruder_stack.variant = container
  139. #Test setting variants.
  140. @pytest.mark.parametrize("container", [
  141. getInstanceContainer(container_type = "variant"),
  142. InstanceContainerSubClass(container_type = "variant")
  143. ])
  144. def test_constrainVariantValid(container, extruder_stack):
  145. extruder_stack.variant = container #Should not give an error.
  146. #Tests setting definitions to invalid containers.
  147. @pytest.mark.parametrize("container", [
  148. getInstanceContainer(container_type = "wrong class"),
  149. getInstanceContainer(container_type = "material"), #Existing, but still wrong class.
  150. ])
  151. def test_constrainVariantInvalid(container, extruder_stack):
  152. with pytest.raises(InvalidContainerError): #Invalid container, should raise an error.
  153. extruder_stack.definition = container
  154. #Test setting definitions.
  155. @pytest.mark.parametrize("container", [
  156. DefinitionContainer(container_id = "DefinitionContainer"),
  157. DefinitionContainerSubClass()
  158. ])
  159. def test_constrainDefinitionValid(container, extruder_stack):
  160. extruder_stack.definition = container #Should not give an error.
  161. ## Tests whether deserialising completes the missing containers with empty
  162. # ones.
  163. @pytest.mark.skip #The test currently fails because the definition container doesn't have a category, which is wrong but we don't have time to refactor that right now.
  164. def test_deserializeCompletesEmptyContainers(extruder_stack: cura.Settings.ExtruderStack):
  165. extruder_stack._containers = [DefinitionContainer(container_id = "definition")] #Set the internal state of this stack manually.
  166. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  167. extruder_stack.deserialize("")
  168. assert len(extruder_stack.getContainers()) == len(cura.Settings.CuraContainerStack._ContainerIndexes.IndexTypeMap) #Needs a slot for every type.
  169. for container_type_index in cura.Settings.CuraContainerStack._ContainerIndexes.IndexTypeMap:
  170. if container_type_index == cura.Settings.CuraContainerStack._ContainerIndexes.Definition: #We're not checking the definition.
  171. continue
  172. assert extruder_stack.getContainer(container_type_index).getId() == "empty" #All others need to be empty.
  173. ## Tests whether an instance container with the wrong type gets removed when
  174. # deserialising.
  175. def test_deserializeRemovesWrongInstanceContainer(extruder_stack):
  176. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Quality] = getInstanceContainer(container_type = "wrong type")
  177. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Definition] = DefinitionContainer(container_id = "some definition")
  178. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  179. extruder_stack.deserialize("")
  180. assert extruder_stack.quality == extruder_stack._empty_instance_container #Replaced with empty.
  181. ## Tests whether a container with the wrong class gets removed when
  182. # deserialising.
  183. def test_deserializeRemovesWrongContainerClass(extruder_stack):
  184. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Quality] = DefinitionContainer(container_id = "wrong class")
  185. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Definition] = DefinitionContainer(container_id = "some definition")
  186. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  187. extruder_stack.deserialize("")
  188. assert extruder_stack.quality == extruder_stack._empty_instance_container #Replaced with empty.
  189. ## Tests whether an instance container in the definition spot results in an
  190. # error.
  191. def test_deserializeWrongDefinitionClass(extruder_stack):
  192. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Definition] = getInstanceContainer(container_type = "definition") #Correct type but wrong class.
  193. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  194. with pytest.raises(UM.Settings.ContainerStack.InvalidContainerStackError): #Must raise an error that there is no definition container.
  195. extruder_stack.deserialize("")
  196. ## Tests whether an instance container with the wrong type is moved into the
  197. # correct slot by deserialising.
  198. def test_deserializeMoveInstanceContainer(extruder_stack):
  199. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Quality] = getInstanceContainer(container_type = "material") #Not in the correct spot.
  200. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Definition] = DefinitionContainer(container_id = "some definition")
  201. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  202. extruder_stack.deserialize("")
  203. assert extruder_stack.quality.getId() == "empty"
  204. assert extruder_stack.material.getId() != "empty"
  205. ## Tests whether a definition container in the wrong spot is moved into the
  206. # correct spot by deserialising.
  207. @pytest.mark.skip #The test currently fails because the definition container doesn't have a category, which is wrong but we don't have time to refactor that right now.
  208. def test_deserializeMoveDefinitionContainer(extruder_stack):
  209. extruder_stack._containers[cura.Settings.CuraContainerStack._ContainerIndexes.Material] = DefinitionContainer(container_id = "some definition") #Not in the correct spot.
  210. with unittest.mock.patch("UM.Settings.ContainerStack.ContainerStack.deserialize", unittest.mock.MagicMock()): #Prevent calling super().deserialize.
  211. extruder_stack.deserialize("")
  212. assert extruder_stack.material.getId() == "empty"
  213. assert extruder_stack.definition.getId() != "empty"
  214. UM.Settings.ContainerStack._containerRegistry = None
  215. ## Tests whether getProperty properly applies the stack-like behaviour on its
  216. # containers.
  217. def test_getPropertyFallThrough(extruder_stack):
  218. #A few instance container mocks to put in the stack.
  219. mock_layer_heights = {} #For each container type, a mock container that defines layer height to something unique.
  220. mock_no_settings = {} #For each container type, a mock container that has no settings at all.
  221. container_indices = cura.Settings.CuraContainerStack._ContainerIndexes #Cache.
  222. for type_id, type_name in container_indices.IndexTypeMap.items():
  223. container = unittest.mock.MagicMock()
  224. container.getProperty = lambda key, property, type_id = type_id: type_id if (key == "layer_height" and property == "value") else None #Returns the container type ID as layer height, in order to identify it.
  225. container.hasProperty = lambda key, property: key == "layer_height"
  226. container.getMetaDataEntry = unittest.mock.MagicMock(return_value = type_name)
  227. mock_layer_heights[type_id] = container
  228. container = unittest.mock.MagicMock()
  229. container.getProperty = unittest.mock.MagicMock(return_value = None) #Has no settings at all.
  230. container.hasProperty = unittest.mock.MagicMock(return_value = False)
  231. container.getMetaDataEntry = unittest.mock.MagicMock(return_value = type_name)
  232. mock_no_settings[type_id] = container
  233. extruder_stack.userChanges = mock_no_settings[container_indices.UserChanges]
  234. extruder_stack.qualityChanges = mock_no_settings[container_indices.QualityChanges]
  235. extruder_stack.quality = mock_no_settings[container_indices.Quality]
  236. extruder_stack.material = mock_no_settings[container_indices.Material]
  237. extruder_stack.variant = mock_no_settings[container_indices.Variant]
  238. with unittest.mock.patch("cura.Settings.CuraContainerStack.DefinitionContainer", unittest.mock.MagicMock): #To guard against the type checking.
  239. extruder_stack.definition = mock_layer_heights[container_indices.Definition] #There's a layer height in here!
  240. assert extruder_stack.getProperty("layer_height", "value") == container_indices.Definition
  241. extruder_stack.variant = mock_layer_heights[container_indices.Variant]
  242. assert extruder_stack.getProperty("layer_height", "value") == container_indices.Variant
  243. extruder_stack.material = mock_layer_heights[container_indices.Material]
  244. assert extruder_stack.getProperty("layer_height", "value") == container_indices.Material
  245. extruder_stack.quality = mock_layer_heights[container_indices.Quality]
  246. assert extruder_stack.getProperty("layer_height", "value") == container_indices.Quality
  247. extruder_stack.qualityChanges = mock_layer_heights[container_indices.QualityChanges]
  248. assert extruder_stack.getProperty("layer_height", "value") == container_indices.QualityChanges
  249. extruder_stack.userChanges = mock_layer_heights[container_indices.UserChanges]
  250. assert extruder_stack.getProperty("layer_height", "value") == container_indices.UserChanges
  251. ## Tests whether inserting a container is properly forbidden.
  252. def test_insertContainer(extruder_stack):
  253. with pytest.raises(InvalidOperationError):
  254. extruder_stack.insertContainer(0, unittest.mock.MagicMock())
  255. ## Tests whether removing a container is properly forbidden.
  256. def test_removeContainer(extruder_stack):
  257. with pytest.raises(InvalidOperationError):
  258. extruder_stack.removeContainer(unittest.mock.MagicMock())
  259. ## Tests setting definitions by specifying an ID of a definition that exists.
  260. def test_setDefinitionByIdExists(extruder_stack, container_registry):
  261. container_registry.return_value = DefinitionContainer(container_id = "some_definition")
  262. extruder_stack.setDefinitionById("some_definition")
  263. assert extruder_stack.definition.getId() == "some_definition"
  264. ## Tests setting definitions by specifying an ID of a definition that doesn't
  265. # exist.
  266. def test_setDefinitionByIdDoesntExist(extruder_stack):
  267. with pytest.raises(InvalidContainerError):
  268. extruder_stack.setDefinitionById("some_definition") #Container registry is empty now.
  269. ## Tests setting materials by specifying an ID of a material that exists.
  270. def test_setMaterialByIdExists(extruder_stack, container_registry):
  271. container_registry.return_value = getInstanceContainer(container_type = "material")
  272. extruder_stack.setMaterialById("InstanceContainer")
  273. assert extruder_stack.material.getId() == "InstanceContainer"
  274. ## Tests setting materials by specifying an ID of a material that doesn't
  275. # exist.
  276. def test_setMaterialByIdDoesntExist(extruder_stack):
  277. with pytest.raises(InvalidContainerError):
  278. extruder_stack.setMaterialById("some_material") #Container registry is empty now.
  279. ## Tests setting properties directly on the extruder stack.
  280. @pytest.mark.parametrize("key, property, value", [
  281. ("layer_height", "value", 0.1337),
  282. ("foo", "value", 100),
  283. ("support_enabled", "value", True),
  284. ("layer_height", "default_value", 0.1337),
  285. ("layer_height", "is_bright_pink", "of course")
  286. ])
  287. def test_setPropertyUser(key, property, value, extruder_stack):
  288. user_changes = unittest.mock.MagicMock()
  289. user_changes.getMetaDataEntry = unittest.mock.MagicMock(return_value = "user")
  290. extruder_stack.userChanges = user_changes
  291. extruder_stack.setProperty(key, property, value) #The actual test.
  292. extruder_stack.userChanges.setProperty.assert_called_once_with(key, property, value) #Make sure that the user container gets a setProperty call.
  293. ## Tests setting properties on specific containers on the global stack.
  294. @pytest.mark.parametrize("target_container, stack_variable", [
  295. ("user", "userChanges"),
  296. ("quality_changes", "qualityChanges"),
  297. ("quality", "quality"),
  298. ("material", "material"),
  299. ("variant", "variant")
  300. ])
  301. def test_setPropertyOtherContainers(target_container, stack_variable, extruder_stack):
  302. #Other parameters that don't need to be varied.
  303. key = "layer_height"
  304. property = "value"
  305. value = 0.1337
  306. #A mock container in the right spot.
  307. container = unittest.mock.MagicMock()
  308. container.getMetaDataEntry = unittest.mock.MagicMock(return_value = target_container)
  309. setattr(extruder_stack, stack_variable, container) #For instance, set global_stack.qualityChanges = container.
  310. extruder_stack.setProperty(key, property, value, target_container = target_container) #The actual test.
  311. getattr(extruder_stack, stack_variable).setProperty.assert_called_once_with(key, property, value) #Make sure that the proper container gets a setProperty call.
  312. ## Tests setting qualities by specifying an ID of a quality that exists.
  313. def test_setQualityByIdExists(extruder_stack, container_registry):
  314. container_registry.return_value = getInstanceContainer(container_type = "quality")
  315. extruder_stack.setQualityById("InstanceContainer")
  316. assert extruder_stack.quality.getId() == "InstanceContainer"
  317. ## Tests setting qualities by specifying an ID of a quality that doesn't exist.
  318. def test_setQualityByIdDoesntExist(extruder_stack):
  319. with pytest.raises(InvalidContainerError):
  320. extruder_stack.setQualityById("some_quality") #Container registry is empty now.
  321. ## Tests setting quality changes by specifying an ID of a quality change that
  322. # exists.
  323. def test_setQualityChangesByIdExists(extruder_stack, container_registry):
  324. container_registry.return_value = getInstanceContainer(container_type = "quality_changes")
  325. extruder_stack.setQualityChangesById("InstanceContainer")
  326. assert extruder_stack.qualityChanges.getId() == "InstanceContainer"
  327. ## Tests setting quality changes by specifying an ID of a quality change that
  328. # doesn't exist.
  329. def test_setQualityChangesByIdDoesntExist(extruder_stack):
  330. with pytest.raises(InvalidContainerError):
  331. extruder_stack.setQualityChangesById("some_quality_changes") #Container registry is empty now.
  332. ## Tests setting variants by specifying an ID of a variant that exists.
  333. def test_setVariantByIdExists(extruder_stack, container_registry):
  334. container_registry.return_value = getInstanceContainer(container_type = "variant")
  335. extruder_stack.setVariantById("InstanceContainer")
  336. assert extruder_stack.variant.getId() == "InstanceContainer"
  337. ## Tests setting variants by specifying an ID of a variant that doesn't exist.
  338. def test_setVariantByIdDoesntExist(extruder_stack):
  339. with pytest.raises(InvalidContainerError):
  340. extruder_stack.setVariantById("some_variant") #Container registry is empty now.