TestDefinitionContainer.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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 os.path
  6. import pytest #This module contains automated tests.
  7. from typing import Any, Dict
  8. import uuid
  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. @pytest.fixture
  22. def definition_container():
  23. uid = str(uuid.uuid4())
  24. result = UM.Settings.DefinitionContainer.DefinitionContainer(uid)
  25. assert result.getId() == uid
  26. return result
  27. ## Tests all definition containers
  28. @pytest.mark.parametrize("file_path", definition_filepaths)
  29. def test_validateMachineDefinitionContainer(file_path, definition_container):
  30. file_name = os.path.basename(file_path)
  31. if file_name == "fdmprinter.def.json" or file_name == "fdmextruder.def.json":
  32. return # Stop checking, these are root files.
  33. assertIsDefinitionValid(definition_container, file_path)
  34. def assertIsDefinitionValid(definition_container, file_path):
  35. with open(file_path, encoding = "utf-8") as data:
  36. json = data.read()
  37. parser, is_valid = definition_container.readAndValidateSerialized(json)
  38. assert is_valid #The definition has invalid JSON structure.
  39. metadata = DefinitionContainer.deserializeMetadata(json, "whatever")
  40. # If the definition defines a platform file, it should be in /resources/meshes/
  41. if "platform" in metadata[0]:
  42. assert metadata[0]["platform"] in all_meshes
  43. if "platform_texture" in metadata[0]:
  44. assert metadata[0]["platform_texture"] in all_images
  45. ## Tests whether setting values are not being hidden by parent containers.
  46. #
  47. # When a definition container defines a "default_value" but inherits from a
  48. # definition that defines a "value", the "default_value" is ineffective. This
  49. # test fails on those things.
  50. @pytest.mark.parametrize("file_path", machine_filepaths)
  51. def test_validateOverridingDefaultValue(file_path: str):
  52. with open(file_path, encoding = "utf-8") as f:
  53. doc = json.load(f)
  54. if "inherits" not in doc:
  55. 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.
  56. if "overrides" not in doc:
  57. return # No settings are being overridden. No need to check anything.
  58. parent_settings = getInheritedSettings(doc["inherits"])
  59. for key, val in doc["overrides"].items():
  60. if "value" in parent_settings[key]:
  61. assert "default_value" not in val, "Unnecessary default_value for {key} in {file_name}".format(key = key, file_name = file_path) # If there is a value in the parent settings, then the default_value is not effective.
  62. ## Get all settings and their properties from a definition we're inheriting
  63. # from.
  64. # \param definition_id The definition we're inheriting from.
  65. # \return A dictionary of settings by key. Each setting is a dictionary of
  66. # properties.
  67. def getInheritedSettings(definition_id: str) -> Dict[str, Any]:
  68. definition_path = os.path.join(os.path.dirname(__file__), "..", "..", "resources", "definitions", definition_id + ".def.json")
  69. with open(definition_path, encoding = "utf-8") as f:
  70. doc = json.load(f)
  71. result = {}
  72. if "inherits" in doc: # Recursive inheritance.
  73. result.update(getInheritedSettings(doc["inherits"]))
  74. if "settings" in doc:
  75. result.update(flattenSettings(doc["settings"]))
  76. if "overrides" in doc:
  77. result = merge_dicts(result, doc["overrides"])
  78. return result
  79. ## Put all settings in the main dictionary rather than in children dicts.
  80. # \param settings Nested settings. The keys are the setting IDs. The values
  81. # are dictionaries of properties per setting, including the "children"
  82. # property.
  83. # \return A dictionary of settings by key. Each setting is a dictionary of
  84. # properties.
  85. def flattenSettings(settings: Dict[str, Any]) -> Dict[str, Any]:
  86. result = {}
  87. for entry, contents in settings.items():
  88. if "children" in contents:
  89. result.update(flattenSettings(contents["children"]))
  90. del contents["children"]
  91. result[entry] = contents
  92. return result
  93. ## Make one dictionary override the other. Nested dictionaries override each
  94. # other in the same way.
  95. # \param base A dictionary of settings that will get overridden by the other.
  96. # \param overrides A dictionary of settings that will override the other.
  97. # \return Combined setting data.
  98. def merge_dicts(base: Dict[str, Any], overrides: Dict[str, Any]) -> Dict[str, Any]:
  99. result = {}
  100. result.update(base)
  101. for key, val in overrides.items():
  102. if key not in result:
  103. result[key] = val
  104. continue
  105. if isinstance(result[key], dict) and isinstance(val, dict):
  106. result[key] = merge_dicts(result[key], val)
  107. else:
  108. result[key] = val
  109. return result
  110. ## Verifies that definition contains don't have an ID field.
  111. #
  112. # ID fields are legacy. They should not be used any more. This is legacy that
  113. # people don't seem to be able to get used to.
  114. @pytest.mark.parametrize("file_path", machine_filepaths)
  115. def test_noId(file_path: str):
  116. with open(file_path, encoding = "utf-8") as f:
  117. doc = json.load(f)
  118. assert "id" not in doc, "Definitions should not have an ID field."