Test with named tuples, not working yet

This commit is contained in:
ChrisTerBeke 2018-11-19 16:35:19 +01:00
parent c04ce7fce8
commit 2497325d60
3 changed files with 53 additions and 107 deletions

View file

@ -1,87 +1,32 @@
# Copyright (c) 2018 Ultimaker B.V. # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher. # Cura is released under the terms of the LGPLv3 or higher.
from typing import Optional from collections import namedtuple
ClusterMaterial = namedtuple('ClusterMaterial', [
'guid',
'material',
'brand',
'version',
'color',
'density'
])
class BaseModel: LocalMaterial = namedtuple('LocalMaterial', [
def __init__(self, **kwargs): 'GUID',
self.__dict__.update(kwargs) 'id',
'type',
def __eq__(self, other): 'status',
return self.__dict__ == other.__dict__ if type(self) == type(other) else False 'base_file',
'setting_version',
'version',
## Represents an item in the cluster API response for installed materials. 'name',
class ClusterMaterial(BaseModel): 'brand',
def __init__(self, **kwargs): 'material',
super().__init__(**kwargs) 'color_name',
self.version = int(self.version) 'description',
self.density = float(self.density) 'adhesion_info',
'approximate_diameter',
guid = None # type: Optional[str] 'properties',
'definition',
material = None # type: Optional[str] 'compatible'
])
brand = None # type: Optional[str]
version = None # type: Optional[int]
color = None # type: Optional[str]
density = None # type: Optional[float]
class LocalMaterialProperties(BaseModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.density = float(self.density)
self.diameter = float(self.diameter)
self.weight = float(self.weight)
density = None # type: Optional[float]
diameter = None # type: Optional[float]
weight = None # type: Optional[int]
class LocalMaterial(BaseModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.properties = LocalMaterialProperties(**self.properties)
self.approximate_diameter = float(self.approximate_diameter)
self.version = int(self.version)
GUID = None # type: Optional[str]
id = None # type: Optional[str]
type = None # type: Optional[str]
status = None # type: Optional[str]
base_file = None # type: Optional[str]
setting_version = None # type: Optional[str]
version = None # type: Optional[int]
name = None # type: Optional[str]
brand = None # type: Optional[str]
material = None # type: Optional[str]
color_name = None # type: Optional[str]
description = None # type: Optional[str]
adhesion_info = None # type: Optional[str]
approximate_diameter = None # type: Optional[float]
properties = None # type: LocalMaterialProperties
definition = None # type: Optional[str]
compatible = None # type: Optional[bool]

View file

@ -156,8 +156,8 @@ class SendMaterialJob(Job):
# \throw KeyError Raised when on of the materials does not include a valid guid # \throw KeyError Raised when on of the materials does not include a valid guid
@classmethod @classmethod
def _parseReply(cls, reply: QNetworkReply) -> Dict[str, ClusterMaterial]: def _parseReply(cls, reply: QNetworkReply) -> Dict[str, ClusterMaterial]:
remote_materials_list = json.loads(reply.readAll().data().decode("utf-8")) remote_materials = json.loads(reply.readAll().data().decode("utf-8"))
return {material["guid"]: ClusterMaterial(**material) for material in remote_materials_list} return {material["id"]: ClusterMaterial(**material) for material in remote_materials}
## Retrieves a list of local materials ## Retrieves a list of local materials
# #
@ -170,12 +170,12 @@ class SendMaterialJob(Job):
material_containers = container_registry.findContainersMetadata(type = "material") material_containers = container_registry.findContainersMetadata(type = "material")
# Find the latest version of all material containers in the registry. # Find the latest version of all material containers in the registry.
for m in material_containers: local_materials = {} # type: Dict[str, LocalMaterial]
for material in material_containers:
try: try:
material = LocalMaterial(**m) material = LocalMaterial(**material)
if material.GUID not in result or material.version > result.get(material.GUID).version: if material.GUID not in result or material.version > result.get(material.GUID).version:
result[material.GUID] = material local_materials[material.GUID] = material
except ValueError: except ValueError:
Logger.logException("w", "Local material {} has invalid values.".format(m["id"])) Logger.logException("w", "Local material {} has invalid values.".format(material["id"]))
return result return result

View file

@ -1,5 +1,7 @@
# Copyright (c) 2018 Ultimaker B.V. # Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher. # Cura is released under the terms of the LGPLv3 or higher.
import json
from typing import Any, List from typing import Any, List
from unittest import TestCase from unittest import TestCase
from unittest.mock import patch, call from unittest.mock import patch, call
@ -108,26 +110,25 @@ class TestSendMaterialJob(TestCase):
job._onGetRemoteMaterials(reply_mock) job._onGetRemoteMaterials(reply_mock)
# We expect the reply to be called once to try to get the printers from the list (readAll()). # We expect the reply to be called once to try to get the printers from the list (readAll()).
# Given that the parsing there fails we do no expect the device to be called for any follow up. # Given that the parsing fails we do no expect the device to be called for any follow up.
self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls) self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
self.assertEqual(0, device_mock.createFormPart.call_count) self.assertEqual(0, device_mock.createFormPart.call_count)
# @patch("PyQt5.QtNetwork.QNetworkReply") @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
# def test_sendMissingMaterials_withMissingGuid(self, reply_mock): @patch("PyQt5.QtNetwork.QNetworkReply")
# reply_mock.attribute.return_value = 200 def test_sendMissingMaterials_withMissingGuid(self, reply_mock, device_mock):
# remoteMaterialWithoutGuid = self._REMOTEMATERIAL_WHITE.copy() reply_mock.attribute.return_value = 200
# del remoteMaterialWithoutGuid["guid"] remote_material_without_guid = self._REMOTE_MATERIAL_WHITE.copy()
# reply_mock.readAll.return_value = QByteArray(json.dumps([remoteMaterialWithoutGuid]).encode("ascii")) del remote_material_without_guid["guid"]
# reply_mock.readAll.return_value = QByteArray(json.dumps([remote_material_without_guid]).encode("ascii"))
# with mock.patch.object(Logger, "log", new=new_log): job = SendMaterialJob(device_mock)
# SendMaterialJob(None).sendMissingMaterials(reply_mock) job._onGetRemoteMaterials(reply_mock)
#
# reply_mock.attribute.assert_called_with(0) # We expect the reply to be called once to try to get the printers from the list (readAll()).
# self.assertEqual(reply_mock.method_calls, [call.attribute(0), call.readAll()]) # Given that parsing fails we do not expect the device to be called for any follow up.
# self._assertLogEntries( self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
# [("e", "Request material storage on printer: Printer"s answer was missing GUIDs.")], self.assertEqual(1, device_mock.createFormPart.call_count)
# _logentries)
#
# @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: []) # @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: [])
# @patch("PyQt5.QtNetwork.QNetworkReply") # @patch("PyQt5.QtNetwork.QNetworkReply")
# def test_sendMissingMaterials_WithInvalidVersionInLocalMaterial(self, reply_mock): # def test_sendMissingMaterials_WithInvalidVersionInLocalMaterial(self, reply_mock):