Merge remote-tracking branch 'origin/devel' into devel

# Conflicts:
#	tests/filemanager/test_filemanager.py
This commit is contained in:
Gina Häußge committed 2018-11-28 17:37:47 +01:00
commit b052925424
17 files changed
+122 -74

No files matched your search

+1 -1
View File
@@ -1533,7 +1533,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":
+1 -1
View File
@@ -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):
+4 -3
View File
@@ -11,6 +11,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
import os
import traceback
import past.builtins
import sys
import re
import tempfile
@@ -509,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
@@ -1646,10 +1647,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, past.builtins.basestring) else x for x in args])
def __contains__(self, item):
if isinstance(item, (str, unicode)):
if isinstance(item, past.builtins.basestring):
return item.lower() in self.data
else:
return item in self.data
+1 -1
View File
@@ -4319,7 +4319,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:
+3 -3
View File
@@ -54,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]
+7
View File
@@ -0,0 +1,7 @@
import sys
OPEN_SIGNATURE = 'builtins.open' if sys.version_info[0] >= 3 else '__builtin__.open'
+46 -29
View File
@@ -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):
@@ -53,18 +58,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 +240,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,21 +288,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("{}.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)
expected = dict(origin=octoprint.filemanager.FileDestinations.LOCAL,
path=path,
pos=pos,
date=now)
mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=2, allow_unicode=True)
mock_atomic_write.assert_called_with(recovery_file, max_permissions=438)
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_with_error(self, mock_time, mock_yaml_safe_dump, mock_atomic_write):
import os
path = "some_file.gco"
pos = 1234
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
self.local_storage.path_in_storage.return_value = path
mock_yaml_safe_dump.side_effect = RuntimeError
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")
@mock.patch("os.remove")
@@ -334,24 +351,24 @@ class FileManagerTest(unittest.TestCase):
@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")
import os
import yaml
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
data = dict(path="some_path.gco",
origin="local",
pos=1234,
date=123456789)
text_data = yaml.dump(data)
data = dict(path="some_path.gco",
origin="local",
pos=1234,
date=123456789)
text_data = yaml.dump(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()
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()
self.assertDictEqual(data, result)
n.assert_called_with(m())
mock_isfile.assert_called_with(recovery_file)
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):
+6 -2
View File
@@ -3,6 +3,8 @@ import unittest
import ddt
import mock
import _fixups
OCTOPI_VERSION = "0.14.0"
DT_MODEL = "Raspberry Pi Model F Rev 1.1"
@@ -13,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("__builtin__.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()
@@ -23,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("__builtin__.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()
+7 -7
View File
@@ -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.assertSetEqual(set(result), set(["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.assertSetEqual(set(result), set(["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)
+21 -8
View File
@@ -13,6 +13,7 @@ import unittest
import shutil
import contextlib
import os
import sys
import tempfile
import yaml
import hashlib
@@ -25,15 +26,29 @@ import octoprint.settings
@ddt.ddt
class TestSettings(unittest.TestCase):
def _load_yaml(self, fname):
if sys.version_info[0] >= 3:
with open(fname, "r+", encoding='utf-8') as f:
return yaml.safe_load(f)
else:
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:
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)
@@ -565,11 +580,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")
+1
View File
@@ -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
+7 -6
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
import _fixups
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(_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
@@ -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(_fixups.OPEN_SIGNATURE, 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(_fixups.OPEN_SIGNATURE, 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(_fixups.OPEN_SIGNATURE, 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(_fixups.OPEN_SIGNATURE, 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(_fixups.OPEN_SIGNATURE, mock.mock_open(), create=True) as m:
self.daemon.set_pid(pid)
# assert
+2 -2
View File
@@ -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)
+2 -2
View File
@@ -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)
+5 -5
View File
@@ -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<x>\d+)"
x_template = "X: {x}"
x_regex = b"X:(?P<x>\d+)"
x_template = b"X: {x}"
x_key = md5sum(x_regex)
x_template_key = md5sum(x_template)
+7 -3
View File
@@ -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
+1 -1
View File
@@ -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)