TestDefinitionContainer.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json # To check files for unnecessarily overridden properties.
  4. import os
  5. import pytest #This module contains automated tests.
  6. from typing import Any, Dict
  7. import uuid
  8. from unittest.mock import patch, MagicMock
  9. import UM.Settings.ContainerRegistry #To create empty instance containers.
  10. import UM.Settings.ContainerStack #To set the container registry the container stacks use.
  11. from UM.Settings.DefinitionContainer import DefinitionContainer #To check against the class of DefinitionContainer.
  12. from UM.Resources import Resources
  13. Resources.addSearchPath(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "resources")))
  14. machine_filepaths = sorted(os.listdir(os.path.join(os.path.dirname(__file__), "..", "..", "resources", "definitions")))
  15. machine_filepaths = [os.path.join(os.path.dirname(__file__), "..", "..", "resources", "definitions", filename) for filename in machine_filepaths]
  16. extruder_filepaths = sorted(os.listdir(os.path.join(os.path.dirname(__file__), "..", "..", "resources", "extruders")))
  17. extruder_filepaths = [os.path.join(os.path.dirname(__file__), "..", "..", "resources", "extruders", filename) for filename in extruder_filepaths]
  18. definition_filepaths = machine_filepaths + extruder_filepaths
  19. all_meshes = os.listdir(os.path.join(os.path.dirname(__file__), "..", "..", "resources", "meshes"))
  20. all_images = os.listdir(os.path.join(os.path.dirname(__file__), "..", "..", "resources", "images"))
  21. # Loading definition files needs a functioning ContainerRegistry
  22. cr = UM.Settings.ContainerRegistry.ContainerRegistry(None)
  23. @pytest.fixture
  24. def definition_container():
  25. uid = str(uuid.uuid4())
  26. result = UM.Settings.DefinitionContainer.DefinitionContainer(uid)
  27. assert result.getId() == uid
  28. return result
  29. ## Tests all definition containers
  30. @pytest.mark.parametrize("file_path", machine_filepaths)
  31. def test_validateMachineDefinitionContainer(file_path, definition_container):
  32. file_name = os.path.basename(file_path)
  33. if file_name == "fdmprinter.def.json" or file_name == "fdmextruder.def.json":
  34. return # Stop checking, these are root files.
  35. from UM.VersionUpgradeManager import FilesDataUpdateResult
  36. mocked_vum = MagicMock()
  37. mocked_vum.updateFilesData = lambda ct, v, fdl, fnl: FilesDataUpdateResult(ct, v, fdl, fnl)
  38. with patch("UM.VersionUpgradeManager.VersionUpgradeManager.getInstance", MagicMock(return_value = mocked_vum)):
  39. assertIsDefinitionValid(definition_container, file_path)
  40. def assertIsDefinitionValid(definition_container, file_path):
  41. with open(file_path, encoding = "utf-8") as data:
  42. json = data.read()
  43. parser, is_valid = definition_container.readAndValidateSerialized(json)
  44. assert is_valid #The definition has invalid JSON structure.
  45. metadata = DefinitionContainer.deserializeMetadata(json, "whatever")
  46. # If the definition defines a platform file, it should be in /resources/meshes/
  47. if "platform" in metadata[0]:
  48. assert metadata[0]["platform"] in all_meshes
  49. if "platform_texture" in metadata[0]:
  50. assert metadata[0]["platform_texture"] in all_images
  51. ## Tests whether setting values are not being hidden by parent containers.
  52. #
  53. # When a definition container defines a "default_value" but inherits from a
  54. # definition that defines a "value", the "default_value" is ineffective. This
  55. # test fails on those things.
  56. @pytest.mark.parametrize("file_path", definition_filepaths)
  57. def test_validateOverridingDefaultValue(file_path: str):
  58. with open(file_path, encoding = "utf-8") as f:
  59. doc = json.load(f)
  60. if "inherits" not in doc:
  61. return # We only want to check for documents where the inheritance overrides the children. If there's no inheritance, this can't happen so it's fine.
  62. if "overrides" not in doc:
  63. return # No settings are being overridden. No need to check anything.
  64. parent_settings = getInheritedSettings(doc["inherits"])
  65. faulty_keys = set()
  66. for key, val in doc["overrides"].items():
  67. if key in parent_settings and "value" in parent_settings[key]:
  68. if "default_value" in val:
  69. faulty_keys.add(key)
  70. assert not faulty_keys, "Unnecessary default_values for {faulty_keys} in {file_name}".format(faulty_keys = sorted(faulty_keys), file_name = file_path) # If there is a value in the parent settings, then the default_value is not effective.
  71. ## Get all settings and their properties from a definition we're inheriting
  72. # from.
  73. # \param definition_id The definition we're inheriting from.
  74. # \return A dictionary of settings by key. Each setting is a dictionary of
  75. # properties.
  76. def getInheritedSettings(definition_id: str) -> Dict[str, Any]:
  77. definition_path = os.path.join(os.path.dirname(__file__), "..", "..", "resources", "definitions", definition_id + ".def.json")
  78. with open(definition_path, encoding = "utf-8") as f:
  79. doc = json.load(f)
  80. result = {}
  81. if "inherits" in doc: # Recursive inheritance.
  82. result.update(getInheritedSettings(doc["inherits"]))
  83. if "settings" in doc:
  84. result.update(flattenSettings(doc["settings"]))
  85. if "overrides" in doc:
  86. result = merge_dicts(result, doc["overrides"])
  87. return result
  88. ## Put all settings in the main dictionary rather than in children dicts.
  89. # \param settings Nested settings. The keys are the setting IDs. The values
  90. # are dictionaries of properties per setting, including the "children"
  91. # property.
  92. # \return A dictionary of settings by key. Each setting is a dictionary of
  93. # properties.
  94. def flattenSettings(settings: Dict[str, Any]) -> Dict[str, Any]:
  95. result = {}
  96. for entry, contents in settings.items():
  97. if "children" in contents:
  98. result.update(flattenSettings(contents["children"]))
  99. del contents["children"]
  100. result[entry] = contents
  101. return result
  102. ## Make one dictionary override the other. Nested dictionaries override each
  103. # other in the same way.
  104. # \param base A dictionary of settings that will get overridden by the other.
  105. # \param overrides A dictionary of settings that will override the other.
  106. # \return Combined setting data.
  107. def merge_dicts(base: Dict[str, Any], overrides: Dict[str, Any]) -> Dict[str, Any]:
  108. result = {}
  109. result.update(base)
  110. for key, val in overrides.items():
  111. if key not in result:
  112. result[key] = val
  113. continue
  114. if isinstance(result[key], dict) and isinstance(val, dict):
  115. result[key] = merge_dicts(result[key], val)
  116. else:
  117. result[key] = val
  118. return result
  119. ## Verifies that definition contains don't have an ID field.
  120. #
  121. # ID fields are legacy. They should not be used any more. This is legacy that
  122. # people don't seem to be able to get used to.
  123. @pytest.mark.parametrize("file_path", definition_filepaths)
  124. def test_noId(file_path: str):
  125. with open(file_path, encoding = "utf-8") as f:
  126. doc = json.load(f)
  127. assert "id" not in doc, "Definitions should not have an ID field."
  128. ## Verifies that extruders say that they work on the same extruder_nr as what
  129. # is listed in their machine definition.
  130. @pytest.mark.parametrize("file_path", extruder_filepaths)
  131. def test_extruderMatch(file_path: str):
  132. extruder_id = os.path.basename(file_path).split(".")[0]
  133. with open(file_path, encoding = "utf-8") as f:
  134. doc = json.load(f)
  135. if "metadata" not in doc:
  136. return # May not be desirable either, but it's probably unfinished then.
  137. if "machine" not in doc["metadata"] or "position" not in doc["metadata"]:
  138. return # FDMextruder doesn't have this since it's not linked to a particular printer.
  139. machine = doc["metadata"]["machine"]
  140. position = doc["metadata"]["position"]
  141. # Find the machine definition.
  142. for machine_filepath in machine_filepaths:
  143. machine_id = os.path.basename(machine_filepath).split(".")[0]
  144. if machine_id == machine:
  145. break
  146. else:
  147. assert False, "The machine ID {machine} is not found.".format(machine = machine)
  148. with open(machine_filepath, encoding = "utf-8") as f:
  149. machine_doc = json.load(f)
  150. # Make sure that the two match up.
  151. assert "metadata" in machine_doc, "Machine definition missing metadata entry."
  152. assert "machine_extruder_trains" in machine_doc["metadata"], "Machine must define extruder trains."
  153. extruder_trains = machine_doc["metadata"]["machine_extruder_trains"]
  154. assert position in extruder_trains, "There must be a reference to the extruder in the machine definition."
  155. assert extruder_trains[position] == extruder_id, "The extruder referenced in the machine definition must match up."
  156. # Also test if the extruder_nr setting is properly overridden.
  157. if "overrides" not in doc or "extruder_nr" not in doc["overrides"] or "default_value" not in doc["overrides"]["extruder_nr"]:
  158. assert position == "0" # Default to 0 is allowed.
  159. assert doc["overrides"]["extruder_nr"]["default_value"] == int(position)