🎨 Add codemods to pre-commit, fix flake8

This commit is contained in:
Gina Häußge committed 2020-10-07 16:27:11 +02:00
1 parent 6d6671c2a1
commit b5be8f3eae
107 files changed
+1149 -1160

No files matched your search

+13 -5
View File
@@ -7,16 +7,24 @@ repos:
- id: trailing-whitespace
- id: check-yaml
- id: check-toml
- repo: https://github.com/OctoPrint/codemods
rev: main
hooks:
- id: codemod_dict_to_literal
args: ['--ignore', 'src/octoprint/vendor']
- id: codemod_set_to_literal
args: ['--ignore', 'src/octoprint/vendor']
- id: codemod_not_in
args: ['--ignore', 'src/octoprint/vendor']
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: stable
hooks:
- id: black
args: ['--config', 'black.toml']
language_version: python3.7
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
- id: isort
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.1
hooks:
+2 -2
View File
@@ -73,7 +73,7 @@ class CodeBlockExt(CodeBlock):
code blocks.
"""
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
option_spec = _merge_dict(CodeBlock.option_spec, {"whitespace": directives.flag})
def run(self):
# type: () -> List[nodes.Node]
@@ -280,4 +280,4 @@ def setup(app):
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
return {"version": "0.1"}
+1 -1
View File
@@ -25,7 +25,7 @@ if False:
# For type annotation
from typing import Any, List # NOQA
cache = dict()
cache = {}
class OnlineIncludeReader(LiteralIncludeReader):
+1 -1
View File
@@ -22,7 +22,7 @@ I don't know anything about).
sys.path.insert(0, os.path.join(basedir, "src"))
import octoprint
import octoprint # noqa: E402
if len(sys.argv) == 1:
sys.argv.append("serve")
+2 -7
View File
@@ -15,13 +15,8 @@ lookupfile = .versioneer-lookup
[flake8]
max-line-length = 90
ignore =
D
E
W
F401
F523
extend-ignore = E203
extend-ignore = E203, E231, E265, E266, E402, E501, E731
select = B,C,E,F,W,T4,B9
exclude =
src/octoprint/vendor
+13 -19
View File
@@ -5,12 +5,12 @@ import os
import sys
from distutils.command.build_py import build_py as _build_py
import versioneer
import versioneer # noqa: F401
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import setuptools
import setuptools # noqa: F401,E402
import octoprint_setuptools
import octoprint_setuptools # noqa: F401,E402
# ----------------------------------------------------------------------------------------
@@ -86,35 +86,29 @@ INSTALL_REQUIRES_OSX = [
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
EXTRA_REQUIRES = {
"develop": [
# Testing dependencies
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# linter
"flake8",
# formatters
"black",
"isort",
# pre-commit
"pre-commit",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
plugins=["cookiecutter>=1.7.2,<1.8"],
"plugins": ["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation - Python 3 required!
docs=[
"docs": [
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext",
],
)
}
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
@@ -154,7 +148,7 @@ def read_file_contents(path):
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
files = {}
def run(self):
print("RUNNING md_to_html_build_py")
@@ -180,7 +174,7 @@ def md_to_html_build_py_factory(files, baseclass):
baseclass.run(self)
return type(md_to_html_build_py)(
md_to_html_build_py.__name__, (md_to_html_build_py,), dict(files=files)
md_to_html_build_py.__name__, (md_to_html_build_py,), {"files": files}
)
@@ -192,11 +186,11 @@ def get_cmdclass():
# add clean command
cmdclass.update(
dict(
clean=octoprint_setuptools.CleanCommand.for_options(
{
"clean": octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
)
}
)
# add translation commands
+4 -4
View File
@@ -438,7 +438,7 @@ def init_pluginsystem(
import os
# we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins
import octoprint.plugins
import octoprint.plugins # noqa: F401
logger = log.getLogger(__name__ + ".startup")
@@ -529,7 +529,7 @@ def init_pluginsystem(
disabled_list = pm.plugin_disabled_list
already_processed = []
for name, addons, _ in sorted_disabled_from_overlays:
if not name in disabled_list and not name.endswith("disabled"):
if name not in disabled_list and not name.endswith("disabled"):
for addon in addons:
if addon in disabled_list:
continue
@@ -541,7 +541,7 @@ def init_pluginsystem(
)
)
if not addon in already_processed and not addon in disabled_list:
if addon not in already_processed and addon not in disabled_list:
disabled_list.append(addon)
logger.info(
"Disabling plugin {} as defined by plugin {}".format(
@@ -593,7 +593,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
return result
for entry in entries:
if not "plugin" in entry:
if "plugin" not in entry:
continue
if "octoversions" in entry and not is_octoprint_compatible(
+4 -4
View File
@@ -235,7 +235,7 @@ class FilebasedGroupManager(GroupManager):
with io.open(self._groupfile, "rt", encoding="utf-8") as f:
data = yaml.safe_load(f)
if not "groups" in data:
if "groups" not in data:
groups = data
data = {"groups": groups}
@@ -283,8 +283,8 @@ class FilebasedGroupManager(GroupManager):
default_permissions = self.default_permissions_for_group(key)
for permission in default_permissions:
if (
not permission.key in tracked_permissions
and not permission in permissions
permission.key not in tracked_permissions
and permission not in permissions
):
permissions.append(permission)
@@ -326,7 +326,7 @@ class FilebasedGroupManager(GroupManager):
"subgroups": self._from_groups(*group._subgroups),
"default": group._default,
}
if not key in self._default_groups:
if key not in self._default_groups:
groups[key]["name"] = group.get_name()
groups[key]["description"] = group.get_description()
+1 -1
View File
@@ -157,7 +157,7 @@ class PluginIdentityContext(object):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
"""
@property
def identity(self):
+10 -11
View File
@@ -8,7 +8,6 @@ import hashlib
import io
import logging
import os
import time
import uuid
# noinspection PyCompatibility
@@ -94,7 +93,7 @@ class UserManager(GroupChangeListener, object):
self._session_users_by_session[user.session] = user
userid = user.get_id()
if not userid in self._sessionids_by_userid:
if userid not in self._sessionids_by_userid:
self._sessionids_by_userid[userid] = set()
self._sessionids_by_userid[userid].add(user.session)
@@ -552,7 +551,7 @@ class FilebasedUserManager(UserManager):
groups = {self._group_manager.user_group}
# migrate from roles to permissions
if "roles" in attributes and not "permissions" in attributes:
if "roles" in attributes and "permissions" not in attributes:
self._logger.info(
"Migrating user {} to new granular permission system".format(
name
@@ -791,7 +790,7 @@ class FilebasedUserManager(UserManager):
self._trigger_on_user_modified(username)
def change_user_password(self, username, password):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
passwordHash = UserManager.create_password_hash(password, settings=self._settings)
@@ -802,7 +801,7 @@ class FilebasedUserManager(UserManager):
self._save()
def change_user_setting(self, username, key, value):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
@@ -813,7 +812,7 @@ class FilebasedUserManager(UserManager):
self._save()
def change_user_settings(self, username, new_settings):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
@@ -824,21 +823,21 @@ class FilebasedUserManager(UserManager):
self._save()
def get_all_user_settings(self, username):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
return user.get_all_settings()
def get_user_setting(self, username, key):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
return user.get_setting(key)
def generate_api_key(self, username):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
@@ -848,7 +847,7 @@ class FilebasedUserManager(UserManager):
return user._apikey
def delete_api_key(self, username):
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
user = self._users[username]
@@ -859,7 +858,7 @@ class FilebasedUserManager(UserManager):
def remove_user(self, username):
UserManager.remove_user(self, username)
if not username in self._users:
if username not in self._users:
raise UnknownUser(username)
del self._users[username]
+12 -10
View File
@@ -5,13 +5,15 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import sys
import click
import octoprint
click.disable_unicode_literals_warning = True
# ~~ click context
@@ -199,13 +201,13 @@ legacy_options = bulk_options(
# ~~ "octoprint" command, merges server_commands and plugin_commands groups
from .analysis import analysis_commands
from .client import client_commands
from .config import config_commands
from .dev import dev_commands
from .plugins import plugin_commands
from .server import server_commands
from .user import user_commands
from .analysis import analysis_commands # noqa: E402
from .client import client_commands # noqa: E402
from .config import config_commands # noqa: E402
from .dev import dev_commands # noqa: E402
from .plugins import plugin_commands # noqa: E402
from .server import server_commands # noqa: E402
from .user import user_commands # noqa: E402
@click.group(
+3 -4
View File
@@ -4,19 +4,18 @@ from __future__ import absolute_import, division, print_function, unicode_litera
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import io
import json
import click
from past.builtins import unicode
import octoprint_client
from octoprint import FatalStartupError, init_settings
from octoprint.cli import bulk_options, get_ctx_obj_option
click.disable_unicode_literals_warning = True
class JsonStringParamType(click.ParamType):
name = "json"
+5 -5
View File
@@ -5,17 +5,17 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import json
import logging
import pprint
import click
import yaml
from octoprint import FatalStartupError, init_settings
from octoprint.cli import bulk_options, get_ctx_obj_option, standard_options
from octoprint.cli import get_ctx_obj_option, standard_options
click.disable_unicode_literals_warning = True
def _to_settings_path(path):
@@ -191,7 +191,7 @@ def remove_value_command(ctx, path, value, as_json=False):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
if value not in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
+3 -3
View File
@@ -5,15 +5,15 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import logging.config
import click
from octoprint.cli import OctoPrintContext, get_ctx_obj_option, pass_octoprint_ctx
from octoprint.util import dict_merge
click.disable_unicode_literals_warning = True
LOGGING_CONFIG = {
"version": 1,
"formatters": {"brief": {"format": "%(message)s"}},
+4 -3
View File
@@ -5,12 +5,11 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
import logging
import sys
import click
from octoprint.cli import (
bulk_options,
get_ctx_obj_option,
@@ -18,6 +17,8 @@ from octoprint.cli import (
standard_options,
)
click.disable_unicode_literals_warning = True
def run_server(
basedir,
+6 -6
View File
@@ -29,7 +29,7 @@ def all_events():
return [
getattr(Events, name)
for name in Events.__dict__
if not name.startswith("_") and not name in ("register_event",)
if not name.startswith("_") and name not in ("register_event",)
]
@@ -357,10 +357,10 @@ class CommandTrigger(GenericEventListener):
continue
if (
not "event" in subscription
or not "command" in subscription
or not "type" in subscription
or not subscription["type"] in ["system", "gcode"]
"event" not in subscription
or "command" not in subscription
or "type" not in subscription
or subscription["type"] not in ["system", "gcode"]
):
self._logger.info(
"Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(
@@ -402,7 +402,7 @@ class CommandTrigger(GenericEventListener):
GenericEventListener.eventCallback(self, event, payload)
if not event in self._subscriptions:
if event not in self._subscriptions:
return
for command, commandType, debug in self._subscriptions[event]:
+7 -7
View File
@@ -17,10 +17,10 @@ import octoprint.util
from octoprint.events import Events, eventManager
from octoprint.util import get_fully_qualified_classname as fqcn
from .analysis import AnalysisQueue, QueueEntry
from .destinations import FileDestinations
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, DiskFileWrapper, StreamWrapper
from .analysis import AnalysisQueue, QueueEntry # noqa: F401
from .destinations import FileDestinations # noqa: F401
from .storage import LocalFileStorage # noqa: F401
from .util import AbstractFileWrapper, DiskFileWrapper, StreamWrapper # noqa: F401
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
@@ -348,7 +348,7 @@ class FileManager(object):
self._determine_analysis_backlog(storage_type, storage_manager)
def remove_storage(self, type):
if not type in self._storage_managers:
if type not in self._storage_managers:
return
del self._storage_managers[type]
@@ -1028,14 +1028,14 @@ class FileManager(object):
return self._storage(destination).last_modified(path=path, recursive=recursive)
def _storage(self, destination):
if not destination in self._storage_managers:
if destination not in self._storage_managers:
raise NoSuchStorage(
"No storage configured for destination {destination}".format(**locals())
)
return self._storage_managers[destination]
def _add_analysis_result(self, destination, path, result):
if not destination in self._storage_managers:
if destination not in self._storage_managers:
return
storage_manager = self._storage_managers[destination]
+4 -4
View File
@@ -90,7 +90,7 @@ class AnalysisQueue(object):
if entry is None:
return False
if not entry.type in self._queues:
if entry.type not in self._queues:
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
@@ -100,7 +100,7 @@ class AnalysisQueue(object):
if entry is None:
return False
if not entry.type in self._queues:
if entry.type not in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
@@ -121,7 +121,7 @@ class AnalysisQueue(object):
for callback in self._callbacks:
try:
callback(entry, result)
except:
except Exception:
self._logger.exception(
"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)},
@@ -477,7 +477,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
if not "RESULTS:" in output:
if "RESULTS:" not in output:
raise RuntimeError("No analysis result found")
_, output = output.split("RESULTS:")
+32 -32
View File
@@ -577,9 +577,9 @@ class LocalFileStorage(StorageInterface):
if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name):
if (
not entry.name in metadata
entry.name not in metadata
or not isinstance(metadata[entry.name], dict)
or not "analysis" in metadata[entry.name]
or "analysis" not in metadata[entry.name]
):
printer_profile_rels = self.get_link(entry.path, "printerprofile")
if printer_profile_rels:
@@ -909,12 +909,12 @@ class LocalFileStorage(StorageInterface):
file_hash = self._create_hash(file_path)
metadata = self._get_metadata_entry(path, name, default={})
metadata_dirty = False
if not "hash" in metadata or metadata["hash"] != file_hash:
if "hash" not in metadata or metadata["hash"] != file_hash:
# hash changed -> throw away old metadata
metadata = {"hash": file_hash}
metadata_dirty = True
if not "display" in metadata and display_name != name:
if "display" not in metadata and display_name != name:
# display name is not the same as file name -> store in metadata
metadata["display"] = display_name
metadata_dirty = True
@@ -1062,7 +1062,7 @@ class LocalFileStorage(StorageInterface):
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if not name in metadata:
if name not in metadata:
return
return metadata[name].get(key)
@@ -1072,12 +1072,12 @@ class LocalFileStorage(StorageInterface):
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata:
if name not in metadata:
return
metadata = self._copied_metadata(metadata, name)
if not key in metadata[name] or overwrite:
if key not in metadata[name] or overwrite:
metadata[name][key] = data
metadata_dirty = True
elif (
@@ -1100,10 +1100,10 @@ class LocalFileStorage(StorageInterface):
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if not name in metadata:
if name not in metadata:
return
if not key in metadata[name]:
if key not in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
@@ -1262,10 +1262,10 @@ class LocalFileStorage(StorageInterface):
def _add_history(self, name, path, data):
metadata = self._copied_metadata(self._get_metadata(path), name)
if not "hash" in metadata[name]:
if "hash" not in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "history" in metadata[name]:
if "history" not in metadata[name]:
metadata[name]["history"] = []
metadata[name]["history"].append(data)
@@ -1275,7 +1275,7 @@ class LocalFileStorage(StorageInterface):
def _update_history(self, name, path, index, data):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
if name not in metadata or "history" not in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
@@ -1290,7 +1290,7 @@ class LocalFileStorage(StorageInterface):
def _delete_history(self, name, path, index):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
if name not in metadata or "history" not in metadata[name]:
return
metadata = self._copied_metadata(metadata, name)
@@ -1306,7 +1306,7 @@ class LocalFileStorage(StorageInterface):
if metadata is None:
metadata = self._copied_metadata(self._get_metadata(path), name)
if not "history" in metadata[name]:
if "history" not in metadata[name]:
return
# collect data from history
@@ -1315,10 +1315,10 @@ class LocalFileStorage(StorageInterface):
for history_entry in metadata[name]["history"]:
if (
not "printTime" in history_entry
or not "success" in history_entry
"printTime" not in history_entry
or "success" not in history_entry
or not history_entry["success"]
or not "printerProfile" in history_entry
or "printerProfile" not in history_entry
):
continue
@@ -1337,12 +1337,12 @@ class LocalFileStorage(StorageInterface):
)
continue
if not printer_profile in former_print_times:
if printer_profile not in former_print_times:
former_print_times[printer_profile] = []
former_print_times[printer_profile].append(print_time)
if (
not printer_profile in last_print
printer_profile not in last_print
or last_print[printer_profile] is None
or (
"timestamp" in history_entry
@@ -1378,14 +1378,14 @@ class LocalFileStorage(StorageInterface):
metadata = self._get_metadata(path)
result = []
if not name in metadata:
if name not in metadata:
return result
if not "links" in metadata[name]:
if "links" not in metadata[name]:
return result
for data in metadata[name]["links"]:
if not "rel" in data or not data["rel"] == searched_rel:
if "rel" not in data or not data["rel"] == searched_rel:
continue
result.append(data)
return result
@@ -1398,10 +1398,10 @@ class LocalFileStorage(StorageInterface):
metadata = self._copied_metadata(self._get_metadata(path), name)
metadata_dirty = False
if not "hash" in metadata[name]:
if "hash" not in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "links" in metadata[name]:
if "links" not in metadata[name]:
metadata[name]["links"] = []
for rel, data in links:
@@ -1423,7 +1423,7 @@ class LocalFileStorage(StorageInterface):
hash = metadata[data["name"]]["hash"]
else:
hash = self._create_hash(ref_path)
if not data["name"] in metadata:
if data["name"] not in metadata:
metadata[data["name"]] = {"hash": hash, "links": []}
else:
metadata[data["name"]]["hash"] = hash
@@ -1432,7 +1432,7 @@ class LocalFileStorage(StorageInterface):
# file doesn't have the correct hash, we won't create the link
continue
if not "links" in metadata[data["name"]]:
if "links" not in metadata[data["name"]]:
metadata[data["name"]]["links"] = []
# add reverse link to link target file
@@ -1491,7 +1491,7 @@ class LocalFileStorage(StorageInterface):
matches = True
for k, v in data.items():
if not k in link or not link[k] == v:
if k not in link or not link[k] == v:
matches = False
break
@@ -1594,7 +1594,7 @@ class LocalFileStorage(StorageInterface):
):
entry_metadata = metadata[entry_name]
if (
not "display" in entry_metadata
"display" not in entry_metadata
and entry_display != entry_name
):
if not metadata_dirty:
@@ -1639,7 +1639,7 @@ class LocalFileStorage(StorageInterface):
):
entry_metadata = metadata[entry_name]
if (
not "display" in entry_metadata
"display" not in entry_metadata
and entry_display != entry_name
):
if not metadata_dirty:
@@ -1761,7 +1761,7 @@ class LocalFileStorage(StorageInterface):
def _remove_metadata_entry(self, path, name):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
if not name in metadata:
if name not in metadata:
return
metadata = copy.copy(metadata)
@@ -1769,7 +1769,7 @@ class LocalFileStorage(StorageInterface):
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
if not "links" in m:
if "links" not in m:
continue
links_hash = (
lambda link: "hash" in link
@@ -1840,7 +1840,7 @@ class LocalFileStorage(StorageInterface):
try:
json.dumps(value, allow_nan=False)
return True
except:
except Exception:
return False
if isinstance(metadata, dict):
+1 -1
View File
@@ -5,7 +5,7 @@ from typing import Union
from past.builtins import basestring, unicode
from octoprint.logging import handlers
from octoprint.logging import handlers # noqa: F401
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
+6 -7
View File
@@ -21,10 +21,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import threading
from octoprint.plugin.core import Plugin, PluginInfo, PluginManager
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F401
from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.settings import settings as s
from octoprint.util import deprecated, to_native_str
@@ -428,16 +427,16 @@ class PluginSettings(object):
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
if "defaults" not in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
if "preprocessors" not in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
+38 -38
View File
@@ -183,23 +183,23 @@ class PluginInfo(object):
attr_pythoncompat = "__plugin_pythoncompat__"
"""
Module attribute from which to retrieve the plugin's python compatibility string.
Module attribute from which to retrieve the plugin's python compatibility string.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to
Python 2 but not Python 3.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended.
Bundled plugins will automatically be assumed to be compatible.
"""
Bundled plugins will automatically be assumed to be compatible.
"""
attr_hidden = "__plugin_hidden__"
"""
Module attribute from which to determine if the plugin's hidden or not.
Module attribute from which to determine if the plugin's hidden or not.
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
Only evaluated for bundled plugins, in order to hide them from the Plugin Manager
and similar places.
"""
attr_hooks = "__plugin_hooks__"
""" Module attribute from which to retrieve the plugin's provided hooks. """
@@ -209,15 +209,15 @@ class PluginInfo(object):
attr_implementations = "__plugin_implementations__"
"""
Module attribute from which to retrieve the plugin's provided implementations.
Module attribute from which to retrieve the plugin's provided implementations.
This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the
first entry will be evaluated.
This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the
first entry will be evaluated.
.. deprecated:: 1.2.0-dev-694
.. deprecated:: 1.2.0-dev-694
Use :attr:`attr_implementation` instead.
"""
Use :attr:`attr_implementation` instead.
"""
attr_helpers = "__plugin_helpers__"
""" Module attribute from which to retrieve the plugin's provided helpers. """
@@ -227,14 +227,14 @@ class PluginInfo(object):
attr_init = "__plugin_init__"
"""
Module attribute which to call when loading the plugin.
Module attribute which to call when loading the plugin.
This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_load`.
This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_load`.
.. deprecated:: 1.2.0-dev-720
.. deprecated:: 1.2.0-dev-720
Use :attr:`attr_load` instead.
"""
Use :attr:`attr_load` instead.
"""
attr_load = "__plugin_load__"
""" Module attribute which to call when loading the plugin. """
@@ -267,9 +267,9 @@ class PluginInfo(object):
self.origin = None
"""
The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin`
or :class:`ModuleOrigin` instance. Set during loading, initially ``None``.
"""
The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin`
or :class:`ModuleOrigin` instance. Set during loading, initially ``None``.
"""
self.enabled = True
"""Whether the plugin is enabled."""
@@ -464,7 +464,7 @@ class PluginInfo(object):
callable or None: Handler for the requested ``hook`` or None if no handler is registered.
"""
if not hook in self.hooks:
if hook not in self.hooks:
return None
return self.hooks[hook]
@@ -1091,9 +1091,9 @@ class PluginManager(object):
import sys
if site.ENABLE_USER_SITE:
if not site.USER_SITE in working_set.entries:
if site.USER_SITE not in working_set.entries:
working_set.add_entry(site.USER_SITE)
if not site.USER_SITE in sys.path:
if site.USER_SITE not in sys.path:
site.addsitedir(site.USER_SITE)
if not isinstance(groups, (list, tuple)):
@@ -1376,7 +1376,7 @@ class PluginManager(object):
added, found = self.find_plugins(
existing=dict(
(k, v) for k, v in self.plugins.items() if not k in force_reload
(k, v) for k, v in self.plugins.items() if k not in force_reload
),
incl_all_found=True,
)
@@ -1475,7 +1475,7 @@ class PluginManager(object):
name (str): plugin identifier
**flags (dict): dictionary of flag names and values
"""
if not name in self.plugins:
if name not in self.plugins:
self.logger.debug(
"Trying to mark an unknown plugin {name}".format(**locals())
)
@@ -1484,7 +1484,7 @@ class PluginManager(object):
if value is None:
continue
if value and not name in self.marked_plugins[key]:
if value and name not in self.marked_plugins[key]:
self.marked_plugins[key].append(name)
elif not value and name in self.marked_plugins[key]:
self.marked_plugins[key].remove(name)
@@ -1500,7 +1500,7 @@ class PluginManager(object):
Returns:
(boolean): True if the plugin has been flagged, False otherwise
"""
if not name in self.plugins:
if name not in self.plugins:
return False
return name in self.marked_plugins[flag]
@@ -1508,7 +1508,7 @@ class PluginManager(object):
def load_plugin(
self, name, plugin=None, startup=False, initialize_implementation=True
):
if not name in self.plugins:
if name not in self.plugins:
self.logger.warning(
"Trying to load an unknown plugin {name}".format(**locals())
)
@@ -1535,7 +1535,7 @@ class PluginManager(object):
self.logger.exception("There was an error loading plugin %s" % name)
def unload_plugin(self, name):
if not name in self.plugins:
if name not in self.plugins:
self.logger.warning(
"Trying to unload unknown plugin {name}".format(**locals())
)
@@ -1569,14 +1569,14 @@ class PluginManager(object):
# make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins
if name in self.enabled_plugins:
del self.enabled_plugins[name]
if not name in self.disabled_plugins:
if name not in self.disabled_plugins:
self.disabled_plugins[name] = plugin
def enable_plugin(
self, name, plugin=None, initialize_implementation=True, startup=False
):
"""Enables a plugin"""
if not name in self.disabled_plugins:
if name not in self.disabled_plugins:
self.logger.warning(
"Tried to enable plugin {name}, however it is not disabled".format(
**locals()
@@ -1630,7 +1630,7 @@ class PluginManager(object):
def disable_plugin(self, name, plugin=None):
"""Disables a plugin"""
if not name in self.enabled_plugins:
if name not in self.enabled_plugins:
self.logger.warning(
"Tried to disable plugin {name}, however it is not enabled".format(
**locals()
@@ -2116,7 +2116,7 @@ class PluginManager(object):
dict: A dict containing all registered handlers mapped by their plugin's identifier.
"""
if not hook in self.plugin_hooks:
if hook not in self.plugin_hooks:
return {}
result = OrderedDict()
@@ -2220,7 +2220,7 @@ class PluginManager(object):
registered with the system.
"""
if not name in self.enabled_plugins:
if name not in self.enabled_plugins:
return None
plugin = self.enabled_plugins[name]
+5 -5
View File
@@ -1114,7 +1114,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
return False
name = implementation._identifier
if not name in seen_wizards:
if name not in seen_wizards:
return False
seen = seen_wizards[name]
@@ -1527,9 +1527,9 @@ class SettingsPlugin(OctoPrintPlugin):
def __init__(self):
self._settings = None
"""
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
the plugin core system upon initialization of the implementation.
"""
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
the plugin core system upon initialization of the implementation.
"""
def on_settings_load(self):
"""
@@ -1578,7 +1578,7 @@ class SettingsPlugin(OctoPrintPlugin):
if len(path) > 1:
for entry in path[:-1]:
if not entry in node:
if entry not in node:
return
node = node[entry]
@@ -11,7 +11,6 @@ import octoprint.plugin
from octoprint.access import USER_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
from octoprint.server import user_permission
class Prompt(object):
@@ -224,7 +223,7 @@ class ActionCommandPromptPlugin(
):
return
if not "S" in cmd:
if "S" not in cmd:
# we only force-send M876 Sx
return
@@ -13,17 +13,13 @@ import re
import sys
import threading
import time
import octoprint.plugin
PY2 = sys.version_info[0] < 3
from collections import OrderedDict
import feedparser
import flask
from flask_babel import gettext
import octoprint.plugin
from octoprint import __version__ as OCTOPRINT_VERSION
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
@@ -34,6 +30,8 @@ from octoprint.server.util.flask import (
)
from octoprint.util import count, monotonic_time, utmify
PY2 = sys.version_info[0] < 3
class AnnouncementPlugin(
octoprint.plugin.AssetPlugin,
@@ -161,7 +159,7 @@ class AnnouncementPlugin(
if "_spotlight" in enabled:
add_blog = True
enabled.remove("_spotlight")
if add_blog and not "_blog" in enabled:
if add_blog and "_blog" not in enabled:
enabled.append("_blog")
self._settings.set(["enabled_channels"], enabled)
@@ -359,7 +357,7 @@ class AnnouncementPlugin(
configs = self._settings.get(["channels"], merged=True)
order = self._settings.get(["channel_order"])
all_keys = order + [
key for key in sorted(configs.keys()) if not key in order
key for key in sorted(configs.keys()) if key not in order
]
result = OrderedDict()
@@ -394,10 +392,10 @@ class AnnouncementPlugin(
all_channels = {}
for key, config in channels.items():
if not key in enabled and not key in forced:
if key not in enabled and key not in forced:
continue
if not "url" in config:
if "url" not in config:
continue
data = self._get_channel_data(key, config, force=force)
+2 -4
View File
@@ -4,8 +4,6 @@ from __future__ import absolute_import, unicode_literals
import io
import os
import threading
import time
import uuid
from collections import defaultdict
import flask
@@ -161,7 +159,7 @@ class AppKeysPlugin(
if data is None:
return flask.make_response("Missing key request", 400)
if not "app" in data:
if "app" not in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
@@ -209,7 +207,7 @@ class AppKeysPlugin(
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
if "decision" not in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
+4 -4
View File
@@ -9,7 +9,7 @@ from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
from octoprint.events import Events
from octoprint.plugin.core import FolderOrigin
from octoprint.server import NO_CONTENT, admin_permission
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import no_firstrun_access
from octoprint.settings import default_settings
from octoprint.util import is_hidden_path, to_bytes
@@ -989,7 +989,7 @@ class BackupPlugin(
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except Exception as exc: ## noqa: F841
except Exception as exc: # noqa: F841
# TODO py3: use the exception, not sys.exc_info()
if callable(on_backup_error):
exc_info = sys.exc_info()
@@ -1278,8 +1278,8 @@ class BackupPlugin(
return (
is_os_compatible(["!windows"])
and not settings.get_boolean(["restore_unsupported"])
and not os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False)
in valid_boolean_trues
and os.environ.get("OCTOPRINT_BACKUP_RESTORE_UNSUPPORTED", False)
not in valid_boolean_trues
)
def _send_client_message(self, message, payload=None):
+1 -1
View File
@@ -47,7 +47,7 @@ class CoreWizardPlugin(
if not method():
continue
if not key in names:
if key not in names:
continue
name = names[key]()
@@ -113,7 +113,7 @@ class AclSubwizard(object):
[USER_GROUP, ADMIN_GROUP],
overwrite=True,
)
elif "ac" in data and not data["ac"] in valid_boolean_trues:
elif "ac" in data and data["ac"] not in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
self._user_manager.disable()
+2 -2
View File
@@ -269,7 +269,7 @@ class DiscoveryPlugin(
reg_type = self._format_zeroconf_service_type(reg_type)
key = (reg_type, port)
if not key in self._zeroconf_registrations:
if key not in self._zeroconf_registrations:
return
infos = self._zeroconf_registrations.pop(key)
@@ -277,7 +277,7 @@ class DiscoveryPlugin(
for info in infos:
self._zeroconf.unregister_service(info)
self._logger.debug("Unregistered {} on port {}".format(reg_type, port))
except:
except Exception:
self._logger.exception(
"Could not (fully) unregister {} on port {}".format(reg_type, port)
)
@@ -4,13 +4,17 @@ from __future__ import absolute_import, division, print_function, unicode_litera
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import errno
import logging
import requests.exceptions
import serial
import tornado.websocket
from flask import jsonify
from flask_babel import gettext
import octoprint.plugin
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import get_fully_qualified_classname as fqcn # noqa: F401
from octoprint.util.version import (
get_octoprint_version_string,
is_released_octoprint_version,
@@ -31,12 +35,6 @@ SETTINGS_DEFAULTS = {
"url_coreui": SENTRY_URL_COREUI,
}
import errno
import requests.exceptions
import serial
import tornado.websocket
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(
@@ -173,7 +171,7 @@ def _enable_errortracking():
from octoprint.plugin import plugin_manager
def _before_send(event, hint):
if not "exc_info" in hint:
if "exc_info" not in hint:
# we only want exceptions
return None
@@ -205,7 +203,7 @@ def _enable_errortracking():
handled = not any(
map(
lambda x: x.get("mechanism")
and x["mechanism"].get("handled", True) == False,
and not x["mechanism"].get("handled", True),
event["exception"]["values"],
)
)
+1 -1
View File
@@ -113,7 +113,7 @@ class LoggingPlugin(
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
+1 -1
View File
@@ -180,7 +180,7 @@ def get_vcgencmd_throttled_state(command):
else:
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
if not "throttled=0x" in output:
if "throttled=0x" not in output:
raise ValueError('cannot parse "{}" output: {}'.format(command, output))
value = output[len("throttled=") :].strip(" \t\r\n\0")
@@ -49,7 +49,7 @@ from octoprint.util.version import (
try:
from os import scandir
except:
except ImportError:
from scandir import scandir
_DATA_FORMAT_VERSION = "v3"
@@ -61,7 +61,7 @@ def map_repository_entry(entry):
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
if "follow_dependency_links" not in result:
result["follow_dependency_links"] = False
result["is_compatible"] = {"octoprint": True, "os": True, "python": True}
@@ -538,7 +538,7 @@ class PluginManagerPlugin(
elif command == "uninstall":
plugin_name = data["plugin"]
if not plugin_name in self._plugin_manager.plugins:
if plugin_name not in self._plugin_manager.plugins:
return make_response("Unknown plugin: %s" % plugin_name, 404)
plugin = self._plugin_manager.plugins[plugin_name]
@@ -559,7 +559,7 @@ class PluginManagerPlugin(
elif command == "enable" or command == "disable":
plugin_name = data["plugin"]
if not plugin_name in self._plugin_manager.plugins:
if plugin_name not in self._plugin_manager.plugins:
return make_response("Unknown plugin: %s" % plugin_name, 404)
plugin = self._plugin_manager.plugins[plugin_name]
@@ -924,7 +924,7 @@ class PluginManagerPlugin(
try:
self._log_call("cp {} {}".format(path, destination))
shutil.copy(path, destination)
except:
except Exception:
self._logger.exception("Installing plugin from {} failed".format(source))
result = {
"result": False,
@@ -1442,7 +1442,7 @@ class PluginManagerPlugin(
fallback=[],
)
)
if not plugin.key in disabled_list:
if plugin.key not in disabled_list:
disabled_list.append(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
@@ -1493,8 +1493,6 @@ class PluginManagerPlugin(
def _fetch_repository_from_disk(self):
repo_data = None
if os.path.isfile(self._repository_cache_path):
import time
mtime = os.path.getmtime(self._repository_cache_path)
if self._is_repository_cache_valid(mtime=mtime):
try:
@@ -1590,8 +1588,6 @@ class PluginManagerPlugin(
def _fetch_notices_from_disk(self):
notice_data = None
if os.path.isfile(self._notices_cache_path):
import time
mtime = os.path.getmtime(self._notices_cache_path)
if self._is_notices_cache_valid(mtime=mtime):
try:
@@ -1654,7 +1650,7 @@ class PluginManagerPlugin(
notices = {}
for notice in notice_data:
if not "plugin" in notice or not "text" in notice or not "date" in notice:
if "plugin" not in notice or "text" not in notice or "date" not in notice:
continue
key = notice["plugin"]
@@ -1676,7 +1672,7 @@ class PluginManagerPlugin(
)
continue
if not key in notices:
if key not in notices:
notices[key] = []
notices[key].append(notice)
@@ -274,7 +274,7 @@ class SoftwareUpdatePlugin(
config_checks = self._settings.get(["checks"])
plugin_and_not_enabled = (
lambda k: k in check_providers
and not check_providers[k] in self._plugin_manager.enabled_plugins
and check_providers[k] not in self._plugin_manager.enabled_plugins
)
obsolete_plugin_checks = list(
filter(plugin_and_not_enabled, config_checks.keys())
@@ -332,7 +332,7 @@ class SoftwareUpdatePlugin(
try:
data = psutil.disk_usage(path)
info["free"] = data.free
except:
except Exception:
self._logger.exception(
"Error while determining disk usage of {}".format(path)
)
@@ -747,7 +747,7 @@ class SoftwareUpdatePlugin(
octoprint_check = dict(configured_checks["octoprint"])
if (
not "method" in octoprint_check
"method" not in octoprint_check
and octoprint_check.get("type") == "git_commit"
):
defaults = {
@@ -1076,7 +1076,7 @@ class SoftwareUpdatePlugin(
if not self._storage_sufficient:
return flask.make_response("Not enough free disk space for updating", 409)
if not "application/json" in flask.request.headers["Content-Type"]:
if "application/json" not in flask.request.headers["Content-Type"]:
return flask.make_response("Expected content-type JSON", 400)
json_data = flask.request.get_json(silent=True)
@@ -1110,7 +1110,7 @@ class SoftwareUpdatePlugin(
settings_dirty = False
for target, data in json_data.items():
if not target in checks:
if target not in checks:
continue
try:
@@ -1259,7 +1259,7 @@ class SoftwareUpdatePlugin(
with futures.ThreadPoolExecutor(max_workers=5) as executor:
for target, check in checks.items():
if not target in check_targets:
if target not in check_targets:
continue
if not check:
@@ -1606,14 +1606,14 @@ class SoftwareUpdatePlugin(
### iterate over all configured targets
for target in check_targets:
if not target in checks:
if target not in checks:
continue
check = checks[target]
if "enabled" in check and not check["enabled"]:
continue
if not target in check_targets:
if target not in check_targets:
continue
target_error, target_result = self._perform_update(target, check, force)
@@ -1793,7 +1793,7 @@ class SoftwareUpdatePlugin(
)
trigger_event(False)
if not "ignorable" in populated_check or not populated_check["ignorable"]:
if "ignorable" not in populated_check or not populated_check["ignorable"]:
target_error = True
if isinstance(e, exceptions.UpdateError):
@@ -1867,7 +1867,7 @@ class SoftwareUpdatePlugin(
def _populated_check(self, target, check):
from flask_babel import gettext
if not "type" in check:
if "type" not in check:
raise exceptions.UnknownCheckType()
result = dict(check)
@@ -1977,7 +1977,7 @@ class SoftwareUpdatePlugin(
if "pip" in result:
if (
not "pip_command" in check
"pip_command" not in check
and self._settings.get(["pip_command"]) is not None
):
result["pip_command"] = self._settings.get(["pip_command"])
@@ -2006,7 +2006,7 @@ class SoftwareUpdatePlugin(
if version checker cannot be determined.
"""
if not "type" in check:
if "type" not in check:
raise exceptions.ConfigurationInvalid("no check type defined")
check_type = check["type"]
@@ -2038,7 +2038,7 @@ class SoftwareUpdatePlugin(
elif "python_updater" in check:
method = "python_updater"
if method is None or (valid_methods and not method in valid_methods):
if method is None or (valid_methods and method not in valid_methods):
raise exceptions.UnknownUpdateType()
return method
@@ -2063,7 +2063,7 @@ class SoftwareUpdatePlugin(
if checks is None:
checks = self._get_configured_checks()
if not "octoprint" in checks:
if "octoprint" not in checks:
return None
if "checkout_folder" in checks["octoprint"]:
@@ -2077,7 +2077,7 @@ class SoftwareUpdatePlugin(
if checks is None:
checks = self._get_configured_checks()
if not "octoprint" in checks:
if "octoprint" not in checks:
return None
return checks["octoprint"].get("branch")
@@ -2086,7 +2086,7 @@ class SoftwareUpdatePlugin(
if checks is None:
checks = self._get_configured_checks()
if not "octoprint" in checks:
if "octoprint" not in checks:
return None
return checks["octoprint"].get("pip")
+2 -2
View File
@@ -161,7 +161,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
return
plugin_message = msg["data"]
if not "type" in plugin_message:
if "type" not in plugin_message:
return
plugin_message_type = plugin_message["type"]
@@ -241,7 +241,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if not name in checks else checks[name]))
click.echo("\t{}".format(name if name not in checks else checks[name]))
socket.wait()
@@ -5,4 +5,10 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import pip, python_updater, single_file_plugin, sleep_a_bit, update_script
from . import ( # noqa: F401
pip,
python_updater,
single_file_plugin,
sleep_a_bit,
update_script,
)
@@ -48,7 +48,7 @@ def _get_pip_caller(command=None):
if command is None:
key = "__default"
if not key in _pip_callers:
if key not in _pip_callers:
try:
_pip_callers[key] = PipCaller(configured=command)
except UnknownPip:
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import (
from . import ( # noqa: F401
always_current,
bitbucket_commit,
commandline,
@@ -38,7 +38,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
return None
reference = r.json()
if not "hash" in reference:
if "hash" not in reference:
return None
return reference["hash"]
@@ -35,7 +35,7 @@ def _get_latest_commit(user, repo, branch):
return None
reference = r.json()
if not "object" in reference or not "sha" in reference["object"]:
if "object" not in reference or "sha" not in reference["object"]:
return None
return reference["object"]["sha"]
@@ -198,8 +198,8 @@ def _get_comparable_version_semantic(version_string, force_base=True):
def _get_sanitized_compare_type(compare_type, custom=None):
if (
not compare_type
in (
compare_type
not in (
"python",
"python_unequal",
"semantic",
@@ -9,7 +9,7 @@ import logging
import pkg_resources
import requests
from octoprint.util import to_native_str
from octoprint.util import to_native_str # noqa: F401
from octoprint.util.version import (
get_comparable_version,
is_prerelease,
@@ -79,7 +79,7 @@ def _get_latest_release(package, include_prerelease):
return None
data = r.json()
if not "info" in data or not "version" in data["info"]:
if "info" not in data or "version" not in data["info"]:
return None
requires_python = data["info"].get("requires_python")
+2 -1
View File
@@ -27,6 +27,7 @@ from octoprint.util.version import get_octoprint_version_string
TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/"
# noinspection PyMissingConstructor
class TrackingPlugin(
octoprint.plugin.SettingsPlugin,
@@ -352,7 +353,7 @@ class TrackingPlugin(
if not self._settings.get_boolean(["events", "commerror"]):
return
if not "reason" in payload or not "error" in payload:
if "reason" not in payload or "error" not in payload:
return
track_event = "commerror_{}".format(payload["reason"])
@@ -462,7 +462,7 @@ class VirtualPrinter(object):
if (
self._writingToSd
and self._writingToSdHandle is not None
and not "M29" in data
and "M29" not in data
):
self._writingToSdHandle.write(data)
self._sendOk()
@@ -908,79 +908,79 @@ class VirtualPrinter(object):
# type: (str) -> None
if data == "" or data == "help" or data == "?":
usage = """
OctoPrint Virtual Printer debug commands
OctoPrint Virtual Printer debug commands
help
?
| This help.
help
?
| This help.
# Action Triggers
# Action Triggers
action_pause
| Sends a "// action:pause" action trigger to the host.
action_resume
| Sends a "// action:resume" action trigger to the host.
action_disconnect
| Sends a "// action:disconnect" action trigger to the
| host.
action_custom <action>[ <parameters>]
| Sends a custom "// action:<action> <parameters>"
| action trigger to the host.
action_pause
| Sends a "// action:pause" action trigger to the host.
action_resume
| Sends a "// action:resume" action trigger to the host.
action_disconnect
| Sends a "// action:disconnect" action trigger to the
| host.
action_custom <action>[ <parameters>]
| Sends a custom "// action:<action> <parameters>"
| action trigger to the host.
# Communication Errors
# Communication Errors
dont_answer
| Will not acknowledge the next command.
go_awol
| Will completely stop replying
trigger_resend_lineno
| Triggers a resend error with a line number mismatch
trigger_resend_checksum
| Triggers a resend error with a checksum mismatch
trigger_missing_checksum
| Triggers a resend error with a missing checksum
trigger_missing_lineno
| Triggers a "no line number with checksum" error w/o resend request
trigger_fatal_error_marlin
| Triggers a fatal error/simulated heater fail, Marlin style
trigger_fatal_error_repetier
| Triggers a fatal error/simulated heater fail, Repetier style
drop_connection
| Drops the serial connection
prepare_ok <broken ok>
| Will cause <broken ok> to be enqueued for use,
| will be used instead of actual "ok"
rerequest_last
| Will cause the last line number + 1 to be rerequest add infinitum
dont_answer
| Will not acknowledge the next command.
go_awol
| Will completely stop replying
trigger_resend_lineno
| Triggers a resend error with a line number mismatch
trigger_resend_checksum
| Triggers a resend error with a checksum mismatch
trigger_missing_checksum
| Triggers a resend error with a missing checksum
trigger_missing_lineno
| Triggers a "no line number with checksum" error w/o resend request
trigger_fatal_error_marlin
| Triggers a fatal error/simulated heater fail, Marlin style
trigger_fatal_error_repetier
| Triggers a fatal error/simulated heater fail, Repetier style
drop_connection
| Drops the serial connection
prepare_ok <broken ok>
| Will cause <broken ok> to be enqueued for use,
| will be used instead of actual "ok"
rerequest_last
| Will cause the last line number + 1 to be rerequest add infinitum
# Reply Timing / Sleeping
# Reply Timing / Sleeping
sleep <int:seconds>
| Sleep <seconds> s
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of next <command>
sleep <int:seconds>
| Sleep <seconds> s
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of next <command>
# SD printing
# SD printing
start_sd <str:file>
| Select and start printing file <file> from SD
select_sd <str:file>
| Select file <file> from SD, don't start printing it yet. Use
| start_sd to start the print
cancel_sd
| Cancels an ongoing SD print
start_sd <str:file>
| Select and start printing file <file> from SD
select_sd <str:file>
| Select file <file> from SD, don't start printing it yet. Use
| start_sd to start the print
cancel_sd
| Cancels an ongoing SD print
# Misc
# Misc
send <str:message>
| Sends back <message>
reset
| Simulates a reset. Internal state will be lost.
unbusy
| Unsets the busy loop.
"""
send <str:message>
| Sends back <message>
reset
| Simulates a reset. Internal state will be lost.
unbusy
| Unsets the busy loop.
"""
for line in usage.split("\n"):
self._send("echo: {}".format(line.strip()))
elif data == "action_pause":
@@ -1299,12 +1299,12 @@ class VirtualPrinter(object):
only_wait_if_higher = True
try:
self.chamberTargetTemp = float(re.search("S([0-9]+)", line).group(1))
except:
except Exception:
if support_r:
try:
self.chamberTargetTemp = float(re.search("R([0-9]+)", line).group(1))
only_wait_if_higher = False
except:
except Exception:
pass
if wait:
@@ -1851,7 +1851,7 @@ class CharCountingQueue(queue.Queue):
def _len(self, item):
return len(item)
def _qsize(self, l=len):
def _qsize(self, l=len): # noqa: E741
return self._size
# Put a new item in the queue
+9 -10
View File
@@ -151,7 +151,6 @@ import copy
import io
import logging
import os
import re
try:
from os import scandir
@@ -454,7 +453,7 @@ class PrinterProfileManager(object):
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers()
if identifier is not None and not identifier in all_identifiers:
if identifier is not None and identifier not in all_identifiers:
return
settings().set(["printerProfiles", "default"], identifier)
@@ -592,7 +591,7 @@ class PrinterProfileManager(object):
if (
"volume" in profile
and "formFactor" in profile["volume"]
and not "origin" in profile["volume"]
and "origin" not in profile["volume"]
):
profile["volume"]["origin"] = (
BedOrigin.CENTER
@@ -601,11 +600,11 @@ class PrinterProfileManager(object):
)
modified = True
if "volume" in profile and not "custom_box" in profile["volume"]:
if "volume" in profile and "custom_box" not in profile["volume"]:
profile["volume"]["custom_box"] = False
modified = True
if "extruder" in profile and not "sharedNozzle" in profile["extruder"]:
if "extruder" in profile and "sharedNozzle" not in profile["extruder"]:
profile["extruder"]["sharedNozzle"] = False
modified = True
@@ -617,7 +616,7 @@ class PrinterProfileManager(object):
profile["extruder"]["offsets"] = [(0.0, 0.0)]
modified = True
if not "heatedChamber" in profile:
if "heatedChamber" not in profile:
profile["heatedChamber"] = False
modified = True
@@ -637,11 +636,11 @@ class PrinterProfileManager(object):
def convert_value(profile, path, converter):
value = profile
for part in path[:-1]:
if not isinstance(value, dict) or not part in value:
if not isinstance(value, dict) or part not in value:
raise RuntimeError("%s is not contained in profile" % ".".join(path))
value = value[part]
if not isinstance(value, dict) or not path[-1] in value:
if not isinstance(value, dict) or path[-1] not in value:
raise RuntimeError("%s is not contained in profile" % ".".join(path))
value[path[-1]] = converter(value[path[-1]])
@@ -698,7 +697,7 @@ class PrinterProfileManager(object):
return False
# validate form factor
if not profile["volume"]["formFactor"] in BedFormFactor.values():
if profile["volume"]["formFactor"] not in BedFormFactor.values():
self._logger.warning(
"Profile has invalid value volume.formFactor: {formFactor}".format(
formFactor=profile["volume"]["formFactor"]
@@ -707,7 +706,7 @@ class PrinterProfileManager(object):
return False
# validate origin type
if not profile["volume"]["origin"] in BedOrigin.values():
if profile["volume"]["origin"] not in BedOrigin.values():
self._logger.warning(
"Profile has invalid value in volume.origin: {origin}".format(
origin=profile["volume"]["origin"]
+3 -3
View File
@@ -305,8 +305,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if (
progress is None
or not self._selectedFile
or not "sd" in self._selectedFile
or not "filename" in self._selectedFile
or "sd" not in self._selectedFile
or "filename" not in self._selectedFile
):
return
@@ -452,7 +452,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
raise ValueError("At least one axis to jog must be provided")
for axis in axes:
if not axis in PrinterInterface.valid_axes:
if axis not in PrinterInterface.valid_axes:
raise ValueError(
"Invalid axis {}, valid axes are {}".format(
axis, ", ".join(PrinterInterface.valid_axes)
+31 -25
View File
@@ -15,12 +15,12 @@ import os
import re
import signal
import sys
import uuid
import uuid # noqa: F401
from builtins import bytes, range
from collections import OrderedDict, defaultdict
from babel import Locale
from flask import (
from flask import ( # noqa: F401
Blueprint,
Flask,
Request,
@@ -32,8 +32,13 @@ from flask import (
session,
)
from flask_assets import Bundle, Environment
from flask_babel import Babel, gettext, ngettext
from flask_login import LoginManager, current_user, session_protected, user_logged_out
from flask_babel import Babel, gettext, ngettext # noqa: F401
from flask_login import ( # noqa: F401
LoginManager,
current_user,
session_protected,
user_logged_out,
)
from past.builtins import basestring, unicode
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
@@ -42,7 +47,7 @@ import octoprint.util
import octoprint.util.net
from octoprint.server import util
from octoprint.util.json import JsonEncoding
from octoprint.vendor.flask_principal import (
from octoprint.vendor.flask_principal import ( # noqa: F401
AnonymousIdentity,
Identity,
Permission,
@@ -89,8 +94,8 @@ connectivityChecker = None
principals = Principal(app)
import octoprint.access.groups as groups
import octoprint.access.permissions as permissions
import octoprint.access.groups as groups # noqa: E402
import octoprint.access.permissions as permissions # noqa: E402
# we set admin_permission to a GroupPermission with the default admin group
admin_permission = octoprint.util.variable_deprecated(
@@ -104,15 +109,15 @@ user_permission = octoprint.util.variable_deprecated(
since="1.4.0",
)(groups.GroupPermission(groups.USER_GROUP))
import octoprint._version
import octoprint.access.groups as groups
import octoprint.access.users as users
import octoprint.events as events
import octoprint.filemanager.analysis
import octoprint.filemanager.storage
import octoprint.plugin
import octoprint.slicing
import octoprint.timelapse
import octoprint._version # noqa: E402
import octoprint.access.groups as groups # noqa: E402
import octoprint.access.users as users # noqa: E402
import octoprint.events as events # noqa: E402
import octoprint.filemanager.analysis # noqa: E402
import octoprint.filemanager.storage # noqa: E402
import octoprint.plugin # noqa: E402
import octoprint.slicing # noqa: E402
import octoprint.timelapse # noqa: E402
# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint import __branch__, __display_version__, __revision__, __version__
@@ -1068,8 +1073,8 @@ class Server(object):
if not isinstance(entry, tuple) or not len(entry) == 3:
continue
if (
not entry[0]
in util.tornado.UploadStorageFallbackHandler.BODY_METHODS
entry[0]
not in util.tornado.UploadStorageFallbackHandler.BODY_METHODS
):
continue
if not isinstance(entry[2], int):
@@ -1210,7 +1215,7 @@ class Server(object):
else:
self._logger.info(
"Listening on http://{}:{}".format(
self._host if not ":" in self._host else "[" + self._host + "]",
self._host if ":" not in self._host else "[" + self._host + "]",
self._port,
)
)
@@ -1533,10 +1538,10 @@ class Server(object):
def externalize_links(text):
def repl(match):
tag = match.group("tag")
if not "href" in tag:
if "href" not in tag:
return match.group(0)
if not "target=" in tag and not "rel=" in tag:
if "target=" not in tag and "rel=" not in tag:
tag += ' target="_blank" rel="noreferrer noopener"'
content = match.group("content")
@@ -1765,7 +1770,7 @@ class Server(object):
def _register_additional_template_plugin(self, plugin):
folder = plugin.get_template_folder()
if folder is not None and not folder in self._template_searchpaths:
if folder is not None and folder not in self._template_searchpaths:
self._template_searchpaths.append(folder)
def _unregister_additional_template_plugin(self, plugin):
@@ -1774,7 +1779,8 @@ class Server(object):
self._template_searchpaths.remove(folder)
def _setup_blueprints(self):
import octoprint.server.views # do not remove or the index view won't be found
# do not remove or the index view won't be found
import octoprint.server.views # noqa: F401
from octoprint.server.api import api
blueprints = OrderedDict()
@@ -2476,7 +2482,7 @@ class Server(object):
else:
self._logger.debug(
"Starting intermediary server on http://{}:{}".format(
host if not ":" in host else "[" + host + "]", port
host if ":" not in host else "[" + host + "]", port
)
)
@@ -2612,7 +2618,7 @@ class Server(object):
if not isinstance(p, dict):
continue
if not "key" in p or not "name" in p:
if "key" not in p or "name" not in p:
continue
if not key_whitelist.match(p["key"]):
+14 -14
View File
@@ -43,24 +43,24 @@ from octoprint.server.util.flask import (
)
from octoprint.settings import settings as s
from octoprint.settings import valid_boolean_trues
from octoprint.vendor.flask_principal import AnonymousIdentity, Identity, identity_changed
from octoprint.vendor.flask_principal import Identity, identity_changed
# ~~ init api blueprint, including sub modules
api = Blueprint("api", __name__)
from . import access as api_access
from . import connection as api_connection
from . import files as api_files
from . import job as api_job
from . import languages as api_languages
from . import printer as api_printer
from . import printer_profiles as api_printer_profiles
from . import settings as api_settings
from . import slicing as api_slicing
from . import system as api_system
from . import timelapse as api_timelapse
from . import users as api_users
from . import access as api_access # noqa: F401,E402
from . import connection as api_connection # noqa: F401,E402
from . import files as api_files # noqa: F401,E402
from . import job as api_job # noqa: F401,E402
from . import languages as api_languages # noqa: F401,E402
from . import printer as api_printer # noqa: F401,E402
from . import printer_profiles as api_printer_profiles # noqa: F401,E402
from . import settings as api_settings # noqa: F401,E402
from . import slicing as api_slicing # noqa: F401,E402
from . import system as api_system # noqa: F401,E402
from . import timelapse as api_timelapse # noqa: F401,E402
from . import users as api_users # noqa: F401,E402
VERSION = "0.1"
@@ -211,7 +211,7 @@ def wizardFinish():
if data is None:
abort(400)
if not "handled" in data:
if "handled" not in data:
abort(400)
handled = data["handled"]
+11 -11
View File
@@ -38,7 +38,7 @@ def get_groups():
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def add_group():
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -46,11 +46,11 @@ def add_group():
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if not "key" in data:
if "key" not in data:
return make_response("Missing mandatory key field", 400)
if not "name" in data:
if "name" not in data:
return make_response("Missing mandatory name field", 400)
if not "permissions" in data:
if "permissions" not in data:
return make_response("Missing mandatory permissions field", 400)
key = data["key"]
@@ -154,7 +154,7 @@ def add_user():
if not userManager.enabled:
return jsonify(SUCCESS)
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -165,11 +165,11 @@ def add_user():
if data is None:
return make_response("Malformed JSON body in request", 400)
if not "name" in data:
if "name" not in data:
return make_response("Missing mandatory name field", 400)
if not "password" in data:
if "password" not in data:
return make_response("Missing mandatory password field", 400)
if not "active" in data:
if "active" not in data:
return make_response("Missing mandatory active field", 400)
name = data["name"]
@@ -218,7 +218,7 @@ def update_user(username):
user = userManager.find_user(username)
if user is not None:
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -275,7 +275,7 @@ def change_password_for_user(username):
and not current_user.is_anonymous
and (current_user.get_name() == username or current_user.is_admin)
):
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -286,7 +286,7 @@ def change_password_for_user(username):
if data is None:
return make_response("Malformed JSON body in request", 400)
if not "password" in data or not data["password"]:
if "password" not in data or not data["password"]:
return make_response("password is missing from request", 400)
try:
+7 -7
View File
@@ -215,7 +215,7 @@ def readGcodeFilesForOrigin(origin):
or request.values.get("_refresh", False),
)
def readGcodeFile(target, filename):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
recursive = False
@@ -446,7 +446,7 @@ def uploadGcodeFile(target):
input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
)
if input_upload_name in request.values and input_upload_path in request.values:
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
upload = octoprint.filemanager.util.DiskFileWrapper(
@@ -684,7 +684,7 @@ def uploadGcodeFile(target):
elif "foldername" in request.values:
foldername = request.values["foldername"]
if not target in [FileDestinations.LOCAL]:
if target not in [FileDestinations.LOCAL]:
return make_response("Unknown target: %s" % target, 400)
canonPath, canonName = fileManager.canonicalize(target, foldername)
@@ -741,7 +741,7 @@ def uploadGcodeFile(target):
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
@no_firstrun_access
def gcodeFileCommand(filename, target):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
# valid file commands, dict mapping command name to mandatory parameters
@@ -1025,7 +1025,7 @@ def gcodeFileCommand(filename, target):
elif command == "copy" or command == "move":
with Permissions.FILES_UPLOAD.require(403):
# Copy and move are only possible on local storage
if not target in [FileDestinations.LOCAL]:
if target not in [FileDestinations.LOCAL]:
return make_response(
"Unsupported target for {}: {}".format(command, target), 400
)
@@ -1160,7 +1160,7 @@ def deleteGcodeFile(filename, target):
)
if _verifyFileExists(target, filename):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 400)
if _isBusy(target, filename):
@@ -1184,7 +1184,7 @@ def deleteGcodeFile(filename, target):
fileManager.remove_file(target, filename)
elif _verifyFolderExists(target, filename):
if not target in [FileDestinations.LOCAL]:
if target not in [FileDestinations.LOCAL]:
return make_response("Unknown target: %s" % target, 400)
if _isBusy(target, filename):
+5 -5
View File
@@ -67,10 +67,10 @@ def getInstalledLanguagePacks():
meta["last_update"] - datetime.datetime(1970, 1, 1)
).total_seconds()
l = Locale.parse(locale)
loc = Locale.parse(locale)
meta["locale"] = locale
meta["locale_display"] = l.display_name
meta["locale_english"] = l.english_name
meta["locale_display"] = loc.display_name
meta["locale_english"] = loc.english_name
return meta
if entry.name == "_plugins":
@@ -78,7 +78,7 @@ def getInstalledLanguagePacks():
if not plugin_entry.is_dir():
continue
if not plugin_entry.name in plugin_manager().plugins:
if plugin_entry.name not in plugin_manager().plugins:
continue
plugin_info = plugin_manager().plugins[plugin_entry.name]
@@ -134,7 +134,7 @@ def uploadLanguagePack():
input_upload_name = (
input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
)
if not input_upload_path in request.values or not input_upload_name in request.values:
if input_upload_path not in request.values or input_upload_name not in request.values:
return make_response("No file included", 400)
upload_name = request.values[input_upload_name]
+5 -5
View File
@@ -42,7 +42,7 @@ def printerState():
result = {}
# add temperature information
if not "temperature" in excludes:
if "temperature" not in excludes:
processor = lambda x: x
heated_bed = printerProfileManager.get_current_or_default()["heatedBed"]
heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"]
@@ -56,11 +56,11 @@ def printerState():
result.update({"temperature": _get_temperature_data(processor)})
# add sd information
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
if "sd" not in excludes and settings().getBoolean(["feature", "sdSupport"]):
result.update({"sd": {"ready": printer.is_sd_ready()}})
# add state information
if not "state" in excludes:
if "state" not in excludes:
state = printer.get_current_data()["state"]
result.update({"state": state})
@@ -348,7 +348,7 @@ def printerPrintheadCommand():
validated_values = []
axes = data["axes"]
for axis in axes:
if not axis in valid_axes:
if axis not in valid_axes:
return make_response("Invalid axis: %s" % axis, 400)
validated_values.append(axis)
@@ -417,7 +417,7 @@ def printerCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content type JSON", 400)
try:
+6 -6
View File
@@ -59,7 +59,7 @@ def printerProfilesList():
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def printerProfilesAdd():
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -70,7 +70,7 @@ def printerProfilesAdd():
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if not "profile" in json_data:
if "profile" not in json_data:
return make_response("No profile included in request", 400)
base_profile = printerProfileManager.get_default()
@@ -94,9 +94,9 @@ def printerProfilesAdd():
profile = dict_merge(base_profile, new_profile)
if not "id" in profile:
if "id" not in profile:
return make_response("Profile does not contain mandatory 'id' field", 400)
if not "name" in profile:
if "name" not in profile:
return make_response("Profile does not contain mandatory 'name' field", 400)
try:
@@ -151,7 +151,7 @@ def printerProfilesDelete(identifier):
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def printerProfilesUpdate(identifier):
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -162,7 +162,7 @@ def printerProfilesUpdate(identifier):
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if not "profile" in json_data:
if "profile" not in json_data:
return make_response("No profile included in request", 400)
profile = printerProfileManager.get(identifier)
+2 -3
View File
@@ -14,8 +14,7 @@ from werkzeug.exceptions import BadRequest
import octoprint.plugin
import octoprint.util
from octoprint.access.permissions import Permissions
from octoprint.events import Events, eventManager
from octoprint.server import admin_permission, pluginManager, printer
from octoprint.server import pluginManager, printer
from octoprint.server.api import NO_CONTENT, api
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
from octoprint.settings import settings, valid_boolean_trues
@@ -359,7 +358,7 @@ def _get_plugin_settings():
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def setSettings():
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
+2 -2
View File
@@ -164,7 +164,7 @@ def slicingGetSlicerProfile(slicer, name):
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def slicingAddSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
@@ -207,7 +207,7 @@ def slicingAddSlicerProfile(slicer, name):
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def slicingPatchSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
+6 -6
View File
@@ -53,7 +53,7 @@ def performSystemAction():
if data is None:
data = request.values
if not "action" in data:
if "action" not in data:
return make_response("action to perform is not defined", 400)
return executeSystemCommand("custom", data["action"])
@@ -96,7 +96,7 @@ def executeSystemCommand(source, command):
if not command_spec:
return make_response("Command {}:{} not found".format(source, command), 404)
if not "command" in command_spec:
if "command" not in command_spec:
return make_response(
"Command {}:{} does not define a command to execute, can't proceed".format(
source, command
@@ -175,7 +175,7 @@ def executeSystemCommand(source, command):
def _to_client_specs(specs):
result = list()
for spec in specs.values():
if not "action" in spec or not "source" in spec:
if "action" not in spec or "source" not in spec:
continue
copied = dict(
(k, v)
@@ -249,7 +249,7 @@ def _get_core_command_specs():
def _get_core_command_spec(action):
available_actions = _get_core_command_specs()
if not action in available_actions:
if action not in available_actions:
logging.getLogger(__name__).warning(
"Command for core action {} is not configured, you need to configure the command before it can be used".format(
action
@@ -264,7 +264,7 @@ def _get_custom_command_specs():
specs = collections.OrderedDict()
dividers = 0
for spec in s().get(["system", "actions"]):
if not "action" in spec:
if "action" not in spec:
continue
copied = dict(spec)
copied["source"] = "custom"
@@ -279,7 +279,7 @@ def _get_custom_command_specs():
def _get_custom_command_spec(action):
available_actions = _get_custom_command_specs()
if not action in available_actions:
if action not in available_actions:
return None
return available_actions[action]
+4 -5
View File
@@ -6,11 +6,8 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import base64
import sys
PY3 = sys.version_info[0] == 3
import logging
import sys
import flask as _flask
import flask_login
@@ -22,7 +19,9 @@ from octoprint.plugin import plugin_manager
from octoprint.settings import settings
from octoprint.util import deprecated, to_unicode
from . import flask, sockjs, tornado, watchdog
from . import flask, sockjs, tornado, watchdog # noqa: F401
PY3 = sys.version_info[0] == 3
@deprecated(
+20 -31
View File
@@ -7,14 +7,12 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import collections
import functools
import io
import logging
import os
import threading
import time
import uuid
import flask
import flask.json
@@ -28,6 +26,7 @@ import webassets.utils
from cachelib import BaseCache
from past.builtins import basestring, long
from werkzeug.local import LocalProxy
from werkzeug.utils import cached_property
import octoprint.access.users
import octoprint.plugin
@@ -42,7 +41,7 @@ from octoprint.util.net import is_lan_address
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from scandir import scandir, walk # noqa: F401
# ~~ monkey patching
@@ -130,24 +129,21 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
)
except Exception:
logger.exception(
"Error while trying to load translations for plugin {name}".format(
**locals()
)
"Error while trying to load translations "
"for plugin {name}".format(**locals())
)
else:
if isinstance(plugin_translations, support.Translations):
translations = translations.merge(plugin_translations)
logger.debug(
"Using translation plugin folder {dirname} from plugin {name} for locale {locale}".format(
**locals()
)
"Using translation plugin folder {dirname} from "
"plugin {name} for locale {locale}".format(**locals())
)
break
else:
logger.debug(
"No translations for locale {locale} from plugin {name}".format(
**locals()
)
"No translations for locale {locale} "
"from plugin {name}".format(**locals())
)
# core translations
@@ -158,9 +154,8 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
core_translations = support.Translations.load(dirname, [locale])
if isinstance(core_translations, support.Translations):
logger.debug(
"Using translation core folder {dirname} for locale {locale}".format(
**locals()
)
"Using translation core folder {dirname} "
"for locale {locale}".format(**locals())
)
break
else:
@@ -262,7 +257,7 @@ def fix_webassets_filtertool():
if not self.no_cache_read:
log.debug("Checking cache for key %s", key)
content = self.cache.get(key)
if not content in (False, None):
if content not in (False, None):
log.debug("Using cached result for %s", key)
return MemoryHunk(content)
@@ -513,8 +508,6 @@ class ReverseProxiedEnvironment(object):
# ~~ request and response versions
from werkzeug.utils import cached_property
class OctoPrintFlaskRequest(flask.Request):
environment_wrapper = staticmethod(lambda x: x)
@@ -678,7 +671,7 @@ def passive_login():
settings().getBoolean(["accessControl", "autologinLocal"])
and settings().get(["accessControl", "autologinAs"]) is not None
and settings().get(["accessControl", "localNetworks"]) is not None
and not "active_logout" in flask.request.cookies
and "active_logout" not in flask.request.cookies
and remote_address
):
# attempt local autologin
@@ -873,7 +866,7 @@ def cached(
path=flask.request.path, key=cache_key
)
)
if not "X-From-Cache" in rv.headers:
if "X-From-Cache" not in rv.headers:
rv.headers["X-From-Cache"] = "true"
return rv
@@ -1087,7 +1080,7 @@ class PreemptiveCache(object):
with self._lock:
cache_data = self.get_all_data()
if not root in cache_data:
if root not in cache_data:
cache_data[root] = []
existing, other = split_matched_and_unmatched(data, cache_data[root])
@@ -1195,7 +1188,7 @@ def lastmodified(date):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if not "Last-Modified" in rv.headers:
if "Last-Modified" not in rv.headers:
try:
result = date
if callable(result):
@@ -1585,7 +1578,7 @@ def get_remote_address(request):
def get_json_command_from_request(request, valid_commands):
content_type = request.headers.get("Content-Type", None)
if content_type is None or not "application/json" in content_type:
if content_type is None or "application/json" not in content_type:
return None, None, make_response("Expected content-type JSON", 400)
data = request.get_json()
@@ -1595,12 +1588,12 @@ def get_json_command_from_request(request, valid_commands):
None,
make_response("Malformed JSON body or wrong content-type in request", 400),
)
if not "command" in data or not data["command"] in valid_commands:
if "command" not in data or data["command"] not in valid_commands:
return None, None, make_response("Expected valid command", 400)
command = data["command"]
for parameter in valid_commands[command]:
if not parameter in data:
if parameter not in data:
return (
None,
None,
@@ -1654,8 +1647,6 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
return self._delegate.needs_rebuild(bundle, ctx) or self.changed_settings(ctx)
def changed_settings(self, ctx):
import json
if not ctx.cache:
return False
@@ -1666,13 +1657,11 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
# then we actually return "no update needed". This is because
# otherwise if no cache / a dummy cache is used, then we would be
# rebuilding every single time.
if not cached_hash is None:
if cached_hash is not None:
return cached_hash != current_hash
return False
def build_done(self, bundle, ctx):
import json
self._delegate.build_done(bundle, ctx)
if not ctx.cache:
return
@@ -1825,7 +1814,7 @@ def collect_plugin_assets(preferred_stylesheet="css"):
)
else:
for stylesheet in supported_stylesheets:
if not stylesheet in all_assets:
if stylesheet not in all_assets:
continue
for asset in all_assets[stylesheet]:
+3 -3
View File
@@ -527,7 +527,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport
for name, part in self._parts.items():
if "filename" in part:
# add form fields for filename, path, size and content_type for all files contained in the request
if not "path" in part:
if "path" not in part:
continue
parameters = {
@@ -736,7 +736,7 @@ class WsgiInputContainer(object):
headers = [
(header, value)
for header, value in headers
if not header.lower() in self.removed_headers
if header.lower() not in self.removed_headers
]
start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
@@ -1432,7 +1432,7 @@ class GlobalHeaderTransform(tornado.web.OutputTransform):
def transform_first_chunk(self, status_code, headers, chunk, finishing):
for header, value in self.HEADERS.items():
if not header in headers:
if header not in headers:
headers[header] = value
for header, value in self.FORCED_HEADERS.items():
headers[header] = value
+1 -1
View File
@@ -186,7 +186,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
# noinspection PyBroadException
try:
shutil.move(path, "{}.failed".format(path))
except:
except Exception:
# something went really wrong here.... but we can't do anything about it, so just log it
self._logger.exception(
"There was an error while trying to mark {} as failed in the watched folder".format(
+20 -20
View File
@@ -29,7 +29,7 @@ from past.builtins import basestring
import octoprint.plugin
from octoprint.access.permissions import OctoPrintPermission, Permissions
from octoprint.filemanager import full_extension_tree, get_all_extensions
from octoprint.server import (
from octoprint.server import ( # noqa: F401
BRANCH,
DISPLAY_VERSION,
LOCALES,
@@ -161,7 +161,7 @@ def _add_additional_assets(hook):
assets = hook()
if isinstance(assets, (tuple, list)):
result += assets
except:
except Exception:
_logger.exception(
"Error fetching theming CSS to include from plugin {}".format(name),
extra={"plugin": name},
@@ -222,7 +222,7 @@ def login():
additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming")
render_kwargs.update({"theming": additional_assets})
except:
except Exception:
_logger.exception("Error processing theming CSS, ignoring")
return render_template("login.jinja2", **render_kwargs)
@@ -245,7 +245,7 @@ def recovery():
try:
additional_assets = _add_additional_assets("octoprint.theming.recovery")
render_kwargs.update({"theming": additional_assets})
except:
except Exception:
_logger.exception("Error processing theming CSS, ignoring")
return render_template("recovery.jinja2", **render_kwargs)
@@ -713,12 +713,12 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
first_run = settings().getBoolean(["server", "firstRun"])
locales = {}
for l in LOCALES:
for loc in LOCALES:
try:
locales[l.language] = {
"language": l.language,
"display": l.display_name,
"english": l.english_name,
locales[loc.language] = {
"language": loc.language,
"display": loc.display_name,
"english": loc.english_name,
}
except Exception:
_logger.exception("Error while collecting available locales")
@@ -1277,8 +1277,8 @@ def fetch_template_data(refresh=False):
x = plugin_aliases[t][x]
if (
x in templates[t]["entries"]
and not x in configured_disabled
and not x in result
and x not in configured_disabled
and x not in result
):
result.append(x)
templates[t]["order"] = result
@@ -1287,9 +1287,9 @@ def fetch_template_data(refresh=False):
templates[t]["order"] += [
x
for x in default_order
if not x in templates[t]["order"]
if x not in templates[t]["order"]
and x in templates[t]["entries"]
and not x in configured_disabled
and x not in configured_disabled
]
all_ordered = set(templates[t]["order"])
@@ -1421,13 +1421,13 @@ def _process_template_configs(name, implementation, configs, rules):
for config in configs:
if not isinstance(config, dict):
continue
if not "type" in config:
if "type" not in config:
continue
template_type = config["type"]
del config["type"]
if not template_type in rules:
if template_type not in rules:
continue
rule = rules[template_type]
@@ -1465,14 +1465,14 @@ def _process_template_configs(name, implementation, configs, rules):
def _process_template_config(name, implementation, rule, config=None, counter=1):
if "mandatory" in rule:
for mandatory in rule["mandatory"]:
if not mandatory in config:
if mandatory not in config:
return None
if config is None:
config = {}
data = dict(config)
if not "suffix" in data and counter > 1:
if "suffix" not in data and counter > 1:
data["suffix"] = "_%d" % counter
if "div" in data:
@@ -1489,13 +1489,13 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
)
return None
if not "template" in data:
if "template" not in data:
data["template"] = rule["template"](name)
if not "name" in data:
if "name" not in data:
data["name"] = implementation._plugin_name
if not "custom_bindings" in data or data["custom_bindings"]:
if "custom_bindings" not in data or data["custom_bindings"]:
data_bind = "allowBindings: true"
if "data_bind" in data:
data_bind = data_bind + ", " + data["data_bind"]
+13 -17
View File
@@ -30,10 +30,6 @@ import os
import re
import sys
import time
import uuid
# noinspection PyCompatibility
from builtins import bytes
import yaml
import yaml.parser
@@ -558,7 +554,7 @@ class HierarchicalChainMap(ChainMap):
def _get_next(cls, key, node, only_local=False):
if isinstance(node, dict):
return node[key]
elif only_local and not key in node.maps[0]:
elif only_local and key not in node.maps[0]:
raise KeyError(key)
else:
return cls._hierarchy_for_key(key, node)
@@ -752,7 +748,7 @@ class Settings(object):
def get_source(self, environment, template):
if self._sep in template:
prefix, name = template.split(self._sep, 1)
if not prefix in self._mapping:
if prefix not in self._mapping:
raise TemplateNotFound(template)
return self._mapping[prefix].get_source(environment, name)
return self._default.get_source(environment, template)
@@ -1125,7 +1121,7 @@ class Settings(object):
or "extruderOffsets" in printer_parameters
):
dirty = True
if not "extruder" in default_profile:
if "extruder" not in default_profile:
default_profile["extruder"] = {}
if "numExtruders" in printer_parameters:
@@ -1144,7 +1140,7 @@ class Settings(object):
if "bedDimensions" in printer_parameters:
dirty = True
bed_dimensions = printer_parameters["bedDimensions"]
if not "volume" in default_profile:
if "volume" not in default_profile:
default_profile["volume"] = {}
if (
@@ -1166,7 +1162,7 @@ class Settings(object):
del config["printerParameters"]["bedDimensions"]
if dirty:
if not "printerProfiles" in config:
if "printerProfiles" not in config:
config["printerProfiles"] = {}
config["printerProfiles"]["defaultProfile"] = default_profile
return dirty
@@ -1191,7 +1187,7 @@ class Settings(object):
scheme = config["server"]["scheme"]
del config["server"]["scheme"]
if not "reverseProxy" in config["server"] or not isinstance(
if "reverseProxy" not in config["server"] or not isinstance(
config["server"]["reverseProxy"], dict
):
config["server"]["reverseProxy"] = {}
@@ -1357,13 +1353,13 @@ class Settings(object):
migrate_to = migration_map.get(action)
if migrate_to is not None:
if (
not "server" in config
or not "commands" in config["server"]
or not migrate_to in config["server"]["commands"]
"server" not in config
or "commands" not in config["server"]
or migrate_to not in config["server"]["commands"]
):
if not "server" in config:
if "server" not in config:
config["server"] = {}
if not "commands" in config["server"]:
if "commands" not in config["server"]:
config["server"]["commands"] = {}
config["server"]["commands"][migrate_to] = command
self._logger.info(
@@ -1528,9 +1524,9 @@ class Settings(object):
and "enabled" in config["gcodeViewer"]
and not config["gcodeViewer"]["enabled"]
):
if not "plugins" in config:
if "plugins" not in config:
config["plugins"] = {}
if not "_disabled" in config["plugins"]:
if "_disabled" not in config["plugins"]:
config["plugins"]["_disabled"] = []
config["plugins"]["_disabled"].append("gcodeviewer")
del config["gcodeViewer"]["enabled"]
+16 -22
View File
@@ -19,14 +19,8 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
import logging
import os
import octoprint.events
import octoprint.plugin
@@ -225,7 +219,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.SlicerNotConfigured: The ``slicer`` is not yet configured and ``require_configured`` was set to True.
"""
if not slicer in self._slicers:
if slicer not in self._slicers:
raise UnknownSlicer(slicer)
if require_configured and not self._slicers[slicer].is_slicer_configured():
@@ -313,8 +307,8 @@ class SlicingManager(object):
if callback_kwargs is None:
callback_kwargs = {}
if not slicer_name in self.configured_slicers:
if not slicer_name in self.registered_slicers:
if slicer_name not in self.configured_slicers:
if slicer_name not in self.registered_slicers:
error = "No such slicer: {slicer_name}".format(**locals())
exc = UnknownSlicer(slicer_name)
else:
@@ -428,7 +422,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.UnknownProfile: The profile for slicer ``slicer`` named ``name`` does not exist.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
try:
@@ -485,7 +479,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.ProfileAlreadyExists: A profile with name ``name`` already exists for ``slicer`` and ``allow_overwrite`` is
False.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
if not isinstance(profile, SlicingProfile):
@@ -534,7 +528,7 @@ class SlicingManager(object):
return profile
def _temporary_profile(self, slicer, name=None, overrides=None):
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
profile = self._get_default_profile(slicer)
@@ -564,7 +558,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.CouldNotDeleteProfile: There was an error while deleting the profile.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
if not name:
@@ -613,15 +607,15 @@ class SlicingManager(object):
was unknown for slicer ``slicer`` and ``require_exists`` was
true.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
if require_configured and not slicer in self.configured_slicers:
if require_configured and slicer not in self.configured_slicers:
raise SlicerNotConfigured(slicer)
if not name:
raise ValueError("name must be set")
if require_exists and not name in self.all_profiles(
if require_exists and name not in self.all_profiles(
slicer, require_configured=require_configured
):
raise UnknownProfile(slicer, name)
@@ -654,9 +648,9 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.SlicerNotConfigured: The slicer ``slicer`` is not configured and ``require_configured`` was True.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
if require_configured and not slicer in self.configured_slicers:
if require_configured and slicer not in self.configured_slicers:
raise SlicerNotConfigured(slicer)
slicer_profile_path = self.get_slicer_profile_path(slicer)
@@ -675,7 +669,7 @@ class SlicingManager(object):
(float) the time stamp of the last modification of the slicer's profiles
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
slicer_profile_path = self.get_slicer_profile_path(slicer)
@@ -697,7 +691,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
path = os.path.join(self._profile_path, slicer)
@@ -725,7 +719,7 @@ class SlicingManager(object):
~octoprint.slicing.exceptions.UnknownProfile: The profile named ``name`` doesn't exist and ``must_exist`` was True.
"""
if not slicer in self.registered_slicers:
if slicer not in self.registered_slicers:
raise UnknownSlicer(slicer)
if not name:
+1 -1
View File
@@ -348,7 +348,7 @@ def _create_render_always_handler(name, gcode=None):
def register_callback(callback):
if not callback in _update_callbacks:
if callback not in _update_callbacks:
_update_callbacks.append(callback)
+5 -5
View File
@@ -7,19 +7,19 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
# Wrapper to the new access.users location
from octoprint.access.users import * # noqa: F403 ## possibly used by other modules
from octoprint.access.users import User, deprecated
AccessUser = User
import warnings
from octoprint.access.users import * # noqa: F401, F403 ## possibly used by other modules
from octoprint.access.users import User, deprecated
warnings.warn(
"octoprint.users is deprecated, use octoprint.access.users instead",
DeprecationWarning,
stacklevel=2,
)
AccessUser = User
class User(AccessUser):
@deprecated(
+13 -9
View File
@@ -38,8 +38,12 @@ except ImportError:
from past.builtins import basestring, unicode
from octoprint import UMASK
from octoprint.util.connectivity import ConnectivityChecker
from octoprint.util.net import address_for_client, interface_addresses, server_reachable
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
from octoprint.util.net import ( # noqa: F401
address_for_client,
interface_addresses,
server_reachable,
)
logger = logging.getLogger(__name__)
@@ -638,7 +642,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
full_name_format = "{filename}.{extension}" if extension else "{filename}"
result = full_name_format.format(filename=filename, extension=extension)
if len(filename) <= 8 and not result in existing_filenames:
if len(filename) <= 8 and result not in existing_filenames:
# early exit
return result
@@ -709,7 +713,7 @@ def filter_non_utf8(line):
return True
def chunks(l, n):
def chunks(l, n): # noqa: E741
"""
Yield successive n-sized chunks from l.
@@ -840,7 +844,7 @@ def dict_sanitize(a, b):
result = deepcopy(a)
for k, v in a.items():
if not k in b:
if k not in b:
del result[k]
elif isinstance(v, dict):
result[k] = dict_sanitize(v, b[k])
@@ -942,7 +946,7 @@ def dict_contains_keys(keys, dictionary):
return False
for k, v in keys.items():
if not k in dictionary:
if k not in dictionary:
return False
elif isinstance(v, dict):
if not dict_contains_keys(v, dictionary[k]):
@@ -1850,11 +1854,11 @@ def time_this(
timing = (time.time() - start) * 1000.0
func = fqfn(f)
l = logtarget
lt = logtarget
if expand_logtarget:
l += "." + func
lt += "." + func
logger = logging.getLogger(l)
logger = logging.getLogger(lt)
if logger.isEnabledFor(logging.DEBUG):
data = {"func": func, "timing": timing}
if incl_func_args:
+25 -25
View File
@@ -29,13 +29,13 @@ from collections import deque
import serial
import wrapt
from past.builtins import basestring, unicode
from past.builtins import basestring
import octoprint.plugin
from octoprint.events import Events, eventManager
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import default_settings, settings
from octoprint.settings import settings
from octoprint.util import (
CountedEvent,
PrependableQueue,
@@ -1264,7 +1264,7 @@ class MachineCom(object):
else:
if retval is None:
continue
if not isinstance(retval, (list, tuple)) or not len(retval) in [2, 3, 4]:
if not isinstance(retval, (list, tuple)) or len(retval) not in [2, 3, 4]:
continue
def to_list(data, t):
@@ -1743,7 +1743,7 @@ class MachineCom(object):
self.STATE_RESUMING,
)
if not self._state in valid_paused_states + valid_running_states:
if self._state not in valid_paused_states + valid_running_states:
return
with self._jobLock:
@@ -2015,7 +2015,7 @@ class MachineCom(object):
for n in range(maxToolNum + 1):
tool = "T%d" % n
if not tool in parsedTemps:
if tool not in parsedTemps:
if shared_nozzle:
actual, target = shared_temp
else:
@@ -2077,7 +2077,7 @@ class MachineCom(object):
self._changeState(self.STATE_DETECT_SERIAL)
self._perform_detection_step(init=True)
if not self._state in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
# we got cancelled during connection, bail
return
@@ -2257,7 +2257,7 @@ class MachineCom(object):
##~~ SD file list
# if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing
if self._sdFileList and not "End file list" in line:
if self._sdFileList and "End file list" not in line:
preprocessed_line = line
fileinfo = preprocessed_line.split(None, 2)
if len(fileinfo) == 3:
@@ -2364,7 +2364,7 @@ class MachineCom(object):
or not self._dwelling_until
or now > self._dwelling_until
)
and not self._state in (self.STATE_DETECT_SERIAL,)
and self._state not in (self.STATE_DETECT_SERIAL,)
):
# We have two timeout variants:
#
@@ -2452,7 +2452,7 @@ class MachineCom(object):
or line.startswith("T:")
or " T0:" in line
or line.startswith("T0:")
or ((" B:" in line or line.startswith("B:")) and not "A:" in line)
or ((" B:" in line or line.startswith("B:")) and "A:" not in line)
):
if (
@@ -2733,7 +2733,7 @@ class MachineCom(object):
try:
current = int(match.group("current"))
total = int(match.group("total"))
except:
except Exception:
self._logger.exception("Error while parsing SD status report")
else:
if (
@@ -2850,7 +2850,7 @@ class MachineCom(object):
if (
feedback_controls
and feedback_matcher
and not "_all" in feedback_errors
and "_all" not in feedback_errors
):
try:
self._process_registered_message(
@@ -2985,7 +2985,7 @@ class MachineCom(object):
self._finish_heatup()
if not self._state in self.OPERATIONAL_STATES:
if self._state not in self.OPERATIONAL_STATES:
return
if self._resendDelta is not None and self._resendNextCommand():
@@ -3242,7 +3242,7 @@ class MachineCom(object):
try:
feedback_key = match_key[len("group") :]
if (
not feedback_key in feedback_controls
feedback_key not in feedback_controls
or feedback_key in feedback_errors
or feedback_match.group(match_key) is None
):
@@ -4435,7 +4435,7 @@ class MachineCom(object):
)
# make sure we don't allow multi entry results in anything but the queuing phase
if not phase in ("queuing",) and len(normalized) > 1:
if phase not in ("queuing",) and len(normalized) > 1:
self._logger.error(
"Error while processing hook {name} for phase {phase} and command {command}: "
"Hook returned multi-entry result for phase {phase} and command {command}. "
@@ -5076,7 +5076,7 @@ class MachineCom(object):
return not self._sanity_check_tools or (
tool
< self._printerProfileManager.get_current_or_default()["extruder"]["count"]
and not tool in self._knownInvalidTools
and tool not in self._knownInvalidTools
)
def _reset_position_timers(self):
@@ -5090,13 +5090,13 @@ class MachineCom(object):
def _atcommand_pause_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if not "script:afterPrintPaused" in tags:
if "script:afterPrintPaused" not in tags:
self.setPause(True, tags={"trigger:atcommand_pause"})
def _atcommand_cancel_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if not "script:afterPrintCancelled" in tags:
if "script:afterPrintCancelled" not in tags:
self.cancelPrint(tags={"trigger:atcommand_cancel"})
_atcommand_abort_queuing = _atcommand_cancel_queuing
@@ -5104,7 +5104,7 @@ class MachineCom(object):
def _atcommand_resume_queuing(self, command, parameters, tags=None, *args, **kwargs):
if tags is None:
tags = set()
if not "script:beforePrintResumed" in tags:
if "script:beforePrintResumed" not in tags:
self.setPause(False, tags={"trigger:atcommand_resume"})
##~~ command phase handlers
@@ -5129,8 +5129,8 @@ class MachineCom(object):
if (
self.isPrinting()
and gcode in self._pausing_commands
and not "trigger:cancel" in tags
and not "trigger:pause" in tags
and "trigger:cancel" not in tags
and "trigger:pause" not in tags
):
self._logger.info("Pausing print job due to command {}".format(gcode))
self.setPause(True)
@@ -5682,7 +5682,7 @@ def apply_temperature_offsets(line, offsets, current_tool=None):
return line
groups = match.groupdict()
if not "temperature" in groups or groups["temperature"] is None:
if "temperature" not in groups or groups["temperature"] is None:
return line
offset = 0
@@ -5716,7 +5716,7 @@ def apply_temperature_offsets(line, offsets, current_tool=None):
def strip_comment(line):
if not ";" in line:
if ";" not in line:
# shortcut
return line
@@ -5747,7 +5747,7 @@ def convert_pause_triggers(configured_triggers):
triggers = {"enable": [], "disable": [], "toggle": []}
for trigger in configured_triggers:
if not "regex" in trigger or not "type" in trigger:
if "regex" not in trigger or "type" not in trigger:
continue
try:
@@ -5850,7 +5850,7 @@ def canonicalize_temperatures(parsed, current):
"""
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
if not "T" in reported_extruders:
if "T" not in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
@@ -6014,7 +6014,7 @@ def parse_capability_line(line):
return None
capability, flag = parts
if not flag in ("0", "1"):
if flag not in ("0", "1"):
# wrong format, can't parse this
return None
+5 -5
View File
@@ -28,9 +28,9 @@ except ImportError: # pragma: no cover
# License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt)
# Website: https://github.com/tartley/colorama/
_ANSI_CSI_PATTERN = (
b"\001?\033\[(\??(?:\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
b"\001?\033\\[(\\??(?:\\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
)
_ANSI_OSC_PATTERN = b"\001?\033\]((?:.|;)*?)(\x07)\002?" # Operating System Command
_ANSI_OSC_PATTERN = b"\001?\033\\]((?:.|;)*?)(\x07)\002?" # Operating System Command
_ANSI_REGEX = re.compile(b"|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN]))
@@ -224,11 +224,11 @@ class CommandlineCaller(object):
def process_lines(lines, logger):
if not lines:
return []
l = self._preprocess_lines(
processed = self._preprocess_lines(
*map(lambda x: to_unicode(x, errors="replace"), lines)
)
logger(*l)
return list(l)
logger(*processed)
return list(processed)
def process_stdout(lines):
return process_lines(lines, self._log_stdout)
+2 -2
View File
@@ -10,7 +10,7 @@ import os
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from scandir import scandir, walk # noqa: F401
from jinja2 import nodes
from jinja2.ext import Extension
@@ -77,7 +77,7 @@ class SelectedFilesLoader(BaseLoader):
self.encoding = encoding
def get_source(self, environment, template):
if not template in self.files:
if template not in self.files:
raise TemplateNotFound(template)
from jinja2.loaders import open_if_exists
-2
View File
@@ -7,10 +7,8 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import io
import logging
import os
import re
import socket
import sys
import threading
import netaddr
import netifaces
+4 -4
View File
@@ -43,7 +43,7 @@ class PipCaller(CommandlineCaller):
# strip --process-dependency-links for versions that don't support it
if (
not pip_version in cls.process_dependency_links
pip_version not in cls.process_dependency_links
and "--process-dependency-links" in args
):
logger.debug(
@@ -54,7 +54,7 @@ class PipCaller(CommandlineCaller):
args.remove("--process-dependency-links")
# strip --no-cache-dir for versions that don't support it
if not pip_version in cls.no_cache_dir and "--no-cache-dir" in args:
if pip_version not in cls.no_cache_dir and "--no-cache-dir" in args:
logger.debug(
"Found --no-cache-dir flag, version {} doesn't support that yet though, removing.".format(
pip_version
@@ -64,7 +64,7 @@ class PipCaller(CommandlineCaller):
# strip --disable-pip-version-check for versions that don't support it
if (
not pip_version in cls.disable_pip_version_check
pip_version not in cls.disable_pip_version_check
and "--disable-pip-version-check" in args
):
logger.debug(
@@ -75,7 +75,7 @@ class PipCaller(CommandlineCaller):
args.remove("--disable-pip-version-check")
# add --no-use-wheel for versions that otherwise break
if pip_version in cls.no_use_wheel and not "--no-use-wheel" in args:
if pip_version in cls.no_use_wheel and "--no-use-wheel" not in args:
logger.debug(
"Version {} needs --no-use-wheel to properly work.".format(pip_version)
)
+4 -4
View File
@@ -70,7 +70,7 @@ class SockJSRouter(object):
def __init__(self,
connection,
prefix='',
user_settings=dict(),
user_settings={},
io_loop=None,
session_kls=None):
"""Constructor.
@@ -119,7 +119,7 @@ class SockJSRouter(object):
base = prefix + r'/[^/.]+/(?P<session_id>[^/.]+)'
# Generate global handler URLs
self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], dict(server=self))
self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], {"server": self})
for p in GLOBAL_HANDLERS]
for k, v in TRANSPORTS.items():
@@ -130,11 +130,11 @@ class SockJSRouter(object):
self._transport_urls.append(
(r'%s/%s$' % (base, k),
v,
dict(server=self))
{"server": self})
)
# Generate static URLs
self._transport_urls.extend([('%s%s' % (prefix, k), v, dict(server=self))
self._transport_urls.extend([('%s%s' % (prefix, k), v, {"server": self})
for k, v in STATIC_HANDLERS.items()])
@property
+1 -1
View File
@@ -78,7 +78,7 @@ class SessionContainer(object):
clean them up all the time.
"""
def __init__(self):
self._items = dict()
self._items = {}
self._queue = []
def add(self, session):
+4 -4
View File
@@ -127,9 +127,9 @@ class InfoHandler(PreflightHandler):
self.disable_cache()
self.set_header('Content-Type', 'application/json; charset=UTF-8')
options = dict(websocket=self.server.websockets_enabled,
cookie_needed=self.server.cookie_needed,
origins=['*:*'],
entropy=random.randint(0, MAXSIZE))
options = {"websocket": self.server.websockets_enabled,
"cookie_needed": self.server.cookie_needed,
"origins": ['*:*'],
"entropy": random.randint(0, MAXSIZE)}
self.write(json_encode(options))
+6 -9
View File
@@ -59,7 +59,7 @@ class StatsCollector(object):
self.sess_active = 0
# Avoid circular reference
self.sess_transports = dict()
self.sess_transports = {}
# Connections
self.conn_active = 0
@@ -81,18 +81,15 @@ class StatsCollector(object):
def dump(self):
"""Return dictionary with current statistical information"""
data = dict(
# Sessions
sessions_active=self.sess_active,
data = {"sessions_active": self.sess_active,
# Connections
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
"connections_active": self.conn_active,
"connections_ps": self.conn_ps.last_average,
# Packets
packets_sent_ps=self.pack_sent_ps.last_average,
packets_recv_ps=self.pack_recv_ps.last_average
)
"packets_sent_ps": self.pack_sent_ps.last_average,
"packets_recv_ps": self.pack_recv_ps.last_average}
for k, v in self.sess_transports.items():
data['transp_' + k] = v
+2 -4
View File
@@ -1612,12 +1612,10 @@ class ZeroconfServiceTypes(object):
def get_all_addresses(address_family):
return list(set(
addr['addr']
return list({addr['addr']
for iface in netifaces.interfaces()
for addr in netifaces.ifaddresses(iface).get(address_family, [])
if addr.get('netmask') != HOST_ONLY_NETWORK_MASK
))
if addr.get('netmask') != HOST_ONLY_NETWORK_MASK})
def normalize_interface_choice(choice, address_family):
+4 -4
View File
@@ -58,7 +58,7 @@ class SocketClient(object):
# prepare a bunch of callback methods
import functools
callbacks = dict()
callbacks = {}
for callback in ("on_open", "on_message", "on_error", "on_close"):
# now, normally we could just use functools.partial for something like
# this, but websocket does a type check against a python function type
@@ -272,7 +272,7 @@ class Client(object):
return self.post(path, data, encoding="json", params=params, timeout=timeout)
def post_command(self, path, command, additional=None, timeout=None):
data = dict(command=command)
data = {"command": command}
if additional:
data.update(additional)
return self.post_json(path, data, params=data, timeout=timeout)
@@ -299,9 +299,9 @@ class Client(object):
with io.open(file_path, "rb") as fp:
if content_type:
files = dict(file=(file_name, fp, content_type))
files = {"file": (file_name, fp, content_type)}
else:
files = dict(file=(file_name, fp))
files = {"file": (file_name, fp)}
response = self.request(
"POST", path, data=additional, files=files, params=params, timeout=timeout
+54 -54
View File
@@ -98,7 +98,7 @@ class CleanCommand(_clean):
if eggs is None:
eggs = []
return type(cls)(
cls.__name__, (cls,), dict(source_folder=source_folder, eggs=eggs)
cls.__name__, (cls,), {"source_folder": source_folder, "eggs": eggs}
)
def initialize_options(self):
@@ -176,7 +176,7 @@ class NewTranslation(Command):
raise ValueError("output_dir must not be None")
return type(cls)(
cls.__name__, (cls,), dict(pot_file=pot_file, output_dir=output_dir)
cls.__name__, (cls,), {"pot_file": pot_file, "output_dir": output_dir}
)
def __init__(self, dist, **kw):
@@ -229,13 +229,13 @@ class ExtractTranslation(Command):
return type(cls)(
cls.__name__,
(cls,),
dict(
mapping_file=mapping_file,
pot_file=pot_file,
input_dirs=input_dirs,
mail_address=mail_address,
copyright_holder=copyright_holder,
),
{
"mapping_file": mapping_file,
"pot_file": pot_file,
"input_dirs": input_dirs,
"mail_address": mail_address,
"copyright_holder": copyright_holder,
},
)
def __init__(self, dist, **kw):
@@ -295,14 +295,14 @@ class RefreshTranslation(Command):
return type(cls)(
cls.__name__,
(cls,),
dict(
mapping_file=mapping_file,
pot_file=pot_file,
input_dirs=input_dirs,
mail_address=mail_address,
copyright_holder=copyright_holder,
output_dir=output_dir,
),
{
"mapping_file": mapping_file,
"pot_file": pot_file,
"input_dirs": input_dirs,
"mail_address": mail_address,
"copyright_holder": copyright_holder,
"output_dir": output_dir,
},
)
def __init__(self, dist, **kw):
@@ -347,7 +347,7 @@ class CompileTranslation(Command):
if output_dir is None:
raise ValueError("output_dir must not be None")
return type(cls)(cls.__name__, (cls,), dict(output_dir=output_dir))
return type(cls)(cls.__name__, (cls,), {"output_dir": output_dir})
def __init__(self, dist, **kw):
from babel.messages import frontend as babel
@@ -382,7 +382,7 @@ class BundleTranslation(Command):
raise ValueError("target_dir must not be None")
return type(cls)(
cls.__name__, (cls,), dict(source_dir=source_dir, target_dir=target_dir)
cls.__name__, (cls,), {"source_dir": source_dir, "target_dir": target_dir}
)
def initialize_options(self):
@@ -439,11 +439,11 @@ class PackTranslation(Command):
return type(cls)(
cls.__name__,
(cls,),
dict(
source_dir=source_dir,
pack_name_prefix=pack_name_prefix,
pack_path_prefix=pack_path_prefix,
),
{
"source_dir": source_dir,
"pack_name_prefix": pack_name_prefix,
"pack_path_prefix": pack_path_prefix,
},
)
def initialize_options(self):
@@ -518,16 +518,16 @@ def get_babel_commandclasses(
mail_address="i18n@octoprint.org",
copyright_holder="The OctoPrint Project",
):
result = dict(
babel_new=NewTranslation.for_options(pot_file=pot_file, output_dir=output_dir),
babel_extract=ExtractTranslation.for_options(
result = {
"babel_new": NewTranslation.for_options(pot_file=pot_file, output_dir=output_dir),
"babel_extract": ExtractTranslation.for_options(
mapping_file=mapping_file,
pot_file=pot_file,
input_dirs=input_dirs,
mail_address=mail_address,
copyright_holder=copyright_holder,
),
babel_refresh=RefreshTranslation.for_options(
"babel_refresh": RefreshTranslation.for_options(
mapping_file=mapping_file,
pot_file=pot_file,
input_dirs=input_dirs,
@@ -535,13 +535,13 @@ def get_babel_commandclasses(
mail_address=mail_address,
copyright_holder=copyright_holder,
),
babel_compile=CompileTranslation.for_options(output_dir=output_dir),
babel_pack=PackTranslation.for_options(
"babel_compile": CompileTranslation.for_options(output_dir=output_dir),
"babel_pack": PackTranslation.for_options(
source_dir=output_dir,
pack_name_prefix=pack_name_prefix,
pack_path_prefix=pack_path_prefix,
),
)
}
if bundled_dir is not None:
result["babel_bundle"] = BundleTranslation.for_options(
@@ -596,12 +596,12 @@ def create_plugin_setup_parameters(
requires = ["OctoPrint"] + list(requires)
if extra_requires is None:
extra_requires = dict()
extra_requires = {}
if not isinstance(extra_requires, dict):
raise ValueError("extra_requires must be a dict")
if cmdclass is None:
cmdclass = dict()
cmdclass = {}
if not isinstance(cmdclass, dict):
raise ValueError("cmdclass must be a dict")
@@ -617,11 +617,11 @@ def create_plugin_setup_parameters(
eggs = [egg] + eggs
cmdclass.update(
dict(
clean=CleanCommand.for_options(
{
"clean": CleanCommand.for_options(
source_folder=os.path.join(source_folder, package), eggs=eggs
)
)
}
)
translation_dir = os.path.join(source_folder, "translations")
@@ -651,35 +651,35 @@ def create_plugin_setup_parameters(
)
print("Found packages: {packages!r}".format(**locals()))
return dict(
name=name,
version=version,
description=description,
author=author,
author_email=mail,
url=url,
license=license,
return {
"name": name,
"version": version,
"description": description,
"author": author,
"author_email": mail,
"url": url,
"license": license,
# adding new commands
cmdclass=cmdclass,
"cmdclass": cmdclass,
# we only have our plugin package to install
packages=packages,
"packages": packages,
# we might have additional data files in sub folders that need to be installed too
package_data={
"package_data": {
package: package_data_dirs(
os.path.join(source_folder, package),
["static", "templates", "translations"] + additional_data,
)
},
include_package_data=True,
"include_package_data": True,
# If you have any package data that needs to be accessible on the file system, such as templates or static assets
# this plugin is not zip_safe.
zip_safe=False,
install_requires=requires,
extras_require=extra_requires,
dependency_links=dependency_links,
"zip_safe": False,
"install_requires": requires,
"extras_require": extra_requires,
"dependency_links": dependency_links,
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
# That way OctoPrint will be able to find the plugin and load it.
entry_points={
"entry_points": {
"octoprint.plugin": ["{identifier} = {package}".format(**locals())]
},
)
}
+1 -1
View File
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import sys # noqa: F401
OPEN_SIGNATURE = "io.open"
+10 -10
View File
@@ -4,16 +4,16 @@ from __future__ import absolute_import, division, print_function, unicode_litera
def plugin_permissions(components):
return [
dict(
name="fancy permission",
description="My Fancy new Permission",
roles=["fancy"],
),
dict(
name="fancy permission with two roles",
description="My Fancy new Permission with two roles",
roles=["fancy1", "fancy2"],
),
{
"name": "fancy permission",
"description": "My Fancy new Permission",
"roles": ["fancy"],
},
{
"name": "fancy permission with two roles",
"description": "My Fancy new Permission with two roles",
"roles": ["fancy1", "fancy2"],
},
]
+1 -3
View File
@@ -7,9 +7,7 @@ Unit tests for octoprint.access.permissions
import unittest
import ddt
from octoprint.access.permissions import OctoPrintPermission, Permissions
from octoprint.access.permissions import Permissions
class PermissionsTest(unittest.TestCase):
+3 -3
View File
@@ -21,7 +21,7 @@ class SessionUserTestCase(unittest.TestCase):
True,
permissions=[],
apikey="apikey",
settings=dict(key="value"),
settings={"key": "value"},
)
def test_two_sessions(self):
@@ -40,13 +40,13 @@ class SessionUserTestCase(unittest.TestCase):
# change should propagate from User to SessionUser
self.user.set_setting("otherkey", "othervalue")
self.assertDictEqual(
dict(key="value", otherkey="othervalue"), session1.get_all_settings()
{"key": "value", "otherkey": "othervalue"}, session1.get_all_settings()
)
# change should propagate from SessionUser to SessionUser
session2.set_setting("otherkey", "yetanothervalue")
self.assertDictEqual(
dict(key="value", otherkey="yetanothervalue"), session1.get_all_settings()
{"key": "value", "otherkey": "yetanothervalue"}, session1.get_all_settings()
)
def test_repr(self):
+62 -67
View File
@@ -25,29 +25,29 @@ class FilemanagerMethodTest(unittest.TestCase):
self.plugin_manager = mock.MagicMock()
hook_extensions = dict(
some_plugin=lambda: dict(dict(machinecode=dict(foo=["foo", "f"]))),
other_plugin=lambda: dict(dict(model=dict(amf=["amf"]))),
mime_map=lambda: dict(
mime_map=dict(
mime_map_yes=octoprint.filemanager.ContentTypeMapping(
hook_extensions = {
"some_plugin": lambda: dict({"machinecode": {"foo": ["foo", "f"]}}),
"other_plugin": lambda: dict({"model": {"amf": ["amf"]}}),
"mime_map": lambda: {
"mime_map": {
"mime_map_yes": octoprint.filemanager.ContentTypeMapping(
["mime_map_yes"], "application/mime_map_yes"
)
)
),
mime_detect=lambda: dict(
dict(
machinecode=dict(
mime_detect_yes=octoprint.filemanager.ContentTypeDetector(
}
},
"mime_detect": lambda: dict(
{
"machinecode": {
"mime_detect_yes": octoprint.filemanager.ContentTypeDetector(
["mime_detect_yes"], lambda x: "application/mime_detect_yes"
),
mime_detect_no=octoprint.filemanager.ContentTypeDetector(
"mime_detect_no": octoprint.filemanager.ContentTypeDetector(
["mime_detect_no"], lambda x: None
),
)
)
}
}
),
)
}
self.plugin_manager.get_hooks.return_value = hook_extensions
self.plugin_manager_getter.return_value = self.plugin_manager
@@ -130,7 +130,7 @@ class FilemanagerMethodTest(unittest.TestCase):
def hook():
raise RuntimeError("Boo!")
self.plugin_manager.get_hooks.return_value = dict(hook=hook)
self.plugin_manager.get_hooks.return_value = {"hook": hook}
with mock.patch("octoprint.filemanager.logging") as patched_logging:
logger = mock.MagicMock()
@@ -181,7 +181,7 @@ class FileManagerTest(unittest.TestCase):
)
self.local_storage.analysis_backlog = iter([])
self.storage_managers = dict()
self.storage_managers = {}
self.storage_managers[
octoprint.filemanager.FileDestinations.LOCAL
] = self.local_storage
@@ -205,7 +205,7 @@ class FileManagerTest(unittest.TestCase):
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
self.local_storage.split_path.return_value = ("", "test.gcode")
test_profile = dict(id="_default", name="My Default Profile")
test_profile = {"id": "_default", "name": "My Default Profile"}
self.printer_profile_manager.get_current_or_default.return_value = test_profile
file_path = self.file_manager.add_file(
@@ -225,16 +225,14 @@ class FileManagerTest(unittest.TestCase):
expected_events = [
mock.call(
octoprint.filemanager.Events.FILE_ADDED,
dict(
storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test.gcode",
path="test.gcode",
type=["machinecode", "gcode"],
),
),
mock.call(
octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables")
{
"storage": octoprint.filemanager.FileDestinations.LOCAL,
"name": "test.gcode",
"path": "test.gcode",
"type": ["machinecode", "gcode"],
},
),
mock.call(octoprint.filemanager.Events.UPDATED_FILES, {"type": "printables"}),
]
self.fire_event.call_args_list = expected_events
@@ -245,7 +243,7 @@ class FileManagerTest(unittest.TestCase):
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
self.local_storage.split_path.return_value = ("", "test.gcode")
test_profile = dict(id="_default", name="My Default Profile")
test_profile = {"id": "_default", "name": "My Default Profile"}
self.printer_profile_manager.get_current_or_default.return_value = test_profile
file_path = self.file_manager.add_file(
@@ -278,16 +276,14 @@ class FileManagerTest(unittest.TestCase):
expected_events = [
mock.call(
octoprint.filemanager.Events.FILE_REMOVED,
dict(
storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test.gcode",
path="test.gcode",
type=["machinecode", "gcode"],
),
),
mock.call(
octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables")
{
"storage": octoprint.filemanager.FileDestinations.LOCAL,
"name": "test.gcode",
"path": "test.gcode",
"type": ["machinecode", "gcode"],
},
),
mock.call(octoprint.filemanager.Events.UPDATED_FILES, {"type": "printables"}),
]
self.fire_event.call_args_list = expected_events
@@ -307,15 +303,13 @@ class FileManagerTest(unittest.TestCase):
expected_events = [
mock.call(
octoprint.filemanager.Events.FOLDER_ADDED,
dict(
storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test_folder",
path="test_folder",
),
),
mock.call(
octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables")
{
"storage": octoprint.filemanager.FileDestinations.LOCAL,
"name": "test_folder",
"path": "test_folder",
},
),
mock.call(octoprint.filemanager.Events.UPDATED_FILES, {"type": "printables"}),
]
self.fire_event.call_args_list = expected_events
@@ -363,15 +357,13 @@ class FileManagerTest(unittest.TestCase):
expected_events = [
mock.call(
octoprint.filemanager.Events.FOLDER_REMOVED,
dict(
storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test_folder",
path="test_folder",
),
),
mock.call(
octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables")
{
"storage": octoprint.filemanager.FileDestinations.LOCAL,
"name": "test_folder",
"path": "test_folder",
},
),
mock.call(octoprint.filemanager.Events.UPDATED_FILES, {"type": "printables"}),
]
self.fire_event.call_args_list = expected_events
@@ -412,12 +404,12 @@ class FileManagerTest(unittest.TestCase):
recovery_file, max_permissions=0o666, mode="wt"
)
expected = dict(
origin=octoprint.filemanager.FileDestinations.LOCAL,
path=path,
pos=pos,
date=now,
)
expected = {
"origin": octoprint.filemanager.FileDestinations.LOCAL,
"path": path,
"pos": pos,
"date": now,
}
mock_yaml_safe_dump.assert_called_with(
expected,
@@ -433,8 +425,6 @@ class FileManagerTest(unittest.TestCase):
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
@@ -485,7 +475,12 @@ class FileManagerTest(unittest.TestCase):
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)
data = {
"path": "some_path.gco",
"origin": "local",
"pos": 1234,
"date": 123456789,
}
text_data = yaml.dump(data)
with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data=text_data)) as m:
@@ -524,7 +519,7 @@ class FileManagerTest(unittest.TestCase):
mock_remove.assert_called_with(recovery_file)
def test_get_metadata(self):
expected = dict(key="value")
expected = {"key": "value"}
self.local_storage.get_metadata.return_value = expected
metadata = self.file_manager.get_metadata(
@@ -558,11 +553,11 @@ class FileManagerTest(unittest.TestCase):
mocked_tempfile.return_value = temp_file
# mock metadata on local storage
metadata = dict(hash="aabbccddeeff")
metadata = {"hash": "aabbccddeeff"}
self.local_storage.get_metadata.return_value = metadata
# mock printer profile
expected_printer_profile = dict(id="_default", name="My Default Profile")
expected_printer_profile = {"id": "_default", "name": "My Default Profile"}
self.printer_profile_manager.get_current_or_default.return_value = (
expected_printer_profile
)
@@ -677,7 +672,7 @@ class FileManagerTest(unittest.TestCase):
self.fire_event.call_args_list = expected_events
# assert that model links were added
expected_links = [("model", dict(name="source.file"))]
expected_links = [("model", {"name": "source.file"})]
self.local_storage.add_file.assert_called_once_with(
"dest.file",
mock.ANY,
+18 -18
View File
@@ -120,7 +120,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.stl",
"bp_case.stl",
FILE_BP_CASE_STL,
links=[("web", dict(href=href, retrieved=retrieved))],
links=[("web", {"href": href, "retrieved": retrieved})],
)
stl_metadata = self.storage.get_metadata(stl_name)
@@ -141,7 +141,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode",
"bp_case.gcode",
FILE_BP_CASE_GCODE,
links=[("model", dict(name=stl_name))],
links=[("model", {"name": stl_name})],
)
stl_metadata = self.storage.get_metadata(stl_name)
@@ -173,7 +173,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode",
"bp_case.gcode",
FILE_BP_CASE_GCODE,
links=[("model", dict(name=stl_name))],
links=[("model", {"name": stl_name})],
)
stl_metadata = self.storage.get_metadata(stl_name)
@@ -372,7 +372,7 @@ class LocalStorageTest(unittest.TestCase):
after_metadata = self.storage.get_metadata("folder")
self.assertIsNotNone(before_metadata)
self.assertDictEqual(before_metadata, dict(display="földer"))
self.assertDictEqual(before_metadata, {"display": "földer"})
self.assertIsNone(after_metadata)
def test_copy_folder(self):
@@ -458,7 +458,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictEqual(after_metadata, dict(display="földer"))
self.assertDictEqual(after_metadata, {"display": "földer"})
@data("copy_folder", "move_folder")
def test_copy_move_folder_different_display(self, operation):
@@ -469,7 +469,7 @@ class LocalStorageTest(unittest.TestCase):
after_metadata = self.storage.get_metadata("test")
self.assertIsNotNone(before_metadata)
self.assertDictEqual(before_metadata, dict(display="földer"))
self.assertDictEqual(before_metadata, {"display": "földer"})
self.assertIsNone(after_metadata)
@data("copy_folder", "move_folder")
@@ -521,7 +521,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode",
"bp_case.gcode",
FILE_BP_CASE_GCODE,
links=[("model", dict(name=bp_case_stl))],
links=[("model", {"name": bp_case_stl})],
)
content_folder = self._add_and_verify_folder("content", "content")
@@ -568,7 +568,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode",
"bp_case.gcode",
FILE_BP_CASE_GCODE,
links=[("model", dict(name=bp_case_stl))],
links=[("model", {"name": bp_case_stl})],
)
content_folder = self._add_and_verify_folder("content", "content")
@@ -609,7 +609,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode",
"bp_case.gcode",
FILE_BP_CASE_GCODE,
links=[("model", dict(name=bp_case_stl))],
links=[("model", {"name": bp_case_stl})],
)
content_folder = self._add_and_verify_folder("content", "content")
@@ -642,7 +642,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE
)
self.storage.add_link(gcode_name, "model", dict(name=stl_name))
self.storage.add_link(gcode_name, "model", {"name": stl_name})
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
@@ -673,7 +673,7 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE
)
self.storage.add_link(stl_name, "machinecode", dict(name=gcode_name))
self.storage.add_link(stl_name, "machinecode", {"name": gcode_name})
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
@@ -701,18 +701,18 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL
)
self.storage.add_link(stl_name, "web", dict(href="http://www.example.com"))
self.storage.add_link(stl_name, "web", dict(href="http://www.example2.com"))
self.storage.add_link(stl_name, "web", {"href": "http://www.example.com"})
self.storage.add_link(stl_name, "web", {"href": "http://www.example2.com"})
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEqual(2, len(stl_metadata["links"]))
self.storage.remove_link(stl_name, "web", dict(href="http://www.example.com"))
self.storage.remove_link(stl_name, "web", {"href": "http://www.example.com"})
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEqual(1, len(stl_metadata["links"]))
self.storage.remove_link(stl_name, "web", dict(href="wrong_href"))
self.storage.remove_link(stl_name, "web", {"href": "wrong_href"})
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEqual(1, len(stl_metadata["links"]))
@@ -725,8 +725,8 @@ class LocalStorageTest(unittest.TestCase):
"bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE
)
self.storage.add_link(stl_name, "machinecode", dict(name=gcode_name))
self.storage.add_link(stl_name, "web", dict(href="http://www.example.com"))
self.storage.add_link(stl_name, "machinecode", {"name": gcode_name})
self.storage.add_link(stl_name, "web", {"href": "http://www.example.com"})
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
@@ -735,7 +735,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(2, len(stl_metadata["links"]))
self.storage.remove_link(
gcode_name, "model", dict(name=stl_name, hash=FILE_BP_CASE_STL.hash)
gcode_name, "model", {"name": stl_name, "hash": FILE_BP_CASE_STL.hash}
)
stl_metadata = self.storage.get_metadata(stl_name)
+13 -13
View File
@@ -22,10 +22,10 @@ NEW_VERSION = "2.0.0"
class Foo(object):
def get_latest(self, target, check, full_data=None):
information = dict(
local=dict(name=OLD_VERSION, value=OLD_VERSION),
remote=dict(name=NEW_VERSION, value=NEW_VERSION),
)
information = {
"local": {"name": OLD_VERSION, "value": OLD_VERSION},
"remote": {"name": NEW_VERSION, "value": NEW_VERSION},
}
current = False
return information, current
@@ -81,15 +81,15 @@ class Foo(object):
def get_update_information():
foo = Foo()
return dict(
always_update=dict(
displayName=NAME,
displayVersion=OLD_VERSION,
type="python_checker",
python_checker=foo,
python_updater=foo,
)
)
return {
"always_update": {
"displayName": NAME,
"displayVersion": OLD_VERSION,
"type": "python_checker",
"python_checker": foo,
"python_updater": foo,
}
}
__plugin_name__ = NAME
+4 -4
View File
@@ -153,13 +153,13 @@ class PluginTestCase(unittest.TestCase):
def test_plugin_initializing(self):
def test_factory(name, implementation):
return dict(test_factory="test_factory_%s" % name)
return {"test_factory": "test_factory_%s" % name}
def verify_injection_order(name, implementation):
self.assertTrue(hasattr(implementation, "_basefolder"))
return dict()
return {}
additional_injects = dict(additional_inject="additional_inject")
additional_injects = {"additional_inject": "additional_inject"}
additional_inject_factories = [test_factory, verify_injection_order]
self.plugin_manager.initialize_implementations(
additional_injects=additional_injects,
@@ -427,7 +427,7 @@ class PluginTestCase(unittest.TestCase):
)
@ddt.unpack
def test_mixins_matching_bases(self, bases_to_set, bases_to_check, expected):
Foo = type(to_native_str("Foo"), bases_to_set, dict())
Foo = type(to_native_str("Foo"), bases_to_set, {})
actual = octoprint.plugin.core.PluginManager.mixins_matching_bases(
Foo, *bases_to_check
)
+53 -53
View File
@@ -26,17 +26,17 @@ class SettingsTestCase(unittest.TestCase):
self.settings = mock.create_autospec(octoprint.settings.Settings)
self.defaults = dict(
some_raw_key="some_raw_value",
some_int_key=1,
some_float_key=2.5,
some_boolean_key=True,
preprocessed=dict(get="PreProcessed", set="PreProcessed"),
)
self.defaults = {
"some_raw_key": "some_raw_value",
"some_int_key": 1,
"some_float_key": 2.5,
"some_boolean_key": True,
"preprocessed": {"get": "PreProcessed", "set": "PreProcessed"},
}
self.get_preprocessors = dict(preprocessed=dict(get=lambda x: x.upper()))
self.get_preprocessors = {"preprocessed": {"get": lambda x: x.upper()}}
self.set_preprocessors = dict(preprocessed=dict(set=lambda x: x.lower()))
self.set_preprocessors = {"preprocessed": {"set": lambda x: x.lower()}}
self.plugin_settings = octoprint.plugin.PluginSettings(
self.settings,
@@ -54,7 +54,7 @@ class SettingsTestCase(unittest.TestCase):
"some_raw_key",
],
),
dict(),
{},
"get",
),
(
@@ -64,7 +64,7 @@ class SettingsTestCase(unittest.TestCase):
"some_raw_key",
],
),
dict(merged=True),
{"merged": True},
"get",
),
(
@@ -74,7 +74,7 @@ class SettingsTestCase(unittest.TestCase):
"some_raw_key",
],
),
dict(asdict=True),
{"asdict": True},
"get",
),
(
@@ -84,11 +84,11 @@ class SettingsTestCase(unittest.TestCase):
"some_raw_key",
],
),
dict(merged=True, asdict=True),
{"merged": True, "asdict": True},
"get",
),
("get_int", (["some_int_key,"],), dict(), "getInt"),
("get_float", (["some_float_key"],), dict(), "getFloat"),
("get_int", (["some_int_key,"],), {}, "getInt"),
("get_float", (["some_float_key"],), {}, "getFloat"),
(
"get_boolean",
(
@@ -96,7 +96,7 @@ class SettingsTestCase(unittest.TestCase):
"some_boolean_key",
],
),
dict(),
{},
"getBoolean",
),
)
@@ -111,21 +111,21 @@ class SettingsTestCase(unittest.TestCase):
forwarded_args = (["plugins", self.plugin_key] + getter_args[0],)
forwarded_kwargs = getter_kwargs
forwarded_kwargs.update(
dict(
defaults=dict(plugins=dict(test_plugin=self.defaults)),
preprocessors=dict(plugins=dict(test_plugin=self.get_preprocessors)),
)
{
"defaults": {"plugins": {"test_plugin": self.defaults}},
"preprocessors": {"plugins": {"test_plugin": self.get_preprocessors}},
}
)
forwarded_method.assert_called_once_with(*forwarded_args, **forwarded_kwargs)
@data(
("global_get", (["some_raw_key"],), dict(), "get"),
("global_get", (["some_raw_key"],), dict(merged=True), "get"),
("global_get", (["some_raw_key"],), dict(asdict=True), "get"),
("global_get", (["some_raw_key"],), dict(merged=True, asdict=True), "get"),
("global_get_int", (["some_int_key"],), dict(), "getInt"),
("global_get_float", (["some_float_key"],), dict(), "getFloat"),
("global_get_boolean", (["some_boolean_key"],), dict(), "getBoolean"),
("global_get", (["some_raw_key"],), {}, "get"),
("global_get", (["some_raw_key"],), {"merged": True}, "get"),
("global_get", (["some_raw_key"],), {"asdict": True}, "get"),
("global_get", (["some_raw_key"],), {"merged": True, "asdict": True}, "get"),
("global_get_int", (["some_int_key"],), {}, "getInt"),
("global_get_float", (["some_float_key"],), {}, "getFloat"),
("global_get_boolean", (["some_boolean_key"],), {}, "getBoolean"),
)
@unpack
def test_global_getter(self, getter, getter_args, getter_kwargs, forwarded):
@@ -150,7 +150,7 @@ class SettingsTestCase(unittest.TestCase):
# further mock out our mocked function so things work as they should
called_method.__name__ = to_native_str(forwarded)
called_method.__qualname__ = to_native_str(forwarded)
called_method.__annotations__ = dict()
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)
self.assertTrue(callable(method))
@@ -158,8 +158,8 @@ class SettingsTestCase(unittest.TestCase):
called_method.assert_called_once_with(
["plugins", self.plugin_key, "some_raw_key"],
defaults=dict(plugins=dict(test_plugin=self.defaults)),
preprocessors=dict(plugins=dict(test_plugin=self.get_preprocessors)),
defaults={"plugins": {"test_plugin": self.defaults}},
preprocessors={"plugins": {"test_plugin": self.get_preprocessors}},
)
self.assertEqual(1, len(w))
@@ -178,7 +178,7 @@ class SettingsTestCase(unittest.TestCase):
],
"some_value",
),
dict(),
{},
"set",
),
(
@@ -189,7 +189,7 @@ class SettingsTestCase(unittest.TestCase):
],
"some_value",
),
dict(force=True),
{"force": True},
"set",
),
(
@@ -200,7 +200,7 @@ class SettingsTestCase(unittest.TestCase):
],
23,
),
dict(),
{},
"setInt",
),
(
@@ -211,7 +211,7 @@ class SettingsTestCase(unittest.TestCase):
],
23,
),
dict(force=True),
{"force": True},
"setInt",
),
(
@@ -222,7 +222,7 @@ class SettingsTestCase(unittest.TestCase):
],
2.3,
),
dict(),
{},
"setFloat",
),
(
@@ -233,7 +233,7 @@ class SettingsTestCase(unittest.TestCase):
],
2.3,
),
dict(force=True),
{"force": True},
"setFloat",
),
(
@@ -244,7 +244,7 @@ class SettingsTestCase(unittest.TestCase):
],
True,
),
dict(),
{},
"setBoolean",
),
(
@@ -255,7 +255,7 @@ class SettingsTestCase(unittest.TestCase):
],
True,
),
dict(force=True),
{"force": True},
"setBoolean",
),
)
@@ -270,10 +270,10 @@ class SettingsTestCase(unittest.TestCase):
forwarded_args = (["plugins", self.plugin_key] + setter_args[0], setter_args[1])
forwarded_kwargs = setter_kwargs
forwarded_kwargs.update(
dict(
defaults=dict(plugins=dict(test_plugin=self.defaults)),
preprocessors=dict(plugins=dict(test_plugin=self.set_preprocessors)),
)
{
"defaults": {"plugins": {"test_plugin": self.defaults}},
"preprocessors": {"plugins": {"test_plugin": self.set_preprocessors}},
}
)
forwarded_method.assert_called_once_with(*forwarded_args, **forwarded_kwargs)
@@ -286,7 +286,7 @@ class SettingsTestCase(unittest.TestCase):
],
"some_value",
),
dict(),
{},
"set",
),
(
@@ -297,7 +297,7 @@ class SettingsTestCase(unittest.TestCase):
],
"some_value",
),
dict(force=True),
{"force": True},
"set",
),
(
@@ -308,7 +308,7 @@ class SettingsTestCase(unittest.TestCase):
],
23,
),
dict(),
{},
"setInt",
),
(
@@ -319,7 +319,7 @@ class SettingsTestCase(unittest.TestCase):
],
23,
),
dict(force=True),
{"force": True},
"setInt",
),
(
@@ -330,7 +330,7 @@ class SettingsTestCase(unittest.TestCase):
],
2.3,
),
dict(),
{},
"setFloat",
),
(
@@ -341,7 +341,7 @@ class SettingsTestCase(unittest.TestCase):
],
2.3,
),
dict(force=True),
{"force": True},
"setFloat",
),
(
@@ -352,7 +352,7 @@ class SettingsTestCase(unittest.TestCase):
],
True,
),
dict(),
{},
"setBoolean",
),
(
@@ -363,7 +363,7 @@ class SettingsTestCase(unittest.TestCase):
],
True,
),
dict(force=True),
{"force": True},
"setBoolean",
),
)
@@ -390,7 +390,7 @@ class SettingsTestCase(unittest.TestCase):
# further mock out our mocked function so things work as they should
called_method.__name__ = to_native_str(forwarded)
called_method.__qualname__ = to_native_str(forwarded)
called_method.__annotations__ = dict()
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)
self.assertTrue(callable(method))
@@ -399,8 +399,8 @@ class SettingsTestCase(unittest.TestCase):
called_method.assert_called_once_with(
["plugins", self.plugin_key, "some_raw_key"],
value,
defaults=dict(plugins=dict(test_plugin=self.defaults)),
preprocessors=dict(plugins=dict(test_plugin=self.set_preprocessors)),
defaults={"plugins": {"test_plugin": self.defaults}},
preprocessors={"plugins": {"test_plugin": self.set_preprocessors}},
)
self.assertEqual(1, len(w))
+18 -18
View File
@@ -50,8 +50,8 @@ class BlueprintPluginTest(unittest.TestCase):
self.assertListEqual(
test_method._blueprint_rules["test_method"],
[
("/test/method", dict(methods=["GET"])),
("/test/method/{foo}", dict(methods=["PUT"])),
("/test/method", {"methods": ["GET"]}),
("/test/method/{foo}", {"methods": ["PUT"]}),
],
)
@@ -69,10 +69,10 @@ class BlueprintPluginTest(unittest.TestCase):
def test_get_blueprint_kwargs(self):
import os
expected = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=os.path.join(self.basefolder, "templates"),
)
expected = {
"static_folder": os.path.join(self.basefolder, "static"),
"template_folder": os.path.join(self.basefolder, "templates"),
}
result = self.plugin.get_blueprint_kwargs()
@@ -81,10 +81,10 @@ class BlueprintPluginTest(unittest.TestCase):
def test_get_blueprint_kwargs_assetplugin(self):
import os
expected = dict(
static_folder=self.assetplugin.get_asset_folder(),
template_folder=os.path.join(self.basefolder, "templates"),
)
expected = {
"static_folder": self.assetplugin.get_asset_folder(),
"template_folder": os.path.join(self.basefolder, "templates"),
}
result = self.assetplugin.get_blueprint_kwargs()
@@ -93,10 +93,10 @@ class BlueprintPluginTest(unittest.TestCase):
def test_get_blueprint_kwargs_templateplugin(self):
import os
expected = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=self.templateplugin.get_template_folder(),
)
expected = {
"static_folder": os.path.join(self.basefolder, "static"),
"template_folder": self.templateplugin.get_template_folder(),
}
result = self.templateplugin.get_blueprint_kwargs()
@@ -105,10 +105,10 @@ class BlueprintPluginTest(unittest.TestCase):
def test_get_blueprint(self):
import os
expected_kwargs = dict(
static_folder=os.path.join(self.basefolder, "static"),
template_folder=os.path.join(self.basefolder, "templates"),
)
expected_kwargs = {
"static_folder": os.path.join(self.basefolder, "static"),
"template_folder": os.path.join(self.basefolder, "templates"),
}
class MyPlugin(octoprint.plugin.BlueprintPlugin):
@octoprint.plugin.BlueprintPlugin.route("/some/path", methods=["GET"])
+42 -40
View File
@@ -21,24 +21,24 @@ class TestSettingsPlugin(unittest.TestCase):
### setup
# settings defaults
defaults = dict(
foo=dict(a=1, b=2, l1=["some", "list"], l2=["another", "list"]),
bar=True,
fnord=None,
)
defaults = {
"foo": {"a": 1, "b": 2, "l1": ["some", "list"], "l2": ["another", "list"]},
"bar": True,
"fnord": None,
}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
# stored config, containing one redundant entry (bar=True, same as default)
in_config = dict(
foo=dict(
l1=["some", "other", "list"],
l2=["another", "list"],
l3=["a", "third", "list"],
),
bar=True,
fnord=dict(c=3, d=4),
)
in_config = {
"foo": {
"l1": ["some", "other", "list"],
"l2": ["another", "list"],
"l3": ["a", "third", "list"],
},
"bar": True,
"fnord": {"c": 3, "d": 4},
}
self.settings.get_all_data.return_value = in_config
### execute
@@ -48,10 +48,10 @@ class TestSettingsPlugin(unittest.TestCase):
### assert
# minimal config (current without redundant value) should have been set
expected = dict(
foo=dict(l1=["some", "other", "list"], l3=["a", "third", "list"]),
fnord=dict(c=3, d=4),
)
expected = {
"foo": {"l1": ["some", "other", "list"], "l3": ["a", "third", "list"]},
"fnord": {"c": 3, "d": 4},
}
self.settings.set.assert_called_once_with([], expected)
def test_on_settings_cleanup_configversion(self):
@@ -59,11 +59,11 @@ class TestSettingsPlugin(unittest.TestCase):
### setup
defaults = dict(foo="fnord")
defaults = {"foo": "fnord"}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
in_config = dict(_config_version=1, foo="fnord")
in_config = {"_config_version": 1, "foo": "fnord"}
self.settings.get_all_data.return_value = in_config
### execute
@@ -73,19 +73,19 @@ class TestSettingsPlugin(unittest.TestCase):
### assert
# minimal config incl. config version should have been set
self.settings.set.assert_called_once_with([], dict(_config_version=1))
self.settings.set.assert_called_once_with([], {"_config_version": 1})
def test_on_settings_cleanup_noconfigversion(self):
"""Tests that config versions of None are cleaned from stored data."""
### setup
defaults = dict(foo="bar")
defaults = {"foo": "bar"}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
# stored config version is None
in_config = dict(_config_version=None, foo="fnord")
in_config = {"_config_version": None, "foo": "fnord"}
self.settings.get_all_data.return_value = in_config
### execute
@@ -95,19 +95,19 @@ class TestSettingsPlugin(unittest.TestCase):
### assert
# minimal config without config version should have been set
self.settings.set.assert_called_once_with([], dict(foo="fnord"))
self.settings.set.assert_called_once_with([], {"foo": "fnord"})
def test_on_settings_cleanup_emptydiff(self):
"""Tests that settings are cleaned up if the diff data <-> defaults is empty."""
### setup
defaults = dict(foo="bar")
defaults = {"foo": "bar"}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
# current stored config, same as defaults
in_config = dict(foo="bar")
in_config = {"foo": "bar"}
self.settings.get_all_data.return_value = in_config
### execute
@@ -162,22 +162,22 @@ class TestSettingsPlugin(unittest.TestCase):
### setup
current = dict(foo="bar")
current = {"foo": "bar"}
self.settings.get_all_data.return_value = current
defaults = dict(foo="foo", bar=dict(a=1, b=2))
defaults = {"foo": "foo", "bar": {"a": 1, "b": 2}}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
### execute
data = dict(foo="fnord", bar=dict(a=1, b=2))
data = {"foo": "fnord", "bar": {"a": 1, "b": 2}}
diff = self.plugin.on_settings_save(data)
### assert
# the minimal diff should have been saved
expected = dict(foo="fnord")
expected = {"foo": "fnord"}
self.settings.set.assert_called_once_with([], expected)
self.assertEqual(diff, expected)
@@ -189,19 +189,19 @@ class TestSettingsPlugin(unittest.TestCase):
self.settings.get_all_data.return_value = None
defaults = dict(foo="bar", bar=dict(a=1, b=2, l=["some", "list"]))
defaults = {"foo": "bar", "bar": {"a": 1, "b": 2, "l": ["some", "list"]}}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
### execute
data = dict(foo="bar")
data = {"foo": "bar"}
diff = self.plugin.on_settings_save(data)
### assert
self.settings.clean_all_data.assert_called_once_with()
self.assertEqual(diff, dict())
self.assertEqual(diff, {})
def test_on_settings_save_configversion(self):
"""Tests that saved data gets stripped config version and set correct one."""
@@ -210,7 +210,7 @@ class TestSettingsPlugin(unittest.TestCase):
self.settings.get_all_data.return_value = None
defaults = dict(foo="bar")
defaults = {"foo": "bar"}
self.plugin.get_settings_defaults = mock.MagicMock()
self.plugin.get_settings_defaults.return_value = defaults
@@ -220,13 +220,13 @@ class TestSettingsPlugin(unittest.TestCase):
### execute
data = dict(_config_version=None, foo="bar")
data = {"_config_version": None, "foo": "bar"}
diff = self.plugin.on_settings_save(data)
### assert
expected_diff = dict()
expected_set = dict(_config_version=version)
expected_diff = {}
expected_set = {"_config_version": version}
# while there was no diff, we should still have saved the new config version
self.settings.set.assert_called_once_with([], expected_set)
@@ -239,9 +239,11 @@ class TestSettingsPlugin(unittest.TestCase):
### setup
# current data incl. config version
current = dict(
_config_version=3, foo="bar", fnord=dict(a=1, b=2, l=["some", "list"])
)
current = {
"_config_version": 3,
"foo": "bar",
"fnord": {"a": 1, "b": 2, "l": ["some", "list"]},
}
# expected is current without _config_version - we make the copy now
# since our current dict will be modified by the test
+65 -65
View File
@@ -90,71 +90,71 @@ class ThrottleStateTestCase(unittest.TestCase):
@ddt.data(
(
0x00000,
dict(
_undervoltage=False,
_freq_capped=False,
_throttled=False,
_past_undervoltage=False,
_past_freq_capped=False,
_past_throttled=False,
current_undervoltage=False,
past_undervoltage=False,
current_overheat=False,
past_overheat=False,
current_issue=False,
past_issue=False,
),
{
"_undervoltage": False,
"_freq_capped": False,
"_throttled": False,
"_past_undervoltage": False,
"_past_freq_capped": False,
"_past_throttled": False,
"current_undervoltage": False,
"past_undervoltage": False,
"current_overheat": False,
"past_overheat": False,
"current_issue": False,
"past_issue": False,
},
),
(
0x50005,
dict(
_undervoltage=True,
_freq_capped=False,
_throttled=True,
_past_undervoltage=True,
_past_freq_capped=False,
_past_throttled=True,
current_undervoltage=True,
past_undervoltage=True,
current_overheat=False,
past_overheat=False,
current_issue=True,
past_issue=True,
),
{
"_undervoltage": True,
"_freq_capped": False,
"_throttled": True,
"_past_undervoltage": True,
"_past_freq_capped": False,
"_past_throttled": True,
"current_undervoltage": True,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": False,
"current_issue": True,
"past_issue": True,
},
),
(
0x50000,
dict(
_undervoltage=False,
_freq_capped=False,
_throttled=False,
_past_undervoltage=True,
_past_freq_capped=False,
_past_throttled=True,
current_undervoltage=False,
past_undervoltage=True,
current_overheat=False,
past_overheat=False,
current_issue=False,
past_issue=True,
),
{
"_undervoltage": False,
"_freq_capped": False,
"_throttled": False,
"_past_undervoltage": True,
"_past_freq_capped": False,
"_past_throttled": True,
"current_undervoltage": False,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": False,
"current_issue": False,
"past_issue": True,
},
),
(
0x00006,
dict(
_undervoltage=False,
_freq_capped=True,
_throttled=True,
_past_undervoltage=False,
_past_freq_capped=False,
_past_throttled=False,
current_undervoltage=False,
past_undervoltage=False,
current_overheat=True,
past_overheat=False,
current_issue=True,
past_issue=False,
),
{
"_undervoltage": False,
"_freq_capped": True,
"_throttled": True,
"_past_undervoltage": False,
"_past_freq_capped": False,
"_past_throttled": False,
"current_undervoltage": False,
"past_undervoltage": False,
"current_overheat": True,
"past_overheat": False,
"current_issue": True,
"past_issue": False,
},
),
)
@ddt.unpack
@@ -179,13 +179,13 @@ class ThrottleStateTestCase(unittest.TestCase):
self.assertDictEqual(
state.as_dict(),
dict(
current_undervoltage=True,
past_undervoltage=True,
current_overheat=False,
past_overheat=True,
current_issue=True,
past_issue=True,
raw_value=-1,
),
{
"current_undervoltage": True,
"past_undervoltage": True,
"current_overheat": False,
"past_overheat": True,
"current_issue": True,
"past_issue": True,
"raw_value": -1,
},
)
@@ -10,84 +10,84 @@ import ddt
class NotificationFilterTest(unittest.TestCase):
@ddt.data(
(
dict(plugin="foo", text="text", date="2020-09-15 00:00:00Z"),
{"plugin": "foo", "text": "text", "date": "2020-09-15 00:00:00Z"},
"1.0.0",
"1.5.0",
True,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
pluginversions=[">=1.0.0"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"pluginversions": [">=1.0.0"],
},
"1.0.0",
"1.5.0",
True,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
pluginversions=[">=2.0.0", "0.9.0", "0.9.1", "1.0.0"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"pluginversions": [">=2.0.0", "0.9.0", "0.9.1", "1.0.0"],
},
"1.0.0",
"1.5.0",
True,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
pluginversions=[">=2.0.0", "0.9.0", "0.9.1", "1.0.0"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"pluginversions": [">=2.0.0", "0.9.0", "0.9.1", "1.0.0"],
},
"1.1.0",
"1.5.0",
False,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
versions=["0.9.0", "0.9.1", "1.0.0", "1.0.1"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"versions": ["0.9.0", "0.9.1", "1.0.0", "1.0.1"],
},
"1.0.0",
"1.5.0",
True,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
versions=["0.9.0", "0.9.1", "1.0.0", "1.0.1"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"versions": ["0.9.0", "0.9.1", "1.0.0", "1.0.1"],
},
"1.1.0",
"1.5.0",
False,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
octoversions=["1.5.0"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"octoversions": ["1.5.0"],
},
"1.0.0",
"1.5.0",
True,
),
(
dict(
plugin="foo",
text="text",
date="2020-09-15 00:00:00Z",
octoversions=["==1.4.2"],
),
{
"plugin": "foo",
"text": "text",
"date": "2020-09-15 00:00:00Z",
"octoversions": ["==1.4.2"],
},
"1.0.0",
"1.5.0",
False,
-2
View File
@@ -12,8 +12,6 @@ import unittest
from ddt import data, ddt, unpack
import octoprint.printer
@ddt
class EstimationTestCase(unittest.TestCase):
+1 -1
View File
@@ -27,7 +27,7 @@ class GetFolderUsageTest(unittest.TestCase):
with mock.patch("octoprint.server.api.system.s") as settings_mock:
settings = mock.MagicMock()
settings.get.return_value = dict(uploads="mocked")
settings.get.return_value = {"uploads": "mocked"}
settings.getBaseFolder.return_value = "mocked"
settings_mock.return_value = settings
+3 -3
View File
@@ -522,7 +522,7 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
expected_suffix = "_P5000"
if scriptroot is not None:
environ.update(dict(SCRIPT_NAME=scriptroot))
environ.update({"SCRIPT_NAME": scriptroot})
expected_suffix += "_R" + scriptroot.replace("/", "|")
request = OctoPrintFlaskRequest(environ)
@@ -535,9 +535,9 @@ class OctoPrintFlaskResponseTest(unittest.TestCase):
expected_path_set = scriptroot + expected_path_set
if path is not None:
kwargs = dict(path=path)
kwargs = {"path": path}
else:
kwargs = dict()
kwargs = {}
with mock.patch("flask.request", new=request):
with mock.patch("octoprint.server.util.flask.settings") as settings_mock:
+9 -10
View File
@@ -12,7 +12,6 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
import unittest
import mock
from ddt import data, ddt, unpack
##~~ _parse_header
@@ -21,10 +20,10 @@ from ddt import data, ddt, unpack
@ddt
class ParseHeaderTest(unittest.TestCase):
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
('form-data; filename="test.gco"', "form-data", dict(filename="test.gco")),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
('form-data; filename="test\\\\.gco"', "form-data", dict(filename="test\\.gco")),
("form-data; filename=test.gco", "form-data", {"filename": "test.gco"}),
('form-data; filename="test.gco"', "form-data", {"filename": "test.gco"}),
("form-data; filename=test\\\\.gco", "form-data", {"filename": "test\\\\.gco"}),
('form-data; filename="test\\\\.gco"', "form-data", {"filename": "test\\.gco"}),
)
@unpack
def test_parse_header_strip_quotes(self, value, expected_key, expected_dict):
@@ -36,18 +35,18 @@ class ParseHeaderTest(unittest.TestCase):
self.assertDictEqual(expected_dict, actual_dict)
@data(
("form-data; filename=test.gco", "form-data", dict(filename="test.gco")),
('form-data; filename="test.gco"', "form-data", dict(filename='"test.gco"')),
("form-data; filename=test\\\\.gco", "form-data", dict(filename="test\\\\.gco")),
("form-data; filename=test.gco", "form-data", {"filename": "test.gco"}),
('form-data; filename="test.gco"', "form-data", {"filename": '"test.gco"'}),
("form-data; filename=test\\\\.gco", "form-data", {"filename": "test\\\\.gco"}),
(
'form-data; filename="test\\\\.gco"',
"form-data",
dict(filename='"test\\\\.gco"'),
{"filename": '"test\\\\.gco"'},
),
(
"form-data; filename=iso-8859-1'en'test.gco",
"form-data",
dict(filename="iso-8859-1'en'test.gco"),
{"filename": "iso-8859-1'en'test.gco"},
),
)
@unpack
+11 -12
View File
@@ -17,7 +17,6 @@ import io
import os
import re
import shutil
import sys
import tempfile
import time
import unittest
@@ -302,7 +301,7 @@ class TestSettings(unittest.TestCase):
data = settings.get(["devel", "virtualPrinter"])
self.assertEqual(len(data), 1)
self.assertDictEqual(dict(enabled=True), data)
self.assertDictEqual({"enabled": True}, data)
def test_get_map_merged(self):
with self.mocked_config():
@@ -311,7 +310,7 @@ class TestSettings(unittest.TestCase):
data = settings.get(["devel", "virtualPrinter"], merged=True)
self.assertGreater(len(data), 1)
test_dict = dict(enabled=True, sendWait=True, waitInterval=1.0)
test_dict = {"enabled": True, "sendWait": True, "waitInterval": 1.0}
test_data = dict((k, v) for k, v in data.items() if k in test_dict)
self.assertEqual(test_dict, test_data)
@@ -362,7 +361,7 @@ class TestSettings(unittest.TestCase):
settings = octoprint.settings.Settings()
server_port = settings.getInt(
["server", "port"], config=dict(server=dict(port=9090))
["server", "port"], config={"server": {"port": 9090}}
)
self.assertEqual(9090, server_port)
@@ -372,7 +371,7 @@ class TestSettings(unittest.TestCase):
settings = octoprint.settings.Settings()
api_enabled = settings.getBoolean(
["api", "enabled"], defaults=dict(api=dict(enabled=False))
["api", "enabled"], defaults={"api": {"enabled": False}}
)
self.assertFalse(api_enabled)
@@ -453,7 +452,7 @@ class TestSettings(unittest.TestCase):
True, settings._config["devel"]["virtualPrinter"]["repetierStyleResends"]
)
@ddt.data("0", "no", "false", ["some", "list"], dict(a="dictionary"), lambda: None)
@ddt.data("0", "no", "false", ["some", "list"], {"a": "dictionary"}, lambda: None)
def test_set_boolean_convert_any_false(self, value):
with self.mocked_config():
settings = octoprint.settings.Settings()
@@ -574,9 +573,9 @@ class TestSettings(unittest.TestCase):
def test_get_preprocessor(self):
with self.mocked_config():
config = dict()
defaults = dict(test="some string")
preprocessors = dict(test=lambda x: x.upper())
config = {}
defaults = {"test": "some string"}
preprocessors = {"test": lambda x: x.upper()}
settings = octoprint.settings.Settings()
value = settings.get(
@@ -587,9 +586,9 @@ class TestSettings(unittest.TestCase):
def test_set_preprocessor(self):
with self.mocked_config():
config = dict()
defaults = dict(foo=dict(bar="fnord"))
preprocessors = dict(foo=dict(bar=lambda x: x.upper()))
config = {}
defaults = {"foo": {"bar": "fnord"}}
preprocessors = {"foo": {"bar": lambda x: x.upper()}}
settings = octoprint.settings.Settings()
settings.set(
+12 -10
View File
@@ -21,9 +21,11 @@ class TestSlicingManager(unittest.TestCase):
self.profile_path = tempfile.mkdtemp()
self.slicer_plugin = mock.MagicMock()
self.slicer_plugin.get_slicer_properties.return_value = dict(
type="mock", name="Mock", same_device=True
)
self.slicer_plugin.get_slicer_properties.return_value = {
"type": "mock",
"name": "Mock",
"same_device": True,
}
self.slicer_plugin.is_slicer_configured.return_value = True
# mock plugin manager
@@ -63,7 +65,7 @@ class TestSlicingManager(unittest.TestCase):
if octoprint.plugin.SlicerPlugin in types:
return plugins
return dict()
return {}
self.plugin_manager.return_value.get_implementations.side_effect = (
get_implementations
@@ -108,12 +110,12 @@ class TestSlicingManager(unittest.TestCase):
# mock retrieval of default profile
def get(path):
return dict()
return {}
self.settings.get.side_effect = get
default_profile = octoprint.slicing.SlicingProfile(
"mock", "default", dict(layer_height=0.2, fill_density=40)
"mock", "default", {"layer_height": 0.2, "fill_density": 40}
)
self.slicer_plugin.get_slicer_default_profile.return_value = default_profile
@@ -141,7 +143,7 @@ class TestSlicingManager(unittest.TestCase):
self.slicer_plugin.do_slice.return_value = True, None
# mock printer profile manager
printer_profile = dict(_id="mock_printer", _name="Mock Printer Profile")
printer_profile = {"_id": "mock_printer", "_name": "Mock Printer Profile"}
def get_printer_profile(printer_profile_id):
self.assertEqual("mock_printer", printer_profile_id)
@@ -155,11 +157,11 @@ class TestSlicingManager(unittest.TestCase):
dest_path = "prefix/dest.file"
profile_name = "dummy_profile"
printer_profile_id = "mock_printer"
position = dict(x=10, y=20)
position = {"x": 10, "y": 20}
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
callback_kwargs = dict(foo="bar")
overrides = dict(layer_height=0.5)
callback_kwargs = {"foo": "bar"}
overrides = {"layer_height": 0.5}
self.slicing_manager.slice(
slicer_name,
-2
View File
@@ -165,8 +165,6 @@ class DaemonTest(unittest.TestCase):
self.daemon.start()
# assert
import signal
self.daemon._double_fork.assert_called_once_with()
self.daemon._redirect_io.assert_called_once_with()
self.daemon.set_pid.assert_called_once_with(str(pid))
+6 -6
View File
@@ -17,13 +17,13 @@ import os
import time
from collections import OrderedDict, namedtuple
_stat = namedtuple("StatResult", "st_size, st_ctime, st_mtime")
_entry = namedtuple("DirEntry", "name, path, is_file, is_dir, stat")
import octoprint.plugin
import octoprint.settings
import octoprint.timelapse
_stat = namedtuple("StatResult", "st_size, st_ctime, st_mtime")
_entry = namedtuple("DirEntry", "name, path, is_file, is_dir, stat")
@ddt.ddt
class TimelapseTest(unittest.TestCase):
@@ -44,7 +44,7 @@ class TimelapseTest(unittest.TestCase):
def extension_factory(*args, **kwargs):
return ["gif"]
hooks = dict(test=extension_factory)
hooks = {"test": extension_factory}
self.plugin_manager.get_hooks.return_value = hooks
self.now = time.time()
@@ -142,7 +142,7 @@ class TimelapseTest(unittest.TestCase):
mocked_path = "/path/to/timelapse"
files = dict()
files = {}
files["one.mpg"] = _stat(st_size=1024, st_ctime=self.now, st_mtime=self.now)
files["nope.jpg"] = _stat(st_size=100, st_ctime=self.now, st_mtime=self.now)
files["two.mpg"] = _stat(st_size=2048, st_ctime=self.now, st_mtime=self.now)
@@ -164,7 +164,7 @@ class TimelapseTest(unittest.TestCase):
@mock.patch("octoprint.timelapse.scandir")
def test_unrendered_timelapses(self, mock_scandir):
## prepare
files = dict()
files = {}
files["one-0.jpg"] = _stat(
st_size=1, st_ctime=self.now - 1, st_mtime=self.now - 1
)
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more