Made the tests work with the named tuples

Tests only use the _onGetRemoteMaterial
This commit is contained in:
Marijn Deé 2018-11-20 16:34:11 +01:00
parent 481ca8cd2f
commit ca60744292

View file

@ -1,53 +1,23 @@
# 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 io
import json import json
from unittest import TestCase, mock
from typing import Any, List
from unittest import TestCase
from unittest.mock import patch, call from unittest.mock import patch, call
from PyQt5.QtCore import QByteArray from PyQt5.QtCore import QByteArray
from UM.Settings.ContainerRegistry import ContainerInterface, ContainerRegistryInterface, DefinitionContainerInterface from UM.MimeTypeDatabase import MimeType
from plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice import ClusterUM3OutputDevice from cura.CuraApplication import CuraApplication
from plugins.UM3NetworkPrinting.src.SendMaterialJob import SendMaterialJob from plugins.UM3NetworkPrinting.src.SendMaterialJob import SendMaterialJob
class ContainerRegistryMock(ContainerRegistryInterface): @patch("builtins.open", lambda _, __: io.StringIO("<xml></xml>"))
@patch("UM.MimeTypeDatabase.MimeTypeDatabase.getMimeTypeForFile",
def __init__(self): lambda _: MimeType(name = "application/x-ultimaker-material-profile", comment = "Ultimaker Material Profile",
self.containersMetaData = None suffixes = ["xml.fdm_material"]))
@patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: ["/materials/generic_pla_white.xml.fdm_material"])
def findContainers(self, *, ignore_case: bool = False, **kwargs: Any) -> List[ContainerInterface]:
raise NotImplementedError()
def findDefinitionContainers(self, **kwargs: Any) -> List[DefinitionContainerInterface]:
raise NotImplementedError()
@classmethod
def getApplication(cls) -> "Application":
raise NotImplementedError()
def getEmptyInstanceContainer(self) -> "InstanceContainer":
raise NotImplementedError()
def isReadOnly(self, container_id: str) -> bool:
raise NotImplementedError()
def setContainersMetadata(self, value):
self.containersMetaData = value
def findContainersMetadata(self, type):
return self.containersMetaData
class MockOutputDevice(ClusterUM3OutputDevice):
def _createFormPart(self, content_header, data, content_type=None):
return "xxx"
class TestSendMaterialJob(TestCase): class TestSendMaterialJob(TestCase):
_LOCAL_MATERIAL_WHITE = {"type": "material", "status": "unknown", "id": "generic_pla_white", _LOCAL_MATERIAL_WHITE = {"type": "material", "status": "unknown", "id": "generic_pla_white",
"base_file": "generic_pla_white", "setting_version": 5, "name": "White PLA", "base_file": "generic_pla_white", "setting_version": 5, "name": "White PLA",
"brand": "Generic", "material": "PLA", "color_name": "White", "brand": "Generic", "material": "PLA", "color_name": "White",
@ -92,7 +62,7 @@ class TestSendMaterialJob(TestCase):
@patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice") @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
@patch("PyQt5.QtNetwork.QNetworkReply") @patch("PyQt5.QtNetwork.QNetworkReply")
def test_sendMissingMaterials_withFailedRequest(self, reply_mock, device_mock): def test__onGetRemoteMaterials_withFailedRequest(self, reply_mock, device_mock):
reply_mock.attribute.return_value = 404 reply_mock.attribute.return_value = 404
job = SendMaterialJob(device_mock) job = SendMaterialJob(device_mock)
job._onGetRemoteMaterials(reply_mock) job._onGetRemoteMaterials(reply_mock)
@ -103,7 +73,7 @@ class TestSendMaterialJob(TestCase):
@patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice") @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
@patch("PyQt5.QtNetwork.QNetworkReply") @patch("PyQt5.QtNetwork.QNetworkReply")
def test_sendMissingMaterials_withBadJsonAnswer(self, reply_mock, device_mock): def test__onGetRemoteMaterials_withBadJsonAnswer(self, reply_mock, device_mock):
reply_mock.attribute.return_value = 200 reply_mock.attribute.return_value = 200
reply_mock.readAll.return_value = QByteArray(b"Six sick hicks nick six slick bricks with picks and sticks.") reply_mock.readAll.return_value = QByteArray(b"Six sick hicks nick six slick bricks with picks and sticks.")
job = SendMaterialJob(device_mock) job = SendMaterialJob(device_mock)
@ -116,7 +86,7 @@ class TestSendMaterialJob(TestCase):
@patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice") @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
@patch("PyQt5.QtNetwork.QNetworkReply") @patch("PyQt5.QtNetwork.QNetworkReply")
def test_sendMissingMaterials_withMissingGuid(self, reply_mock, device_mock): def test__onGetRemoteMaterials_withMissingGuidInRemoteMaterial(self, reply_mock, device_mock):
reply_mock.attribute.return_value = 200 reply_mock.attribute.return_value = 200
remote_material_without_guid = self._REMOTE_MATERIAL_WHITE.copy() remote_material_without_guid = self._REMOTE_MATERIAL_WHITE.copy()
del remote_material_without_guid["guid"] del remote_material_without_guid["guid"]
@ -127,151 +97,114 @@ class TestSendMaterialJob(TestCase):
# 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 parsing fails we do not expect the device to be called for any follow up. # Given that parsing fails we do not 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(1, device_mock.createFormPart.call_count) self.assertEqual(0, device_mock.createFormPart.call_count)
# @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: []) @patch("cura.Settings.CuraContainerRegistry")
# @patch("PyQt5.QtNetwork.QNetworkReply") @patch("cura.CuraApplication")
# def test_sendMissingMaterials_WithInvalidVersionInLocalMaterial(self, reply_mock): @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
# reply_mock.attribute.return_value = 200 @patch("PyQt5.QtNetwork.QNetworkReply")
# reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTEMATERIAL_WHITE]).encode("ascii")) def test__onGetRemoteMaterials_withInvalidVersionInLocalMaterial(self, reply_mock, device_mock, application_mock,
# container_registry_mock):
# containerRegistry = ContainerRegistryMock() reply_mock.attribute.return_value = 200
# localMaterialWhiteWithInvalidVersion = self._LOCALMATERIAL_WHITE.copy() reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTE_MATERIAL_WHITE]).encode("ascii"))
# localMaterialWhiteWithInvalidVersion["version"] = "one"
# containerRegistry.setContainersMetadata([localMaterialWhiteWithInvalidVersion]) localMaterialWhiteWithInvalidVersion = self._LOCAL_MATERIAL_WHITE.copy()
# localMaterialWhiteWithInvalidVersion["version"] = "one"
# with mock.patch.object(Logger, "log", new=new_log): container_registry_mock.findContainersMetadata.return_value = [localMaterialWhiteWithInvalidVersion]
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry):
# SendMaterialJob(None).sendMissingMaterials(reply_mock) application_mock.getContainerRegistry.return_value = container_registry_mock
#
# reply_mock.attribute.assert_called_with(0) with mock.patch.object(CuraApplication, "getInstance", new = lambda: application_mock):
# self.assertEqual(reply_mock.method_calls, [call.attribute(0), call.readAll()]) job = SendMaterialJob(device_mock)
# self._assertLogEntries([("e", "Material generic_pla_white has invalid version number one.")], _logentries) job._onGetRemoteMaterials(reply_mock)
#
# @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: []) self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
# @patch("PyQt5.QtNetwork.QNetworkReply") self.assertEqual([call.getContainerRegistry()], application_mock.method_calls)
# def test_sendMissingMaterials_WithMultipleLocalVersionsLowFirst(self, reply_mock): self.assertEqual([call.findContainersMetadata(type = "material")], container_registry_mock.method_calls)
# reply_mock.attribute.return_value = 200 self.assertEqual(0, device_mock.createFormPart.call_count)
# reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTEMATERIAL_WHITE]).encode("ascii"))
# @patch("cura.Settings.CuraContainerRegistry")
# containerRegistry = ContainerRegistryMock() @patch("cura.CuraApplication")
# localMaterialWhiteWithHigherVersion = self._LOCALMATERIAL_WHITE.copy() @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
# localMaterialWhiteWithHigherVersion["version"] = "2" @patch("PyQt5.QtNetwork.QNetworkReply")
# containerRegistry.setContainersMetadata([self._LOCALMATERIAL_WHITE, localMaterialWhiteWithHigherVersion]) def test__onGetRemoteMaterials_withNoUpdate(self, reply_mock, device_mock, application_mock,
# container_registry_mock):
# with mock.patch.object(Logger, "log", new=new_log): application_mock.getContainerRegistry.return_value = container_registry_mock
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry):
# SendMaterialJob(None).sendMissingMaterials(reply_mock) device_mock.createFormPart.return_value = "_xXx_"
#
# reply_mock.attribute.assert_called_with(0) container_registry_mock.findContainersMetadata.return_value = [self._LOCAL_MATERIAL_WHITE]
# self.assertEqual(reply_mock.method_calls, [call.attribute(0), call.readAll()])
# self._assertLogEntries([], _logentries) reply_mock.attribute.return_value = 200
# reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTE_MATERIAL_WHITE]).encode("ascii"))
# @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: [])
# @patch("PyQt5.QtNetwork.QNetworkReply") with mock.patch.object(CuraApplication, "getInstance", new = lambda: application_mock):
# def test_sendMissingMaterials_MaterialMissingOnPrinter(self, reply_mock): job = SendMaterialJob(device_mock)
# reply_mock.attribute.return_value = 200 job._onGetRemoteMaterials(reply_mock)
# reply_mock.readAll.return_value = QByteArray(
# json.dumps([self._REMOTEMATERIAL_WHITE]).encode("ascii")) self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
# self.assertEqual([call.getContainerRegistry()], application_mock.method_calls)
# containerRegistry = ContainerRegistryMock() self.assertEqual([call.findContainersMetadata(type = "material")], container_registry_mock.method_calls)
# containerRegistry.setContainersMetadata([self._LOCALMATERIAL_WHITE, self._LOCALMATERIAL_BLACK]) self.assertEqual(0, device_mock.createFormPart.call_count)
# self.assertEqual(0, device_mock.postFormWithParts.call_count)
# with mock.patch.object(Logger, "log", new=new_log):
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry): @patch("cura.Settings.CuraContainerRegistry")
# SendMaterialJob(None).sendMissingMaterials(reply_mock) @patch("cura.CuraApplication")
# @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
# reply_mock.attribute.assert_called_with(0) @patch("PyQt5.QtNetwork.QNetworkReply")
# self.assertEqual(reply_mock.method_calls, [call.attribute(0), call.readAll()]) def test__onGetRemoteMaterials_withUpdatedMaterial(self, reply_mock, device_mock, application_mock,
# self._assertLogEntries([], _logentries) container_registry_mock):
# application_mock.getContainerRegistry.return_value = container_registry_mock
# @patch("builtins.open", lambda a, b: io.StringIO("<xml></xml>"))
# @patch("UM.MimeTypeDatabase.MimeTypeDatabase.getMimeTypeForFile", device_mock.createFormPart.return_value = "_xXx_"
# lambda _: MimeType(name="application/x-ultimaker-material-profile", comment="Ultimaker Material Profile",
# suffixes=["xml.fdm_material"])) localMaterialWhiteWithHigherVersion = self._LOCAL_MATERIAL_WHITE.copy()
# @patch("UM.Resources.Resources.getAllResourcesOfType", lambda _: ["/materials/generic_pla_white.xml.fdm_material"]) localMaterialWhiteWithHigherVersion["version"] = "2"
# @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice") container_registry_mock.findContainersMetadata.return_value = [localMaterialWhiteWithHigherVersion]
# def test_sendMaterialsToPrinter(self, device_mock):
# device_mock._createFormPart.return_value = "_xXx_" reply_mock.attribute.return_value = 200
# with mock.patch.object(Logger, "log", new=new_log): reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTE_MATERIAL_WHITE]).encode("ascii"))
# job = SendMaterialJob(device_mock)
# job.sendMaterialsToPrinter({"generic_pla_white"}) with mock.patch.object(CuraApplication, "getInstance", new = lambda: application_mock):
# job = SendMaterialJob(device_mock)
# self._assertLogEntries([("d", "Syncing material generic_pla_white with cluster.")], _logentries) job._onGetRemoteMaterials(reply_mock)
# self.assertEqual([call._createFormPart("name="file"; filename="generic_pla_white.xml.fdm_material"", "<xml></xml>"),
# call.postFormWithParts(on_finished=job.sendingFinished, parts = ["_xXx_"], target = "materials/")], device_mock.method_calls) self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
# self.assertEqual([call.getContainerRegistry()], application_mock.method_calls)
# @patch("PyQt5.QtNetwork.QNetworkReply") self.assertEqual([call.findContainersMetadata(type = "material")], container_registry_mock.method_calls)
# def test_sendingFinished_success(self, reply_mock) -> None: self.assertEqual(1, device_mock.createFormPart.call_count)
# reply_mock.attribute.return_value = 200 self.assertEqual(1, device_mock.postFormWithParts.call_count)
# with mock.patch.object(Logger, "log", new=new_log): self.assertEquals(
# SendMaterialJob(None).sendingFinished(reply_mock) [call.createFormPart("name=\"file\"; filename=\"generic_pla_white.xml.fdm_material\"", "<xml></xml>"),
# call.postFormWithParts(target = "materials/", parts = ["_xXx_"], on_finished = job.sendingFinished)],
# reply_mock.attribute.assert_called_once_with(0) device_mock.method_calls)
# self.assertEqual(0, len(_logentries))
# @patch("cura.Settings.CuraContainerRegistry")
# @patch("PyQt5.QtNetwork.QNetworkReply") @patch("cura.CuraApplication")
# def test_sendingFinished_failed(self, reply_mock) -> None: @patch("plugins.UM3NetworkPrinting.src.ClusterUM3OutputDevice")
# reply_mock.attribute.return_value = 404 @patch("PyQt5.QtNetwork.QNetworkReply")
# reply_mock.readAll.return_value = QByteArray(b"Six sick hicks nick six slick bricks with picks and sticks.") def test__onGetRemoteMaterials_withNewMaterial(self, reply_mock, device_mock, application_mock,
# container_registry_mock):
# with mock.patch.object(Logger, "log", new=new_log): application_mock.getContainerRegistry.return_value = container_registry_mock
# SendMaterialJob(None).sendingFinished(reply_mock)
# device_mock.createFormPart.return_value = "_xXx_"
# reply_mock.attribute.assert_called_with(0)
# self.assertEqual(reply_mock.method_calls, [call.attribute(0), call.attribute(0), call.readAll()]) container_registry_mock.findContainersMetadata.return_value = [self._LOCAL_MATERIAL_WHITE,
# self._LOCAL_MATERIAL_BLACK]
# self._assertLogEntries([
# ("e", "Received error code from printer when syncing material: 404"), reply_mock.attribute.return_value = 200
# ("e", "Six sick hicks nick six slick bricks with picks and sticks.") reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTE_MATERIAL_BLACK]).encode("ascii"))
# ], _logentries)
# with mock.patch.object(CuraApplication, "getInstance", new = lambda: application_mock):
# @patch("PyQt5.QtNetwork.QNetworkReply") job = SendMaterialJob(device_mock)
# def test_parseReply(self, reply_mock): job._onGetRemoteMaterials(reply_mock)
# reply_mock.readAll.return_value = QByteArray(json.dumps([self._REMOTEMATERIAL_WHITE]).encode("ascii"))
# self.assertEqual([call.attribute(0), call.readAll()], reply_mock.method_calls)
# response = SendMaterialJob._parseReply(reply_mock) self.assertEqual([call.getContainerRegistry()], application_mock.method_calls)
# self.assertEqual([call.findContainersMetadata(type = "material")], container_registry_mock.method_calls)
# self.assertTrue(len(response) == 1) self.assertEqual(1, device_mock.createFormPart.call_count)
# self.assertEqual(next(iter(response.values())), ClusterMaterial(**self._REMOTEMATERIAL_WHITE)) self.assertEqual(1, device_mock.postFormWithParts.call_count)
# self.assertEquals(
# @patch("PyQt5.QtNetwork.QNetworkReply") [call.createFormPart("name=\"file\"; filename=\"generic_pla_white.xml.fdm_material\"", "<xml></xml>"),
# def test_parseReplyWithInvalidMaterial(self, reply_mock): call.postFormWithParts(target = "materials/", parts = ["_xXx_"], on_finished = job.sendingFinished)],
# remoteMaterialWithInvalidVersion = self._REMOTEMATERIAL_WHITE.copy() device_mock.method_calls)
# remoteMaterialWithInvalidVersion["version"] = "one"
# reply_mock.readAll.return_value = QByteArray(json.dumps([remoteMaterialWithInvalidVersion]).encode("ascii"))
#
# with self.assertRaises(ValueError):
# SendMaterialJob._parseReply(reply_mock)
#
# def test__getLocalMaterials(self):
# containerRegistry = ContainerRegistryMock()
# containerRegistry.setContainersMetadata([self._LOCALMATERIAL_WHITE, self._LOCALMATERIAL_BLACK])
#
# with mock.patch.object(Logger, "log", new=new_log):
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry):
# local_materials = SendMaterialJob(None)._getLocalMaterials()
#
# self.assertTrue(len(local_materials) == 2)
#
# def test__getLocalMaterialsWithMultipleVersions(self):
# containerRegistry = ContainerRegistryMock()
# localMaterialWithNewerVersion = self._LOCALMATERIAL_WHITE.copy()
# localMaterialWithNewerVersion["version"] = 2
# containerRegistry.setContainersMetadata([self._LOCALMATERIAL_WHITE, localMaterialWithNewerVersion])
#
# with mock.patch.object(Logger, "log", new=new_log):
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry):
# local_materials = SendMaterialJob(None)._getLocalMaterials()
#
# self.assertTrue(len(local_materials) == 1)
# self.assertTrue(list(local_materials.values())[0].version == 2)
#
# containerRegistry.setContainersMetadata([localMaterialWithNewerVersion, self._LOCALMATERIAL_WHITE])
#
# with mock.patch.object(Logger, "log", new=new_log):
# with mock.patch.object(ContainerRegistry, "getInstance", lambda: containerRegistry):
# local_materials = SendMaterialJob(None)._getLocalMaterials()
#
# self.assertTrue(len(local_materials) == 1)
# self.assertTrue(list(local_materials.values())[0].version == 2)