From a5f87597adc528af38cf85e6f541837b4e8b2bd5 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 1 Sep 2018 22:27:10 -0700 Subject: [PATCH 01/20] refactor and upgrade tests Some prepwork for py3. Tossing these together: - assertItemsEqual doesn't do what it says on the box. It only said "hey, these lists have the same number of items". Not content or anything. Changing that to SetEqual, which is much closer to what is wanted- ensuring that lists have the same content without caring about their order. - use assertRaises instead of try/catch - update some mocks, especially mock_open. - include the refactored test_get_recovery_data sent to the maintenance branch in #2806. --- tests/filemanager/test_filemanager.py | 57 +++++++++++---------------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 278578151..6de49d48d 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -53,18 +53,18 @@ class FilemanagerMethodTest(unittest.TestCase): self.assertTrue("machinecode" in full) self.assertTrue("gcode" in full["machinecode"]) self.assertTrue(isinstance(full["machinecode"]["gcode"], octoprint.filemanager.ContentTypeMapping)) - self.assertItemsEqual(["gcode", "gco", "g"], full["machinecode"]["gcode"].extensions) + self.assertSetEqual(set(["gcode", "gco", "g"]), set(full["machinecode"]["gcode"].extensions)) self.assertTrue("foo" in full["machinecode"]) self.assertTrue(isinstance(full["machinecode"]["foo"], list)) - self.assertItemsEqual(["f", "foo"], full["machinecode"]["foo"]) + self.assertSetEqual(set(["f", "foo"]), set(full["machinecode"]["foo"])) self.assertTrue("model" in full) self.assertTrue("stl" in full["model"]) self.assertTrue(isinstance(full["model"]["stl"], octoprint.filemanager.ContentTypeMapping)) - self.assertItemsEqual(["stl"], full["model"]["stl"].extensions) + self.assertSetEqual(set(["stl"]), set(full["model"]["stl"].extensions)) self.assertTrue("amf" in full["model"]) self.assertTrue(isinstance(full["model"]["amf"], list)) - self.assertItemsEqual(["amf"], full["model"]["amf"]) + self.assertSetEqual(set(["amf"]), set(full["model"]["amf"])) def test_get_mimetype(self): self.assertEqual(octoprint.filemanager.get_mime_type("foo.stl"), "application/sla") @@ -235,22 +235,18 @@ class FileManagerTest(unittest.TestCase): def test_add_folder_not_ignoring_existing(self): self.local_storage.add_folder.side_effect = RuntimeError("already there") - try: + with self.assertRaises(RuntimeError, msg="already there"): self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder", ignore_existing=False) self.fail("Expected an exception to occur!") - except RuntimeError as e: - self.assertEqual("already there", e.message) self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False, display=None) def test_add_folder_display(self): self.local_storage.add_folder.side_effect = RuntimeError("already there") - try: + with self.assertRaises(RuntimeError, msg="already there"): self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder", display=u"täst_folder") self.fail("Expected an exception to occur!") - except RuntimeError as e: - self.assertEqual("already there", e.message) self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=True, display=u"täst_folder") @@ -287,41 +283,37 @@ class FileManagerTest(unittest.TestCase): pos = 1234 recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") - mock_atomic_write.return_value = mock.MagicMock(spec=file) mock_atomic_write_handle = mock_atomic_write.return_value.__enter__.return_value mock_time.return_value = now self.local_storage.path_in_storage.return_value = path - self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) + mock_atomic_write.assert_called_with(recovery_file, max_permissions=0o666) expected = dict(origin=octoprint.filemanager.FileDestinations.LOCAL, path=path, pos=pos, date=now) - - mock_atomic_write.assert_called_with(recovery_file) mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=" ", allow_unicode=True) @mock.patch("octoprint.util.atomic_write", create=True) @mock.patch("yaml.safe_dump", create=True) @mock.patch("time.time") - def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write): + def test_save_recovery_data_with_error(self, mock_time, mock_yaml_safe_dump, mock_atomic_write): import os - now = 123456789 path = "some_file.gco" pos = 1234 recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") - mock_atomic_write.return_value = mock.MagicMock(spec=file) - mock_atomic_write_handle = mock_atomic_write.return_value.__enter__.return_value - mock_time.return_value = now self.local_storage.path_in_storage.return_value = path mock_yaml_safe_dump.side_effect = RuntimeError - self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) @mock.patch("os.path.isfile") @mock.patch("os.remove") @@ -352,29 +344,26 @@ class FileManagerTest(unittest.TestCase): self.file_manager.delete_recovery_data() - @mock.patch("os.path.isfile") - @mock.patch("yaml.safe_load") - def test_get_recovery_data(self, mock_yaml_safe_load, mock_isfile): + @mock.patch("os.path.isfile", return_value=True) + def test_get_recovery_data(self, mock_isfile): import os + import yaml recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml") - mock_isfile.return_value = True - data = dict(path="some_path.gco", origin="local", pos=1234, date=123456789) - mock_yaml_safe_load.return_value = data + text_data = yaml.dump(data) - with mock.patch("__builtin__.open", mock.mock_open(read_data=data), create=True) as m: - result = self.file_manager.get_recovery_data() + with mock.patch("__builtin__.open", mock.mock_open(read_data=text_data)) as m: + # moved safe_load to here so we could mock up the return value properly + with mock.patch("yaml.safe_load", return_value=data) as n: + result = self.file_manager.get_recovery_data() - self.assertDictEqual(data, result) - - m.assert_called_with(recovery_file) - - mock_handle = m() - mock_yaml_safe_load.assert_called_with(mock_handle) + self.assertDictEqual(data, result) + n.assert_called_with(m()) + mock_isfile.assert_called_with(recovery_file) @mock.patch("os.path.isfile") def test_get_recovery_data_no_file(self, mock_isfile): From 660724741c24a50f10fa417dc464319f4ebdb0e1 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 1 Sep 2018 22:31:33 -0700 Subject: [PATCH 02/20] quick refactor for deprecated 'assertEquals' It's been quietly allowed but was dropped in py3. --- tests/server/util/test_flask.py | 14 +++++++------- tests/timelapse/test_timelapse_renderjob.py | 4 ++-- tests/util/test_pip.py | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/server/util/test_flask.py b/tests/server/util/test_flask.py index fef5a9864..2e43fb4bf 100644 --- a/tests/server/util/test_flask.py +++ b/tests/server/util/test_flask.py @@ -487,15 +487,15 @@ class ReverseProxiedEnvironmentTest(unittest.TestCase): def test_header_config_ok(self): result = ReverseProxiedEnvironment.to_header_candidates(["prefix-header1", "prefix-header2"]) - self.assertEquals(result, ["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"]) + self.assertEqual(result, ["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"]) def test_header_config_string(self): result = ReverseProxiedEnvironment.to_header_candidates("prefix-header") - self.assertEquals(result, ["HTTP_PREFIX_HEADER"]) + self.assertEqual(result, ["HTTP_PREFIX_HEADER"]) def test_header_config_none(self): result = ReverseProxiedEnvironment.to_header_candidates(None) - self.assertEquals(result, []) + self.assertEqual(result, []) ##~~ @@ -521,22 +521,22 @@ class OctoPrintFlaskRequestTest(unittest.TestCase): def test_server_name(self): request = OctoPrintFlaskRequest(standard_environ) - self.assertEquals("localhost", request.server_name) + self.assertEqual("localhost", request.server_name) def test_server_port(self): request = OctoPrintFlaskRequest(standard_environ) - self.assertEquals("5000", request.server_port) + self.assertEqual("5000", request.server_port) def test_cookie_suffix(self): request = OctoPrintFlaskRequest(standard_environ) - self.assertEquals("_P5000", request.cookie_suffix) + self.assertEqual("_P5000", request.cookie_suffix) def test_cookie_suffix_with_root(self): script_root_environ = dict(standard_environ) script_root_environ["SCRIPT_NAME"] = "/path/to/octoprint" request = OctoPrintFlaskRequest(script_root_environ) - self.assertEquals("_P5000_R|path|to|octoprint", request.cookie_suffix) + self.assertEqual("_P5000_R|path|to|octoprint", request.cookie_suffix) def test_cookies(self): environ = dict(standard_environ) diff --git a/tests/timelapse/test_timelapse_renderjob.py b/tests/timelapse/test_timelapse_renderjob.py index c9f2a12e8..a3a26926d 100644 --- a/tests/timelapse/test_timelapse_renderjob.py +++ b/tests/timelapse/test_timelapse_renderjob.py @@ -33,7 +33,7 @@ class TimelapseRenderJobTest(unittest.TestCase): @unpack def test_create_ffmpeg_command_string(self, args, kwargs, expected): actual = TimelapseRenderJob._create_ffmpeg_command_string(*args, **kwargs) - self.assertEquals(actual, expected) + self.assertEqual(actual, expected) @data( (dict(), @@ -67,4 +67,4 @@ class TimelapseRenderJobTest(unittest.TestCase): @unpack def test_create_filter_string(self, kwargs, expected): actual = TimelapseRenderJob._create_filter_string(**kwargs) - self.assertEquals(actual, expected) + self.assertEqual(actual, expected) diff --git a/tests/util/test_pip.py b/tests/util/test_pip.py index 5b91b01f0..c65271a0b 100644 --- a/tests/util/test_pip.py +++ b/tests/util/test_pip.py @@ -77,4 +77,4 @@ class PipCallerTest(unittest.TestCase): with mock.patch.object(site, "ENABLE_USER_SITE", user_site): parsed = pkg_resources.parse_version(version) actual = octoprint.util.pip.PipCaller.clean_install_command(args, parsed, virtual_env, use_user, force_user) - self.assertEquals(expected, actual) + self.assertEqual(expected, actual) From 250e83ad7e1f8598318d23a31a9c1f194679f8e0 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 1 Sep 2018 22:32:47 -0700 Subject: [PATCH 03/20] more specific asserts This lets the testing framework show the test error better. --- tests/util/test_caseinsensitive_set.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/util/test_caseinsensitive_set.py b/tests/util/test_caseinsensitive_set.py index 9dfbf7443..22f13004f 100644 --- a/tests/util/test_caseinsensitive_set.py +++ b/tests/util/test_caseinsensitive_set.py @@ -18,8 +18,8 @@ class TestCaseInsensitiveSet(unittest.TestCase): @ddt.data("A", "a", "foo", True, 23) def test_contained(self, value): - self.assertTrue(value in self.set) + self.assertIn(value, self.set) @ddt.data("b", "fnord", False, 42) def test_not_contained(self, value): - self.assertFalse(value in self.set) + self.assertNotIn(value, self.set) From e84293c415f0504cda94ea631a36bf2a79c2bf72 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 1 Sep 2018 22:34:36 -0700 Subject: [PATCH 04/20] add py3compat to CaseInsensitiveSet --- src/octoprint/util/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 918ac1a4b..8ac3c3fe7 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -11,6 +11,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp import os import traceback +import six import sys import re import tempfile @@ -1641,10 +1642,10 @@ class CaseInsensitiveSet(collections.Set): """ def __init__(self, *args): - self.data = set([x.lower() if isinstance(x, (str, unicode)) else x for x in args]) + self.data = set([x.lower() if isinstance(x, six.string_types) else x for x in args]) def __contains__(self, item): - if isinstance(item, (str, unicode)): + if isinstance(item, six.string_types): return item.lower() in self.data else: return item in self.data From 8a0252ccfea190a4858f2258933c914a094c99a3 Mon Sep 17 00:00:00 2001 From: tedder Date: Sun, 2 Sep 2018 00:16:06 -0700 Subject: [PATCH 05/20] add patch workaround for py2/py3 --- tests/filemanager/test_filemanager.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 6de49d48d..de134e8bc 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -9,12 +9,17 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import io import unittest import mock +import six import octoprint.filemanager import octoprint.filemanager.util import octoprint.settings +# we can't seem to get this from six.moves, so we have to work around it to ensure py2/py3 compatability +BUILTINS = "builtins" +if six.PY2: BUILTINS = "__builtin__" + class FilemanagerMethodTest(unittest.TestCase): def setUp(self): @@ -287,7 +292,7 @@ class FileManagerTest(unittest.TestCase): mock_time.return_value = now self.local_storage.path_in_storage.return_value = path - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch("{}.open".format(BUILTINS), mock.mock_open(), create=True) as m: self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) mock_atomic_write.assert_called_with(recovery_file, max_permissions=0o666) @@ -312,7 +317,7 @@ class FileManagerTest(unittest.TestCase): mock_yaml_safe_dump.side_effect = RuntimeError - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch("{}.open".format(BUILTINS), mock.mock_open(), create=True) as m: self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos) @mock.patch("os.path.isfile") @@ -356,7 +361,7 @@ class FileManagerTest(unittest.TestCase): date=123456789) text_data = yaml.dump(data) - with mock.patch("__builtin__.open", mock.mock_open(read_data=text_data)) as m: + with mock.patch("{}.open".format(BUILTINS), mock.mock_open(read_data=text_data)) as m: # moved safe_load to here so we could mock up the return value properly with mock.patch("yaml.safe_load", return_value=data) as n: result = self.file_manager.get_recovery_data() From 7867052339ee401aa6cab74fd77a78eb0ee665c5 Mon Sep 17 00:00:00 2001 From: tedder Date: Sun, 2 Sep 2018 00:44:30 -0700 Subject: [PATCH 06/20] another 'set equality', this one to fix map/list mappings --- tests/server/util/test_flask.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/server/util/test_flask.py b/tests/server/util/test_flask.py index 2e43fb4bf..50b422519 100644 --- a/tests/server/util/test_flask.py +++ b/tests/server/util/test_flask.py @@ -487,11 +487,11 @@ class ReverseProxiedEnvironmentTest(unittest.TestCase): def test_header_config_ok(self): result = ReverseProxiedEnvironment.to_header_candidates(["prefix-header1", "prefix-header2"]) - self.assertEqual(result, ["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"]) + self.assertSetEqual(set(result), set(["HTTP_PREFIX_HEADER1", "HTTP_PREFIX_HEADER2"])) def test_header_config_string(self): result = ReverseProxiedEnvironment.to_header_candidates("prefix-header") - self.assertEqual(result, ["HTTP_PREFIX_HEADER"]) + self.assertSetEqual(set(result), set(["HTTP_PREFIX_HEADER"])) def test_header_config_none(self): result = ReverseProxiedEnvironment.to_header_candidates(None) From 466260690761c6b0588d03474c8a35290c5202fd Mon Sep 17 00:00:00 2001 From: tedder Date: Tue, 18 Sep 2018 08:37:34 -0700 Subject: [PATCH 07/20] PR feedback: use future instead of six Tests pass. --- src/octoprint/util/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 8ac3c3fe7..9184077be 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -11,7 +11,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp import os import traceback -import six +import past.builtins import sys import re import tempfile @@ -1642,10 +1642,10 @@ class CaseInsensitiveSet(collections.Set): """ def __init__(self, *args): - self.data = set([x.lower() if isinstance(x, six.string_types) else x for x in args]) + self.data = set([x.lower() if isinstance(x, past.builtins.basestring) else x for x in args]) def __contains__(self, item): - if isinstance(item, six.string_types): + if isinstance(item, past.builtins.basestring): return item.lower() in self.data else: return item in self.data From 2972d38cefea62f44429e530adf22d59c961f61e Mon Sep 17 00:00:00 2001 From: tedder Date: Tue, 18 Sep 2018 08:54:58 -0700 Subject: [PATCH 08/20] use a number instead of a string for safe_dump --- tests/filemanager/test_filemanager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index de134e8bc..2f0e608d8 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -301,7 +301,7 @@ class FileManagerTest(unittest.TestCase): pos=pos, date=now) - mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=" ", allow_unicode=True) + mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=2, allow_unicode=True) @mock.patch("octoprint.util.atomic_write", create=True) @mock.patch("yaml.safe_dump", create=True) From c2f09b1715aa72821572c6841ba4b747c7728a7a Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 13:14:27 -0700 Subject: [PATCH 09/20] fixes to test_comm_helpers --- src/octoprint/util/comm.py | 2 +- tests/util/test_comm_helpers.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 3397ac396..4b1a8e474 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -4219,7 +4219,7 @@ def parse_temperature_line(line, current): tool = values["tool"] toolnum = values.get("toolnum", None) toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None - if toolNumber > maxToolNum: + if toolNumber and toolNumber > maxToolNum: maxToolNum = toolNumber try: diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 119ff406d..21a733d8b 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -103,15 +103,15 @@ class TestCommHelpers(unittest.TestCase): m.update(input) return m.hexdigest() - temp_regex = "T:((\d*\.)\d+)" - temp_template = "Temp: {}" - temp2_template = "Temperature: {}" + temp_regex = b'T:((\d*\.)\d+)' + temp_template = b"Temp: {}" + temp2_template = b"Temperature: {}" temp_key = md5sum(temp_regex) temp_template_key = md5sum(temp_template) temp2_template_key = md5sum(temp2_template) - x_regex = "X:(?P\d+)" - x_template = "X: {x}" + x_regex = b"X:(?P\d+)" + x_template = b"X: {x}" x_key = md5sum(x_regex) x_template_key = md5sum(x_template) From 52fe19e5f9291c182d3d380ec269da8918bf6ecf Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 15:54:29 -0700 Subject: [PATCH 10/20] fix util.to_unicode for py2/py3. --- src/octoprint/util/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 9184077be..912f197a7 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -510,7 +510,7 @@ def to_str(s_or_u, encoding="utf-8", errors="strict"): def to_unicode(s_or_u, encoding="utf-8", errors="strict"): """Make sure ``s_or_u`` is a unicode string.""" - if isinstance(s_or_u, str): + if isinstance(s_or_u, bytes): return s_or_u.decode(encoding, errors=errors) else: return s_or_u From bd35de80c36d9b87fc06e7197b15ce839bb55fe6 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 15:55:19 -0700 Subject: [PATCH 11/20] fix test_file_helpers, couldn't figureout a non-conditional way to do this --- tests/util/test_file_helpers.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 36bf525da..214424891 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -332,12 +332,16 @@ class IsHiddenPathTest(unittest.TestCase): self.path_hidden_on_windows = os.path.join(self.basepath, "hidden_on_windows.txt") self.path_always_hidden = os.path.join(self.basepath, ".always_hidden.txt") + import sys for attr in ("path_always_visible", "path_hidden_on_windows", "path_always_hidden"): path = getattr(self, attr) - with open(path, "w+b") as f: - f.write(attr) + if sys.version_info[0] >= 3: + with open(path, "w+", encoding='utf-8') as f: + f.write(attr) + else: + with open(path, "wb+") as f: + f.write(attr) - import sys if sys.platform == "win32": # we use ctypes and the windows API to set the hidden attribute on the file # only hidden on windows From 472fda6645c0cb92e2686d29953f942c8d7e3ad2 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 16:02:44 -0700 Subject: [PATCH 12/20] setuptools py3 compatability --- src/octoprint_setuptools/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 794bc2619..9c1b24eb6 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import os import shutil import glob +from past.builtins import basestring from setuptools import Command from distutils.command.clean import clean as _clean From aa383e3ca12eb3d3a6812b3b575e04e5017e4a46 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 16:15:22 -0700 Subject: [PATCH 13/20] fix all __builtin__.open patch/mock calls --- tests/plugins/pi_support/test_pi_support.py | 5 +++-- tests/test_daemon.py | 13 +++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/plugins/pi_support/test_pi_support.py b/tests/plugins/pi_support/test_pi_support.py index be33f8c71..52c1baa38 100644 --- a/tests/plugins/pi_support/test_pi_support.py +++ b/tests/plugins/pi_support/test_pi_support.py @@ -2,6 +2,7 @@ import unittest import ddt import mock +from builtins import open # lets py2 use 'builtins.open' instead of '__builtin__.open' in mocking OCTOPI_VERSION = "0.14.0" @@ -14,7 +15,7 @@ class PiSupportTestCase(unittest.TestCase): def test_get_octopi_version(self): from octoprint.plugins.pi_support import get_octopi_version - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: m.return_value.readline.return_value = OCTOPI_VERSION version = get_octopi_version() @@ -24,7 +25,7 @@ class PiSupportTestCase(unittest.TestCase): def test_get_proc_dt_model(self): from octoprint.plugins.pi_support import get_proc_dt_model - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: m.return_value.readline.return_value = DT_MODEL model = get_proc_dt_model() diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 61211b2c9..bec339c5d 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,5 +1,6 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function +from builtins import open # lets py2 use 'builtins.open' instead of '__builtin__.open' in mocking import unittest import mock @@ -102,7 +103,7 @@ class DaemonTest(unittest.TestCase): @mock.patch("sys.stdout") @mock.patch("sys.stderr") @mock.patch("os.devnull") - @mock.patch("__builtin__.open") + @mock.patch("builtins.open") @mock.patch("os.dup2") def test_redirect_io(self, mock_dup2, mock_open, mock_devnull, mock_stderr, mock_stdout, mock_stdin): # setup @@ -390,7 +391,7 @@ class DaemonTest(unittest.TestCase): pid = 1234 # test - with mock.patch("__builtin__.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: result = self.daemon.get_pid() # assert @@ -403,7 +404,7 @@ class DaemonTest(unittest.TestCase): handle.__enter__.side_effect = IOError() # test - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: result = self.daemon.get_pid() # assert @@ -415,7 +416,7 @@ class DaemonTest(unittest.TestCase): pid = "not an integer" # test - with mock.patch("__builtin__.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: result = self.daemon.get_pid() # assert @@ -427,7 +428,7 @@ class DaemonTest(unittest.TestCase): pid = "1234" # test - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert @@ -440,7 +441,7 @@ class DaemonTest(unittest.TestCase): pid = 1234 # test - with mock.patch("__builtin__.open", mock.mock_open(), create=True) as m: + with mock.patch("builtins.open", mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert From 22fdc1d933308a434d5894fdaeee7924b6f9e450 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 16:58:24 -0700 Subject: [PATCH 14/20] final open mock tactic: add a central global. --- tests/_fixups.py | 7 +++++++ tests/plugins/pi_support/test_pi_support.py | 9 ++++++--- tests/test_daemon.py | 14 +++++++------- 3 files changed, 20 insertions(+), 10 deletions(-) create mode 100644 tests/_fixups.py diff --git a/tests/_fixups.py b/tests/_fixups.py new file mode 100644 index 000000000..4e2c3ab55 --- /dev/null +++ b/tests/_fixups.py @@ -0,0 +1,7 @@ + + + +import sys + + +OPEN_SIGNATURE = 'builtins.open' if sys.version_info[0] >= 3 else '__builtin__.open' diff --git a/tests/plugins/pi_support/test_pi_support.py b/tests/plugins/pi_support/test_pi_support.py index 52c1baa38..05354f713 100644 --- a/tests/plugins/pi_support/test_pi_support.py +++ b/tests/plugins/pi_support/test_pi_support.py @@ -2,7 +2,8 @@ import unittest import ddt import mock -from builtins import open # lets py2 use 'builtins.open' instead of '__builtin__.open' in mocking + +import _fixups OCTOPI_VERSION = "0.14.0" @@ -14,8 +15,9 @@ class PiSupportTestCase(unittest.TestCase): def test_get_octopi_version(self): from octoprint.plugins.pi_support import get_octopi_version + #import _fixups - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: m.return_value.readline.return_value = OCTOPI_VERSION version = get_octopi_version() @@ -24,8 +26,9 @@ class PiSupportTestCase(unittest.TestCase): def test_get_proc_dt_model(self): from octoprint.plugins.pi_support import get_proc_dt_model + #import _fixups - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: m.return_value.readline.return_value = DT_MODEL model = get_proc_dt_model() diff --git a/tests/test_daemon.py b/tests/test_daemon.py index bec339c5d..96974aca2 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,6 +1,6 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function -from builtins import open # lets py2 use 'builtins.open' instead of '__builtin__.open' in mocking +import _fixups import unittest import mock @@ -103,7 +103,7 @@ class DaemonTest(unittest.TestCase): @mock.patch("sys.stdout") @mock.patch("sys.stderr") @mock.patch("os.devnull") - @mock.patch("builtins.open") + @mock.patch(_fixups.OPEN_SIGNATURE) @mock.patch("os.dup2") def test_redirect_io(self, mock_dup2, mock_open, mock_devnull, mock_stderr, mock_stdout, mock_stdin): # setup @@ -391,7 +391,7 @@ class DaemonTest(unittest.TestCase): pid = 1234 # test - with mock.patch("builtins.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: result = self.daemon.get_pid() # assert @@ -404,7 +404,7 @@ class DaemonTest(unittest.TestCase): handle.__enter__.side_effect = IOError() # test - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: result = self.daemon.get_pid() # assert @@ -416,7 +416,7 @@ class DaemonTest(unittest.TestCase): pid = "not an integer" # test - with mock.patch("builtins.open", mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data="{}\n".format(pid)), create=True) as m: result = self.daemon.get_pid() # assert @@ -428,7 +428,7 @@ class DaemonTest(unittest.TestCase): pid = "1234" # test - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert @@ -441,7 +441,7 @@ class DaemonTest(unittest.TestCase): pid = 1234 # test - with mock.patch("builtins.open", mock.mock_open(), create=True) as m: + with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m: self.daemon.set_pid(pid) # assert From 791e759b4039f31f731f8a3e558e48366d66771f Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 17:21:05 -0700 Subject: [PATCH 15/20] keys() doesn't return a list, so restoring the contract. --- src/octoprint/slicing/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py index e919f1727..dfb07d627 100644 --- a/src/octoprint/slicing/__init__.py +++ b/src/octoprint/slicing/__init__.py @@ -157,7 +157,7 @@ class SlicingManager(object): Returns: (list of str) Identifiers of all available slicers. """ - return self._slicers.keys() + return list(self._slicers.keys()) @property def configured_slicers(self): From df706f61db051487dd7d88a435efe5f71eb48ff4 Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 17:21:33 -0700 Subject: [PATCH 16/20] import locally for py3 mock compatability --- tests/slicing/test_slicingmanager.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/slicing/test_slicingmanager.py b/tests/slicing/test_slicingmanager.py index d3ef60ea6..138f69223 100644 --- a/tests/slicing/test_slicingmanager.py +++ b/tests/slicing/test_slicingmanager.py @@ -28,6 +28,7 @@ class TestSlicingManager(unittest.TestCase): self._mock_slicer_plugins(self.slicer_plugin) # mock profile manager + import octoprint.printer.profile self.printer_profile_manager = mock.MagicMock(spec=octoprint.printer.profile.PrinterProfileManager) # mock settings From 743ff35bcf563643f773c5cbd352d535f54614fa Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 18:05:10 -0700 Subject: [PATCH 17/20] add some yaml wrappers for the test environment --- tests/settings/test_settings.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 9c8ab966e..3e110d6ab 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -13,6 +13,7 @@ import unittest import shutil import contextlib import os +import sys import tempfile import yaml import hashlib @@ -24,15 +25,28 @@ import octoprint.settings @ddt.ddt class TestSettings(unittest.TestCase): + def _load_yaml(self, fname): + if sys.version_info[0] >= 3: + with open(fname, "w+", encoding='utf-8') as f: + return yaml.safe_load(f) + else: + with open(fname, "wb+") as f: + return yaml.safe_load(f) + def _dump_yaml(self, fname, config): + if sys.version_info[0] >= 3: + with open(fname, "w+", encoding='utf-8') as f: + yaml.safe_dump(config, f) + else: + with open(fname, "wb+") as f: + yaml.safe_dump(config, f) + def setUp(self): self.base_path = os.path.join(os.path.dirname(__file__), "_files") self.config_path = os.path.realpath(os.path.join(self.base_path, "config.yaml")) self.defaults_path = os.path.realpath(os.path.join(self.base_path, "defaults.yaml")) - with open(self.config_path, "r+b") as f: - self.config = yaml.safe_load(f) - with open(self.defaults_path, "r+b") as f: - self.defaults = yaml.safe_load(f) + self.config = self._load_yaml(self.config_path) + self.defaults = self._load_yaml(self.defaults_path) from octoprint.util import dict_merge self.expected_effective = dict_merge(self.defaults, self.config) @@ -503,11 +517,9 @@ class TestSettings(unittest.TestCase): self.assertEqual("0.0.0.0", settings.get(["server", "host"])) # modify yaml file externally - with open(configfile, "r+b") as f: - config = yaml.safe_load(f) + config = self._load_yaml(configfile) config["server"]["host"] = "127.0.0.1" - with open(configfile, "w+b") as f: - yaml.safe_dump(config, f) + self._dump_yaml(configfile, config) # set some value, should also reload file before setting new api key settings.set(["api", "key"], "key") From 9cb3631ad02334edc02099b4f29c9a537982e69b Mon Sep 17 00:00:00 2001 From: tedder Date: Sat, 22 Sep 2018 18:05:32 -0700 Subject: [PATCH 18/20] first py3 fix --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 08eb032bd..fe8c50fcc 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1502,7 +1502,7 @@ class Settings(object): return value is not None def getBaseFolder(self, type, create=True, allow_fallback=True, log_error=False, check_writable=True, deep_check_writable=False): - if type not in default_settings["folder"].keys() + ["base"]: + if type not in list(default_settings["folder"].keys()) + ["base"]: return None if type == "base": From b3cc44cea5b03de5742f633f22b83f9bb0d9edaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 30 Oct 2018 16:46:12 +0100 Subject: [PATCH 19/20] Fix build error `octoprint_setuptools` is imported into the build before the dependencies are installed, hence we don't have `past.builtins` yet. Since the `basestring` type was only needed for some asserts here that *usually* shouldn't be needed we can just comment out that stuff for now. --- src/octoprint_setuptools/__init__.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 9c1b24eb6..d7b0884d7 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -8,7 +8,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import os import shutil import glob -from past.builtins import basestring from setuptools import Command from distutils.command.clean import clean as _clean @@ -55,9 +54,9 @@ def has_requirement(requirement, requirements): if requirement is None or requirements is None: return False - assert isinstance(requirement, basestring) - assert isinstance(requirements, (list, tuple)) - assert all(list(map(lambda x: x is not None and isinstance(x, basestring), requirements))) + #assert isinstance(requirement, basestring) + #assert isinstance(requirements, (list, tuple)) + #assert all(list(map(lambda x: x is not None and isinstance(x, basestring), requirements))) requirement = requirement.lower() requirements = [r.lower() for r in requirements] From 3ad4818488dbec7864151ca8afb3b12647322833 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 30 Oct 2018 16:56:14 +0100 Subject: [PATCH 20/20] Use read instead of write mode in _load_yaml --- tests/settings/test_settings.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 3e110d6ab..39d6570b1 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -27,11 +27,12 @@ class TestSettings(unittest.TestCase): def _load_yaml(self, fname): if sys.version_info[0] >= 3: - with open(fname, "w+", encoding='utf-8') as f: + with open(fname, "r+", encoding='utf-8') as f: return yaml.safe_load(f) else: - with open(fname, "wb+") as f: + with open(fname, "r+b") as f: return yaml.safe_load(f) + def _dump_yaml(self, fname, config): if sys.version_info[0] >= 3: with open(fname, "w+", encoding='utf-8') as f: