예제 #1
0
def test_getUsedSettings(data):
    function = SettingFunction(data["code"])
    answer = function.getUsedSettingKeys()
    assert len(answer) == len(data["variables"])
    for variable in data[
            "variables"]:  # Check for set equality regardless of the order.
        assert variable in answer
예제 #2
0
def test_eq():
    setting_function = SettingFunction("3 * 3")
    assert not (setting_function == "some string"
                )  # Equality against something of a different type.
    assert setting_function != "some string"
    assert setting_function == setting_function  # Equality against itself.
    assert not (setting_function != setting_function)

    duplicate = SettingFunction(
        "3 * 3")  # Different instance with the same code. Should be equal!
    assert setting_function == duplicate
    assert not (setting_function != duplicate)

    same_answer = SettingFunction(
        "9")  # Different code but the result is the same. Should NOT be equal!
    assert not (setting_function == same_answer)
    assert setting_function != same_answer
    def _modifyInfillAnglesInSettingDict(self, settings):
        for key, value in settings.items():
            if key == "infill_angles":
                if type(value) is str:
                    value = SettingFunction(value)(self._propertyHandler)
                if len(value) == 0:
                    settings[key] = [self.INFILL_DIRECTION]
                else:
                    settings[key] = [value[0]]

        return settings
예제 #4
0
def setting_function_bad(request):
    return SettingFunction(request.param)
예제 #5
0
def test_str():
    # Due to the simplicity of the function, it's not really necessary to make a full-blown parametrised test for this. Just two simple tests:
    function = SettingFunction("3.14156")  # Simple test case.
    assert str(function) == "=3.14156"
    function = SettingFunction("")  # Also the edge case.
    assert str(function) == "="
예제 #6
0
def test_call(data):
    value_provider = MockValueProvider()
    function = SettingFunction(data["code"])
    assert function(value_provider) == data["result"]
        "label": "Test",
        "default_value": 1,
        "description": "Test Setting",
        "type": "int",
        "unit": "mm"
    }, {
        "unit": "mm"
    }),
    ({
        "label": "Test",
        "default_value": 1,
        "description": "Test Setting",
        "type": "int",
        "value": "10"
    }, {
        "value": SettingFunction("10")
    }),
]


@pytest.mark.parametrize("data,expected", test_basic_properties_data)
def test_basic_properties(data, expected):
    definition = UM.Settings.SettingDefinition.SettingDefinition("test", None)

    definition.deserialize(data)

    for key, value in expected.items():
        assert getattr(definition, key) == value


def test_missing_properties():
예제 #8
0
from unittest.mock import patch, MagicMock

import pytest

from UM.Settings.SettingFunction import SettingFunction
from UM.Settings.SettingInstance import InstanceState
from cura.Settings.SettingInheritanceManager import SettingInheritanceManager

setting_function = SettingFunction("")
setting_function.getUsedSettingKeys = MagicMock(return_value=["omg", "zomg"])

setting_property_dict = {
    "setting_1": {},
    "setting_2": {
        "state": InstanceState.User,
        "enabled": False
    },
    "setting_3": {
        "state": InstanceState.User,
        "enabled": True
    },
    "setting_4": {
        "state": InstanceState.User,
        "enabled": True,
        "value": 12
    },
    "setting_5": {
        "state": InstanceState.User,
        "enabled": True,
        "value": setting_function
    }
    def checkJob(self, machine_name="printer", show_extruder_warnings=False) -> Tuple[pywim.smartslice.job.Job, Dict[str, str]]:

        if len(getPrintableNodes()) == 0:
            return None, {}

        # Create a new instance of errors. We will use this to replace the old errors and
        # emit a signal to replace them
        errors = []

        if len(getPrintableNodes()) != 1:
            errors.append(pywim.smartslice.val.InvalidSetup(
                "Invalid number of printable models on the build tray",
                "Only 1 printable model is currently supported"
            ))

        # We build a new job from scratch evertime - it's easier than trying to manage a whole bunch of changes
        job = pywim.smartslice.job.Job()

        # Extruder Manager
        extruderManager = Application.getInstance().getExtruderManager()
        emActive = extruderManager._active_extruder_index

        # Normal mesh
        normal_mesh = getPrintableNodes()[0]

        # Get all nodes to cycle through
        nodes = [normal_mesh] + getModifierMeshes()

        # Cycle through all of the meshes and check extruder
        for node in nodes:
            active_extruder = getNodeActiveExtruder(node)

            # Build the data for Smart Slice error checking
            mesh = pywim.chop.mesh.Mesh(node.getName())
            mesh.print_config.auxiliary = self._getAuxDict(node.callDecoration("getStack"))
            job.chop.meshes.add(mesh)

            # Check the active extruder
            any_individual_extruder = all(map(lambda k : (int(active_extruder.getProperty(k, "value")) <= 0), ExtruderProperty.EXTRUDER_KEYS))
            if not ( int(active_extruder.getMetaDataEntry("position")) == 0 and int(emActive) == 0 and any_individual_extruder ):
                errors.append(pywim.smartslice.val.InvalidSetup(
                    "Invalid extruder selected for <i>{}</i>".format(node.getName()),
                    "Change active extruder to Extruder 1"
                ))
                show_extruder_warnings = False # Turn the warnings off - we aren't on the right extruder

        # Check the material
        machine_extruder = getNodeActiveExtruder(normal_mesh)
        guid = machine_extruder.material.getMetaData().get("GUID", "")
        material, tested = self.getMaterial(guid)

        if not material:
            errors.append(pywim.smartslice.val.InvalidSetup(
                "Material <i>{}</i> is not currently supported for Smart Slice".format(machine_extruder.material.name),
                "Please select a supported material."
            ))
        else:
            if not tested and show_extruder_warnings:
                self._material_warning.setText(i18n_catalog.i18nc(
                    "@info:status", "Material <b>{}</b> has not been tested for Smart Slice. A generic equivalent will be used.".format(machine_extruder.material.name)
                ))
                self._material_warning.show()

                self.materialWarning.emit(guid)
            elif tested:
                self._material_warning.hide()

            job.bulk.add(
                pywim.fea.model.Material.from_dict(material)
            )

        # Use Cases
        smart_sliceScene_node = findChildSceneNode(getPrintableNodes()[0], Root)
        if smart_sliceScene_node:
            job.chop.steps = smart_sliceScene_node.createSteps()

        # Requirements
        req_tool = SmartSliceRequirements.getInstance()
        job.optimization.min_safety_factor = req_tool.targetSafetyFactor
        job.optimization.max_displacement = req_tool.maxDisplacement

        # Global print config -- assuming only 1 extruder is active for ALL meshes right now
        print_config = pywim.am.Config()
        print_config.layer_height = self._propertyHandler.getGlobalProperty("layer_height")
        print_config.layer_width = self._propertyHandler.getExtruderProperty("line_width")
        print_config.walls = self._propertyHandler.getExtruderProperty("wall_line_count")
        print_config.bottom_layers = self._propertyHandler.getExtruderProperty("top_layers")
        print_config.top_layers = self._propertyHandler.getExtruderProperty("bottom_layers")

        # > https://github.com/Ultimaker/CuraEngine/blob/master/src/FffGcodeWriter.cpp#L402
        skin_angles = self._propertyHandler.getExtruderProperty("skin_angles")
        if type(skin_angles) is str:
            skin_angles = SettingFunction(skin_angles)(self._propertyHandler)
        if len(skin_angles) > 0:
            print_config.skin_orientations.extend(tuple(skin_angles))
        else:
            print_config.skin_orientations.extend((45, 135))

        infill_pattern = self._propertyHandler.getExtruderProperty("infill_pattern")
        print_config.infill.density = self._propertyHandler.getExtruderProperty("infill_sparse_density")
        if infill_pattern in self.INFILL_CURA_SMARTSLICE.keys():
            print_config.infill.pattern = self.INFILL_CURA_SMARTSLICE[infill_pattern]
        else:
            print_config.infill.pattern = infill_pattern # The job validation will handle the error

        # > https://github.com/Ultimaker/CuraEngine/blob/master/src/FffGcodeWriter.cpp#L366
        infill_angles = self._propertyHandler.getExtruderProperty("infill_angles")
        if type(infill_angles) is str:
            infill_angles = SettingFunction(infill_angles)(self._propertyHandler)
        if len(infill_angles) == 0:
            print_config.infill.orientation = self.INFILL_DIRECTION
        else:
            if len(infill_angles) > 1:
                Logger.log("w", "More than one infill angle is set! Only the first will be taken!")
                Logger.log("d", "Ignoring the angles: {}".format(infill_angles[1:]))
            print_config.infill.orientation = infill_angles[0]

        print_config.auxiliary = self._getAuxDict(
            Application.getInstance().getGlobalContainerStack()
        )

        # Extruder config
        extruders = ()
        machine_extruder = getNodeActiveExtruder(normal_mesh)
        for extruder_stack in [machine_extruder]:
            extruder = pywim.chop.machine.Extruder(diameter=extruder_stack.getProperty("machine_nozzle_size", "value"))
            extruder.print_config.auxiliary = self._getAuxDict(extruder_stack)
            extruders += (extruder,)

        printer = pywim.chop.machine.Printer(name=machine_name, extruders=extruders)
        job.chop.slicer = pywim.chop.slicer.CuraEngine(config=print_config, printer=printer)

        # Check the job and add the errors
        errors = errors + job.validate()

        error_dict = {}
        for err in errors:
            error_dict[err.error()] = err.resolution()

        return job, error_dict