diff --git a/InvenTree/InvenTree/api.py b/InvenTree/InvenTree/api.py index 0713479f7a..ea043f2264 100644 --- a/InvenTree/InvenTree/api.py +++ b/InvenTree/InvenTree/api.py @@ -1,6 +1,4 @@ -""" -Main JSON interface views -""" +"""Main JSON interface views.""" from django.conf import settings from django.http import JsonResponse @@ -16,7 +14,8 @@ from .views import AjaxView class InfoView(AjaxView): - """ Simple JSON endpoint for InvenTree information. + """Simple JSON endpoint for InvenTree information. + Use to confirm that the server is running, etc. """ @@ -37,9 +36,7 @@ class InfoView(AjaxView): class NotFoundView(AjaxView): - """ - Simple JSON view when accessing an invalid API view. - """ + """Simple JSON view when accessing an invalid API view.""" permission_classes = [permissions.AllowAny] @@ -54,8 +51,7 @@ class NotFoundView(AjaxView): class APIDownloadMixin: - """ - Mixin for enabling a LIST endpoint to be downloaded a file. + """Mixin for enabling a LIST endpoint to be downloaded a file. To download the data, add the ?export= to the query string. @@ -92,10 +88,7 @@ class APIDownloadMixin: class AttachmentMixin: - """ - Mixin for creating attachment objects, - and ensuring the user information is saved correctly. - """ + """Mixin for creating attachment objects, and ensuring the user information is saved correctly.""" permission_classes = [permissions.IsAuthenticated] @@ -106,8 +99,7 @@ class AttachmentMixin: ] def perform_create(self, serializer): - """ Save the user information when a file is uploaded """ - + """Save the user information when a file is uploaded.""" attachment = serializer.save() attachment.user = self.request.user attachment.save() diff --git a/InvenTree/InvenTree/api_tester.py b/InvenTree/InvenTree/api_tester.py index 935252de5b..78be1e5ad7 100644 --- a/InvenTree/InvenTree/api_tester.py +++ b/InvenTree/InvenTree/api_tester.py @@ -1,6 +1,4 @@ -""" -Helper functions for performing API unit tests -""" +"""Helper functions for performing API unit tests.""" import csv import io @@ -62,10 +60,7 @@ class UserMixin: self.client.login(username=self.username, password=self.password) def assignRole(self, role=None, assign_all: bool = False): - """ - Set the user roles for the registered user - """ - + """Set the user roles for the registered user.""" # role is of the format 'rule.permission' e.g. 'part.add' if not assign_all and role: @@ -89,16 +84,13 @@ class UserMixin: class InvenTreeAPITestCase(UserMixin, APITestCase): - """ - Base class for running InvenTree API tests - """ + """Base class for running InvenTree API tests.""" def getActions(self, url): - """ - Return a dict of the 'actions' available at a given endpoint. + """Return a dict of the 'actions' available at a given endpoint. + Makes use of the HTTP 'OPTIONS' method to request this. """ - response = self.client.options(url) self.assertEqual(response.status_code, 200) @@ -110,10 +102,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return actions def get(self, url, data={}, expected_code=200): - """ - Issue a GET request - """ - + """Issue a GET request.""" response = self.client.get(url, data, format='json') if expected_code is not None: @@ -122,10 +111,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def post(self, url, data, expected_code=None, format='json'): - """ - Issue a POST request - """ - + """Issue a POST request.""" response = self.client.post(url, data=data, format=format) if expected_code is not None: @@ -134,10 +120,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def delete(self, url, expected_code=None): - """ - Issue a DELETE request - """ - + """Issue a DELETE request.""" response = self.client.delete(url) if expected_code is not None: @@ -146,10 +129,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def patch(self, url, data, expected_code=None, format='json'): - """ - Issue a PATCH request - """ - + """Issue a PATCH request.""" response = self.client.patch(url, data=data, format=format) if expected_code is not None: @@ -158,10 +138,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def put(self, url, data, expected_code=None, format='json'): - """ - Issue a PUT request - """ - + """Issue a PUT request.""" response = self.client.put(url, data=data, format=format) if expected_code is not None: @@ -170,10 +147,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def options(self, url, expected_code=None): - """ - Issue an OPTIONS request - """ - + """Issue an OPTIONS request.""" response = self.client.options(url, format='json') if expected_code is not None: @@ -182,10 +156,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return response def download_file(self, url, data, expected_code=None, expected_fn=None, decode=True): - """ - Download a file from the server, and return an in-memory file - """ - + """Download a file from the server, and return an in-memory file.""" response = self.client.get(url, data=data, format='json') if expected_code is not None: @@ -221,10 +192,7 @@ class InvenTreeAPITestCase(UserMixin, APITestCase): return fo def process_csv(self, fo, delimiter=',', required_cols=None, excluded_cols=None, required_rows=None): - """ - Helper function to process and validate a downloaded csv file - """ - + """Helper function to process and validate a downloaded csv file.""" # Check that the correct object type has been passed self.assertTrue(isinstance(fo, io.StringIO)) diff --git a/InvenTree/InvenTree/api_version.py b/InvenTree/InvenTree/api_version.py index 993c7e9980..87189cd972 100644 --- a/InvenTree/InvenTree/api_version.py +++ b/InvenTree/InvenTree/api_version.py @@ -1,6 +1,4 @@ -""" -InvenTree API version information -""" +"""InvenTree API version information.""" # InvenTree API version diff --git a/InvenTree/InvenTree/apps.py b/InvenTree/InvenTree/apps.py index 74dbca444c..b580ccc49a 100644 --- a/InvenTree/InvenTree/apps.py +++ b/InvenTree/InvenTree/apps.py @@ -37,10 +37,7 @@ class InvenTreeConfig(AppConfig): self.add_user_on_startup() def remove_obsolete_tasks(self): - """ - Delete any obsolete scheduled tasks in the database - """ - + """Delete any obsolete scheduled tasks in the database.""" obsolete = [ 'InvenTree.tasks.delete_expired_sessions', 'stock.tasks.delete_old_stock_items', @@ -101,13 +98,11 @@ class InvenTreeConfig(AppConfig): ) def update_exchange_rates(self): # pragma: no cover - """ - Update exchange rates each time the server is started, *if*: + """Update exchange rates each time the server is started, *if*: a) Have not been updated recently (one day or less) b) The base exchange rate has been altered """ - try: from djmoney.contrib.exchange.models import ExchangeBackend @@ -150,7 +145,7 @@ class InvenTreeConfig(AppConfig): logger.error(f"Error updating exchange rates: {e}") def add_user_on_startup(self): - """Add a user on startup""" + """Add a user on startup.""" # stop if checks were already created if hasattr(settings, 'USER_ADDED') and settings.USER_ADDED: return @@ -202,9 +197,7 @@ class InvenTreeConfig(AppConfig): settings.USER_ADDED = True def collect_notification_methods(self): - """ - Collect all notification methods - """ + """Collect all notification methods.""" from common.notifications import storage storage.collect() diff --git a/InvenTree/InvenTree/ci_render_js.py b/InvenTree/InvenTree/ci_render_js.py index 1be38df107..d8783d14df 100644 --- a/InvenTree/InvenTree/ci_render_js.py +++ b/InvenTree/InvenTree/ci_render_js.py @@ -1,6 +1,6 @@ -""" -Pull rendered copies of the templated -only used for testing the js files! - This file is omited from coverage +"""Pull rendered copies of the templated. + +Only used for testing the js files! - This file is omited from coverage. """ import os # pragma: no cover @@ -10,8 +10,7 @@ from InvenTree.helpers import InvenTreeTestCase # pragma: no cover class RenderJavascriptFiles(InvenTreeTestCase): # pragma: no cover - """ - A unit test to "render" javascript files. + """A unit test to "render" javascript files. The server renders templated javascript files, we need the fully-rendered files for linting and static tests. @@ -73,10 +72,7 @@ class RenderJavascriptFiles(InvenTreeTestCase): # pragma: no cover return n def test_render_files(self): - """ - Look for all javascript files - """ - + """Look for all javascript files.""" n = 0 print("Rendering javascript files...") diff --git a/InvenTree/InvenTree/config.py b/InvenTree/InvenTree/config.py index d7691cf4cc..fe3e41a10f 100644 --- a/InvenTree/InvenTree/config.py +++ b/InvenTree/InvenTree/config.py @@ -1,6 +1,4 @@ -""" -Helper functions for loading InvenTree configuration options -""" +"""Helper functions for loading InvenTree configuration options.""" import logging import os @@ -10,17 +8,15 @@ logger = logging.getLogger('inventree') def get_base_dir(): - """ Returns the base (top-level) InvenTree directory """ + """Returns the base (top-level) InvenTree directory.""" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_config_file(): - """ - Returns the path of the InvenTree configuration file. + """Returns the path of the InvenTree configuration file. Note: It will be created it if does not already exist! """ - base_dir = get_base_dir() cfg_filename = os.getenv('INVENTREE_CONFIG_FILE') @@ -43,8 +39,7 @@ def get_config_file(): def get_plugin_file(): - """ - Returns the path of the InvenTree plugins specification file. + """Returns the path of the InvenTree plugins specification file. Note: It will be created if it does not already exist! """ @@ -70,14 +65,12 @@ def get_plugin_file(): def get_setting(environment_var, backup_val, default_value=None): - """ - Helper function for retrieving a configuration setting value + """Helper function for retrieving a configuration setting value. - First preference is to look for the environment variable - Second preference is to look for the value of the settings file - Third preference is the default value """ - val = os.getenv(environment_var) if val is not None: diff --git a/InvenTree/InvenTree/context.py b/InvenTree/InvenTree/context.py index c0b27ad5bf..4e3d38d1b0 100644 --- a/InvenTree/InvenTree/context.py +++ b/InvenTree/InvenTree/context.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- -""" -Provides extra global data to all templates. -""" +"""Provides extra global data to all templates.""" import InvenTree.status from InvenTree.status_codes import (BuildStatus, PurchaseOrderStatus, @@ -12,13 +10,11 @@ from users.models import RuleSet def health_status(request): - """ - Provide system health status information to the global context. + """Provide system health status information to the global context. - Not required for AJAX requests - Do not provide if it is already provided to the context """ - if request.path.endswith('.js'): # Do not provide to script requests return {} # pragma: no cover @@ -53,10 +49,7 @@ def health_status(request): def status_codes(request): - """ - Provide status code enumerations. - """ - + """Provide status code enumerations.""" if hasattr(request, '_inventree_status_codes'): # Do not duplicate efforts return {} @@ -74,8 +67,7 @@ def status_codes(request): def user_roles(request): - """ - Return a map of the current roles assigned to the user. + """Return a map of the current roles assigned to the user. Roles are denoted by their simple names, and then the permission type. @@ -86,7 +78,6 @@ def user_roles(request): Each value will return a boolean True / False """ - user = request.user roles = { diff --git a/InvenTree/InvenTree/exceptions.py b/InvenTree/InvenTree/exceptions.py index 55017affc0..f595fb40d6 100644 --- a/InvenTree/InvenTree/exceptions.py +++ b/InvenTree/InvenTree/exceptions.py @@ -1,6 +1,4 @@ -""" -Custom exception handling for the DRF API -""" +"""Custom exception handling for the DRF API.""" # -*- coding: utf-8 -*- from __future__ import unicode_literals @@ -21,13 +19,11 @@ from rest_framework.response import Response def exception_handler(exc, context): - """ - Custom exception handler for DRF framework. - Ref: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling + """Custom exception handler for DRF framework. + Ref: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling Catches any errors not natively handled by DRF, and re-throws as an error DRF can handle """ - response = None # Catch any django validation error, and re-throw a DRF validation error diff --git a/InvenTree/InvenTree/exchange.py b/InvenTree/InvenTree/exchange.py index a46e1356a8..94c0ce6527 100644 --- a/InvenTree/InvenTree/exchange.py +++ b/InvenTree/InvenTree/exchange.py @@ -11,8 +11,7 @@ from common.settings import currency_code_default, currency_codes class InvenTreeExchange(SimpleExchangeBackend): - """ - Backend for automatically updating currency exchange rates. + """Backend for automatically updating currency exchange rates. Uses the exchangerate.host service API """ @@ -30,11 +29,10 @@ class InvenTreeExchange(SimpleExchangeBackend): } def get_response(self, **kwargs): - """ - Custom code to get response from server. + """Custom code to get response from server. + Note: Adds a 5-second timeout """ - url = self.get_url(**kwargs) try: diff --git a/InvenTree/InvenTree/fields.py b/InvenTree/InvenTree/fields.py index 9995c5444c..d7c0e1ad80 100644 --- a/InvenTree/InvenTree/fields.py +++ b/InvenTree/InvenTree/fields.py @@ -1,4 +1,4 @@ -""" Custom fields used in InvenTree """ +"""Custom fields used in InvenTree.""" import sys from decimal import Decimal @@ -19,13 +19,13 @@ from .validators import allowable_url_schemes class InvenTreeURLFormField(FormURLField): - """ Custom URL form field with custom scheme validators """ + """Custom URL form field with custom scheme validators.""" default_validators = [validators.URLValidator(schemes=allowable_url_schemes())] class InvenTreeURLField(models.URLField): - """ Custom URL field which has custom scheme validators """ + """Custom URL field which has custom scheme validators.""" default_validators = [validators.URLValidator(schemes=allowable_url_schemes())] @@ -36,7 +36,7 @@ class InvenTreeURLField(models.URLField): def money_kwargs(): - """ returns the database settings for MoneyFields """ + """Returns the database settings for MoneyFields.""" from common.settings import currency_code_default, currency_code_mappings kwargs = {} @@ -46,9 +46,7 @@ def money_kwargs(): class InvenTreeModelMoneyField(ModelMoneyField): - """ - Custom MoneyField for clean migrations while using dynamic currency settings - """ + """Custom MoneyField for clean migrations while using dynamic currency settings.""" def __init__(self, **kwargs): # detect if creating migration @@ -73,13 +71,13 @@ class InvenTreeModelMoneyField(ModelMoneyField): super().__init__(**kwargs) def formfield(self, **kwargs): - """ override form class to use own function """ + """Override form class to use own function.""" kwargs['form_class'] = InvenTreeMoneyField return super().formfield(**kwargs) class InvenTreeMoneyField(MoneyField): - """ custom MoneyField for clean migrations while using dynamic currency settings """ + """Custom MoneyField for clean migrations while using dynamic currency settings.""" def __init__(self, *args, **kwargs): # override initial values with the real info from database kwargs.update(money_kwargs()) @@ -87,9 +85,7 @@ class InvenTreeMoneyField(MoneyField): class DatePickerFormField(forms.DateField): - """ - Custom date-picker field - """ + """Custom date-picker field.""" def __init__(self, **kwargs): @@ -115,10 +111,7 @@ class DatePickerFormField(forms.DateField): def round_decimal(value, places): - """ - Round value to the specified number of places. - """ - + """Round value to the specified number of places.""" if value is not None: # see https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize for options return value.quantize(Decimal(10) ** -places) @@ -132,11 +125,10 @@ class RoundingDecimalFormField(forms.DecimalField): return value def prepare_value(self, value): - """ - Override the 'prepare_value' method, to remove trailing zeros when displaying. + """Override the 'prepare_value' method, to remove trailing zeros when displaying. + Why? It looks nice! """ - if type(value) == Decimal: return InvenTree.helpers.normalize(value) else: diff --git a/InvenTree/InvenTree/filters.py b/InvenTree/InvenTree/filters.py index f0058e399a..0d551f1b72 100644 --- a/InvenTree/InvenTree/filters.py +++ b/InvenTree/InvenTree/filters.py @@ -2,8 +2,7 @@ from rest_framework.filters import OrderingFilter class InvenTreeOrderingFilter(OrderingFilter): - """ - Custom OrderingFilter class which allows aliased filtering of related fields. + """Custom OrderingFilter class which allows aliased filtering of related fields. To use, simply specify this filter in the "filter_backends" section. @@ -27,9 +26,7 @@ class InvenTreeOrderingFilter(OrderingFilter): # Attempt to map ordering fields based on provided aliases if ordering is not None and aliases is not None: - """ - Ordering fields should be mapped to separate fields - """ + """Ordering fields should be mapped to separate fields.""" ordering_initial = ordering ordering = [] diff --git a/InvenTree/InvenTree/forms.py b/InvenTree/InvenTree/forms.py index 50e2d26fff..736b582603 100644 --- a/InvenTree/InvenTree/forms.py +++ b/InvenTree/InvenTree/forms.py @@ -1,6 +1,4 @@ -""" -Helper forms which subclass Django forms to provide additional functionality -""" +"""Helper forms which subclass Django forms to provide additional functionality.""" import logging from urllib.parse import urlencode @@ -30,7 +28,7 @@ logger = logging.getLogger('inventree') class HelperForm(forms.ModelForm): - """ Provides simple integration of crispy_forms extension. """ + """Provides simple integration of crispy_forms extension.""" # Custom field decorations can be specified here, per form class field_prefix = {} @@ -117,7 +115,7 @@ class HelperForm(forms.ModelForm): class ConfirmForm(forms.Form): - """ Generic confirmation form """ + """Generic confirmation form.""" confirm = forms.BooleanField( required=False, initial=False, @@ -131,8 +129,7 @@ class ConfirmForm(forms.Form): class DeleteForm(forms.Form): - """ Generic deletion form which provides simple user confirmation - """ + """Generic deletion form which provides simple user confirmation.""" confirm_delete = forms.BooleanField( required=False, @@ -148,9 +145,7 @@ class DeleteForm(forms.Form): class EditUserForm(HelperForm): - """ - Form for editing user information - """ + """Form for editing user information.""" class Meta: model = User @@ -161,8 +156,7 @@ class EditUserForm(HelperForm): class SetPasswordForm(HelperForm): - """ Form for setting user password - """ + """Form for setting user password.""" enter_password = forms.CharField(max_length=100, min_length=8, @@ -189,7 +183,7 @@ class SetPasswordForm(HelperForm): class SettingCategorySelectForm(forms.ModelForm): - """ Form for setting category settings """ + """Form for setting category settings.""" category = forms.ModelChoiceField(queryset=PartCategory.objects.all()) @@ -220,9 +214,7 @@ class SettingCategorySelectForm(forms.ModelForm): # override allauth class CustomSignupForm(SignupForm): - """ - Override to use dynamic settings - """ + """Override to use dynamic settings.""" def __init__(self, *args, **kwargs): kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED') @@ -261,9 +253,7 @@ class CustomSignupForm(SignupForm): class RegistratonMixin: - """ - Mixin to check if registration should be enabled - """ + """Mixin to check if registration should be enabled.""" def is_open_for_signup(self, request, *args, **kwargs): if settings.EMAIL_HOST and InvenTreeSetting.get_setting('LOGIN_ENABLE_REG', True): return super().is_open_for_signup(request, *args, **kwargs) @@ -283,20 +273,16 @@ class RegistratonMixin: class CustomAccountAdapter(RegistratonMixin, OTPAdapter, DefaultAccountAdapter): - """ - Override of adapter to use dynamic settings - """ + """Override of adapter to use dynamic settings.""" def send_mail(self, template_prefix, email, context): - """only send mail if backend configured""" + """Only send mail if backend configured.""" if settings.EMAIL_HOST: return super().send_mail(template_prefix, email, context) return False class CustomSocialAccountAdapter(RegistratonMixin, DefaultSocialAccountAdapter): - """ - Override of adapter to use dynamic settings - """ + """Override of adapter to use dynamic settings.""" def is_auto_signup_allowed(self, request, sociallogin): if InvenTreeSetting.get_setting('LOGIN_SIGNUP_SSO_AUTO', True): return super().is_auto_signup_allowed(request, sociallogin) diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index c541ce4ef5..929a1ff708 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -1,6 +1,4 @@ -""" -Provides helper functions used throughout the InvenTree project -""" +"""Provides helper functions used throughout the InvenTree project.""" import io import json @@ -27,21 +25,15 @@ from .settings import MEDIA_URL, STATIC_URL def getSetting(key, backup_value=None): - """ - Shortcut for reading a setting value from the database - """ - + """Shortcut for reading a setting value from the database.""" return InvenTreeSetting.get_setting(key, backup_value=backup_value) def generateTestKey(test_name): - """ - Generate a test 'key' for a given test name. - This must not have illegal chars as it will be used for dict lookup in a template. + """Generate a test 'key' for a given test name. This must not have illegal chars as it will be used for dict lookup in a template. Tests must be named such that they will have unique keys. """ - key = test_name.strip().lower() key = key.replace(" ", "") @@ -52,33 +44,23 @@ def generateTestKey(test_name): def getMediaUrl(filename): - """ - Return the qualified access path for the given file, - under the media directory. - """ - + """Return the qualified access path for the given file, under the media directory.""" return os.path.join(MEDIA_URL, str(filename)) def getStaticUrl(filename): - """ - Return the qualified access path for the given file, - under the static media directory. - """ - + """Return the qualified access path for the given file, under the static media directory.""" return os.path.join(STATIC_URL, str(filename)) def construct_absolute_url(*arg): - """ - Construct (or attempt to construct) an absolute URL from a relative URL. + """Construct (or attempt to construct) an absolute URL from a relative URL. This is useful when (for example) sending an email to a user with a link to something in the InvenTree web framework. This requires the BASE_URL configuration option to be set! """ - base = str(InvenTreeSetting.get_setting('INVENTREE_BASE_URL')) url = '/'.join(arg) @@ -99,23 +81,17 @@ def construct_absolute_url(*arg): def getBlankImage(): - """ - Return the qualified path for the 'blank image' placeholder. - """ - + """Return the qualified path for the 'blank image' placeholder.""" return getStaticUrl("img/blank_image.png") def getBlankThumbnail(): - """ - Return the qualified path for the 'blank image' thumbnail placeholder. - """ - + """Return the qualified path for the 'blank image' thumbnail placeholder.""" return getStaticUrl("img/blank_image.thumbnail.png") def TestIfImage(img): - """ Test if an image file is indeed an image """ + """Test if an image file is indeed an image.""" try: Image.open(img).verify() return True @@ -124,7 +100,7 @@ def TestIfImage(img): def TestIfImageURL(url): - """ Test if an image URL (or filename) looks like a valid image format. + """Test if an image URL (or filename) looks like a valid image format. Simply tests the extension against a set of allowed values """ @@ -137,7 +113,7 @@ def TestIfImageURL(url): def str2bool(text, test=True): - """ Test if a string 'looks' like a boolean value. + """Test if a string 'looks' like a boolean value. Args: text: Input text @@ -153,10 +129,7 @@ def str2bool(text, test=True): def is_bool(text): - """ - Determine if a string value 'looks' like a boolean. - """ - + """Determine if a string value 'looks' like a boolean.""" if str2bool(text, True): return True elif str2bool(text, False): @@ -166,9 +139,7 @@ def is_bool(text): def isNull(text): - """ - Test if a string 'looks' like a null value. - This is useful for querying the API against a null key. + """Test if a string 'looks' like a null value. This is useful for querying the API against a null key. Args: text: Input text @@ -176,15 +147,11 @@ def isNull(text): Returns: True if the text looks like a null value """ - return str(text).strip().lower() in ['top', 'null', 'none', 'empty', 'false', '-1', ''] def normalize(d): - """ - Normalize a decimal number, and remove exponential formatting. - """ - + """Normalize a decimal number, and remove exponential formatting.""" if type(d) is not Decimal: d = Decimal(d) @@ -195,8 +162,7 @@ def normalize(d): def increment(n): - """ - Attempt to increment an integer (or a string that looks like an integer!) + """Attempt to increment an integer (or a string that looks like an integer!) e.g. @@ -204,9 +170,7 @@ def increment(n): 2 -> 3 AB01 -> AB02 QQQ -> QQQ - """ - value = str(n).strip() # Ignore empty strings @@ -248,10 +212,7 @@ def increment(n): def decimal2string(d): - """ - Format a Decimal number as a string, - stripping out any trailing zeroes or decimal points. - Essentially make it look like a whole number if it is one. + """Format a Decimal number as a string, stripping out any trailing zeroes or decimal points. Essentially make it look like a whole number if it is one. Args: d: A python Decimal object @@ -259,7 +220,6 @@ def decimal2string(d): Returns: A string representation of the input number """ - if type(d) is Decimal: d = normalize(d) @@ -280,8 +240,7 @@ def decimal2string(d): def decimal2money(d, currency=None): - """ - Format a Decimal number as Money + """Format a Decimal number as Money. Args: d: A python Decimal object @@ -296,7 +255,7 @@ def decimal2money(d, currency=None): def WrapWithQuotes(text, quote='"'): - """ Wrap the supplied text with quotes + """Wrap the supplied text with quotes. Args: text: Input text to wrap @@ -305,7 +264,6 @@ def WrapWithQuotes(text, quote='"'): Returns: Supplied text wrapped in quote char """ - if not text.startswith(quote): text = quote + text @@ -316,7 +274,7 @@ def WrapWithQuotes(text, quote='"'): def MakeBarcode(object_name, object_pk, object_data=None, **kwargs): - """ Generate a string for a barcode. Adds some global InvenTree parameters. + """Generate a string for a barcode. Adds some global InvenTree parameters. Args: object_type: string describing the object type e.g. 'StockItem' @@ -363,8 +321,7 @@ def MakeBarcode(object_name, object_pk, object_data=None, **kwargs): def GetExportFormats(): - """ Return a list of allowable file formats for exporting data """ - + """Return a list of allowable file formats for exporting data.""" return [ 'csv', 'tsv', @@ -376,8 +333,7 @@ def GetExportFormats(): def DownloadFile(data, filename, content_type='application/text', inline=False): - """ - Create a dynamic file for the user to download. + """Create a dynamic file for the user to download. Args: data: Raw file data (string or bytes) @@ -388,7 +344,6 @@ def DownloadFile(data, filename, content_type='application/text', inline=False): Return: A StreamingHttpResponse object wrapping the supplied data """ - filename = WrapWithQuotes(filename) if type(data) == str: @@ -407,8 +362,7 @@ def DownloadFile(data, filename, content_type='application/text', inline=False): def extract_serial_numbers(serials, expected_quantity, next_number: int): - """ - Attempt to extract serial numbers from an input string: + """Attempt to extract serial numbers from an input string: Requirements: - Serial numbers can be either strings, or integers @@ -423,7 +377,6 @@ def extract_serial_numbers(serials, expected_quantity, next_number: int): expected_quantity: The number of (unique) serial numbers we expect next_number(int): the next possible serial number """ - serials = serials.strip() # fill in the next serial number into the serial @@ -543,8 +496,7 @@ def extract_serial_numbers(serials, expected_quantity, next_number: int): def validateFilterString(value, model=None): - """ - Validate that a provided filter string looks like a list of comma-separated key=value pairs + """Validate that a provided filter string looks like a list of comma-separated key=value pairs. These should nominally match to a valid database filter based on the model being filtered. @@ -559,7 +511,6 @@ def validateFilterString(value, model=None): Returns a map of key:value pairs """ - # Empty results map results = {} @@ -605,28 +556,19 @@ def validateFilterString(value, model=None): def addUserPermission(user, permission): - """ - Shortcut function for adding a certain permission to a user. - """ - + """Shortcut function for adding a certain permission to a user.""" perm = Permission.objects.get(codename=permission) user.user_permissions.add(perm) def addUserPermissions(user, permissions): - """ - Shortcut function for adding multiple permissions to a user. - """ - + """Shortcut function for adding multiple permissions to a user.""" for permission in permissions: addUserPermission(user, permission) def getMigrationFileNames(app): - """ - Return a list of all migration filenames for provided app - """ - + """Return a list of all migration filenames for provided app.""" local_dir = os.path.dirname(os.path.abspath(__file__)) migration_dir = os.path.join(local_dir, '..', app, 'migrations') @@ -646,10 +588,7 @@ def getMigrationFileNames(app): def getOldestMigrationFile(app, exclude_extension=True, ignore_initial=True): - """ - Return the filename associated with the oldest migration - """ - + """Return the filename associated with the oldest migration.""" oldest_num = -1 oldest_file = None @@ -671,10 +610,7 @@ def getOldestMigrationFile(app, exclude_extension=True, ignore_initial=True): def getNewestMigrationFile(app, exclude_extension=True): - """ - Return the filename associated with the newest migration - """ - + """Return the filename associated with the newest migration.""" newest_file = None newest_num = -1 @@ -692,8 +628,7 @@ def getNewestMigrationFile(app, exclude_extension=True): def clean_decimal(number): - """ Clean-up decimal value """ - + """Clean-up decimal value.""" # Check if empty if number is None or number == '' or number == 0: return Decimal(0) @@ -729,7 +664,7 @@ def clean_decimal(number): def get_objectreference(obj, type_ref: str = 'content_type', object_ref: str = 'object_id'): - """lookup method for the GenericForeignKey fields + """Lookup method for the GenericForeignKey fields. Attributes: - obj: object that will be resolved @@ -769,9 +704,7 @@ def get_objectreference(obj, type_ref: str = 'content_type', object_ref: str = ' def inheritors(cls): - """ - Return all classes that are subclasses from the supplied cls - """ + """Return all classes that are subclasses from the supplied cls.""" subcls = set() work = [cls] while work: diff --git a/InvenTree/InvenTree/management/commands/clean_settings.py b/InvenTree/InvenTree/management/commands/clean_settings.py index 7607f2a574..f82fbbca45 100644 --- a/InvenTree/InvenTree/management/commands/clean_settings.py +++ b/InvenTree/InvenTree/management/commands/clean_settings.py @@ -1,6 +1,4 @@ -""" -Custom management command to cleanup old settings that are not defined anymore -""" +"""Custom management command to cleanup old settings that are not defined anymore.""" import logging @@ -10,9 +8,7 @@ logger = logging.getLogger('inventree') class Command(BaseCommand): - """ - Cleanup old (undefined) settings in the database - """ + """Cleanup old (undefined) settings in the database.""" def handle(self, *args, **kwargs): diff --git a/InvenTree/InvenTree/management/commands/prerender.py b/InvenTree/InvenTree/management/commands/prerender.py index efaaad80dc..90d4c99f31 100644 --- a/InvenTree/InvenTree/management/commands/prerender.py +++ b/InvenTree/InvenTree/management/commands/prerender.py @@ -1,6 +1,4 @@ -""" -Custom management command to prerender files -""" +"""Custom management command to prerender files.""" import os @@ -13,7 +11,7 @@ from django.utils.translation import override as lang_over def render_file(file_name, source, target, locales, ctx): - """ renders a file into all provided locales """ + """Renders a file into all provided locales.""" for locale in locales: target_file = os.path.join(target, locale + '.' + file_name) with open(target_file, 'w') as localised_file: @@ -23,9 +21,7 @@ def render_file(file_name, source, target, locales, ctx): class Command(BaseCommand): - """ - django command to prerender files - """ + """Django command to prerender files.""" def handle(self, *args, **kwargs): # static directories diff --git a/InvenTree/InvenTree/management/commands/rebuild_models.py b/InvenTree/InvenTree/management/commands/rebuild_models.py index 2a60da9365..120a4ad18e 100644 --- a/InvenTree/InvenTree/management/commands/rebuild_models.py +++ b/InvenTree/InvenTree/management/commands/rebuild_models.py @@ -1,5 +1,4 @@ -""" -Custom management command to rebuild all MPTT models +"""Custom management command to rebuild all MPTT models. - This is crucial after importing any fixtures, etc """ @@ -8,9 +7,7 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): - """ - Rebuild all database models which leverage the MPTT structure. - """ + """Rebuild all database models which leverage the MPTT structure.""" def handle(self, *args, **kwargs): diff --git a/InvenTree/InvenTree/management/commands/rebuild_thumbnails.py b/InvenTree/InvenTree/management/commands/rebuild_thumbnails.py index 3d684df06d..480bab41b2 100644 --- a/InvenTree/InvenTree/management/commands/rebuild_thumbnails.py +++ b/InvenTree/InvenTree/management/commands/rebuild_thumbnails.py @@ -1,5 +1,4 @@ -""" -Custom management command to rebuild thumbnail images +"""Custom management command to rebuild thumbnail images. - May be required after importing a new dataset, for example """ @@ -20,15 +19,10 @@ logger = logging.getLogger('inventree') class Command(BaseCommand): - """ - Rebuild all thumbnail images - """ + """Rebuild all thumbnail images.""" def rebuild_thumbnail(self, model): - """ - Rebuild the thumbnail specified by the "image" field of the provided model - """ - + """Rebuild the thumbnail specified by the "image" field of the provided model.""" if not model.image: return diff --git a/InvenTree/InvenTree/management/commands/remove_mfa.py b/InvenTree/InvenTree/management/commands/remove_mfa.py index 53266348e2..4abf05ebcb 100644 --- a/InvenTree/InvenTree/management/commands/remove_mfa.py +++ b/InvenTree/InvenTree/management/commands/remove_mfa.py @@ -1,15 +1,11 @@ -""" -Custom management command to remove MFA for a user -""" +"""Custom management command to remove MFA for a user.""" from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand class Command(BaseCommand): - """ - Remove MFA for a user - """ + """Remove MFA for a user.""" def add_arguments(self, parser): parser.add_argument('mail', type=str) diff --git a/InvenTree/InvenTree/management/commands/wait_for_db.py b/InvenTree/InvenTree/management/commands/wait_for_db.py index ebd6999f7f..b892309609 100644 --- a/InvenTree/InvenTree/management/commands/wait_for_db.py +++ b/InvenTree/InvenTree/management/commands/wait_for_db.py @@ -1,6 +1,4 @@ -""" -Custom management command, wait for the database to be ready! -""" +"""Custom management command, wait for the database to be ready!""" import time @@ -10,9 +8,7 @@ from django.db.utils import ImproperlyConfigured, OperationalError class Command(BaseCommand): - """ - django command to pause execution until the database is ready - """ + """Django command to pause execution until the database is ready.""" def handle(self, *args, **kwargs): diff --git a/InvenTree/InvenTree/metadata.py b/InvenTree/InvenTree/metadata.py index e2d42bb539..e9ed616e80 100644 --- a/InvenTree/InvenTree/metadata.py +++ b/InvenTree/InvenTree/metadata.py @@ -12,8 +12,7 @@ logger = logging.getLogger('inventree') class InvenTreeMetadata(SimpleMetadata): - """ - Custom metadata class for the DRF API. + """Custom metadata class for the DRF API. This custom metadata class imits the available "actions", based on the user's role permissions. @@ -23,7 +22,6 @@ class InvenTreeMetadata(SimpleMetadata): Additionally, we include some extra information about database models, so we can perform lookup for ForeignKey related fields. - """ def determine_metadata(self, request, view): @@ -106,11 +104,7 @@ class InvenTreeMetadata(SimpleMetadata): return metadata def get_serializer_info(self, serializer): - """ - Override get_serializer_info so that we can add 'default' values - to any fields whose Meta.model specifies a default value - """ - + """Override get_serializer_info so that we can add 'default' values to any fields whose Meta.model specifies a default value.""" self.serializer = serializer serializer_info = super().get_serializer_info(serializer) @@ -208,10 +202,7 @@ class InvenTreeMetadata(SimpleMetadata): pass if instance is not None: - """ - If there is an instance associated with this API View, - introspect that instance to find any specific API info. - """ + """If there is an instance associated with this API View, introspect that instance to find any specific API info.""" if hasattr(instance, 'api_instance_filters'): @@ -233,13 +224,10 @@ class InvenTreeMetadata(SimpleMetadata): return serializer_info def get_field_info(self, field): - """ - Given an instance of a serializer field, return a dictionary - of metadata about it. + """Given an instance of a serializer field, return a dictionary of metadata about it. We take the regular DRF metadata and add our own unique flavor """ - # Run super method first field_info = super().get_field_info(field) diff --git a/InvenTree/InvenTree/middleware.py b/InvenTree/InvenTree/middleware.py index aaf13f7623..3a96d8dc11 100644 --- a/InvenTree/InvenTree/middleware.py +++ b/InvenTree/InvenTree/middleware.py @@ -35,6 +35,7 @@ class AuthRequiredMiddleware(object): if not request.user.is_authenticated: """ Normally, a web-based session would use csrftoken based authentication. + However when running an external application (e.g. the InvenTree app or Python library), we must validate the user token manually. """ @@ -105,7 +106,7 @@ url_matcher = re_path('', include(frontendpatterns)) class Check2FAMiddleware(BaseRequire2FAMiddleware): - """check if user is required to have MFA enabled""" + """check if user is required to have MFA enabled.""" def require_2fa(self, request): # Superusers are require to have 2FA. try: @@ -117,7 +118,7 @@ class Check2FAMiddleware(BaseRequire2FAMiddleware): class CustomAllauthTwoFactorMiddleware(AllauthTwoFactorMiddleware): - """This function ensures only frontend code triggers the MFA auth cycle""" + """This function ensures only frontend code triggers the MFA auth cycle.""" def process_request(self, request): try: if not url_matcher.resolve(request.path[1:]): @@ -127,9 +128,7 @@ class CustomAllauthTwoFactorMiddleware(AllauthTwoFactorMiddleware): class InvenTreeRemoteUserMiddleware(PersistentRemoteUserMiddleware): - """ - Middleware to check if HTTP-header based auth is enabled and to set it up - """ + """Middleware to check if HTTP-header based auth is enabled and to set it up.""" header = settings.REMOTE_LOGIN_HEADER def process_request(self, request): diff --git a/InvenTree/InvenTree/models.py b/InvenTree/InvenTree/models.py index aba8b36763..a3fe3ddc65 100644 --- a/InvenTree/InvenTree/models.py +++ b/InvenTree/InvenTree/models.py @@ -1,6 +1,4 @@ -""" -Generic models which provide extra functionality over base Django model types. -""" +"""Generic models which provide extra functionality over base Django model types.""" import logging import os @@ -25,25 +23,21 @@ logger = logging.getLogger('inventree') def rename_attachment(instance, filename): - """ - Function for renaming an attachment file. - The subdirectory for the uploaded file is determined by the implementing class. + """Function for renaming an attachment file. The subdirectory for the uploaded file is determined by the implementing class. - Args: + Args: instance: Instance of a PartAttachment object filename: name of uploaded file Returns: path to store file, format: '//filename' """ - # Construct a path to store a file attachment for a given model type return os.path.join(instance.getSubdir(), filename) class DataImportMixin(object): - """ - Model mixin class which provides support for 'data import' functionality. + """Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import """ @@ -53,12 +47,10 @@ class DataImportMixin(object): @classmethod def get_import_fields(cls): - """ - Return all available import fields + """Return all available import fields. Where information on a particular field is not explicitly provided, introspect the base model to (attempt to) find that information. - """ fields = cls.IMPORT_FIELDS @@ -85,7 +77,7 @@ class DataImportMixin(object): @classmethod def get_required_import_fields(cls): - """ Return all *required* import fields """ + """Return all *required* import fields.""" fields = {} for name, field in cls.get_import_fields().items(): @@ -98,8 +90,7 @@ class DataImportMixin(object): class ReferenceIndexingMixin(models.Model): - """ - A mixin for keeping track of numerical copies of the "reference" field. + """A mixin for keeping track of numerical copies of the "reference" field. !!DANGER!! always add `ReferenceIndexingSerializerMixin`to all your models serializers to ensure the reference field is not too big @@ -155,7 +146,7 @@ def extract_int(reference, clip=0x7fffffff): class InvenTreeAttachment(models.Model): - """ Provides an abstracted class for managing file attachments. + """Provides an abstracted class for managing file attachments. An attachment can be either an uploaded file, or an external URL @@ -167,11 +158,10 @@ class InvenTreeAttachment(models.Model): """ def getSubdir(self): - """ - Return the subdirectory under which attachments should be stored. + """Return the subdirectory under which attachments should be stored. + Note: Re-implement this for each subclass of InvenTreeAttachment """ - return "attachments" def save(self, *args, **kwargs): @@ -222,15 +212,13 @@ class InvenTreeAttachment(models.Model): @basename.setter def basename(self, fn): - """ - Function to rename the attachment file. + """Function to rename the attachment file. - Filename cannot be empty - Filename cannot contain illegal characters - Filename must specify an extension - Filename cannot match an existing file """ - fn = fn.strip() if len(fn) == 0: @@ -291,7 +279,7 @@ class InvenTreeAttachment(models.Model): class InvenTreeTree(MPTTModel): - """ Provides an abstracted self-referencing tree model for data categories. + """Provides an abstracted self-referencing tree model for data categories. - Each Category has one parent Category, which can be blank (for a top-level Category). - Each Category can have zero-or-more child Categor(y/ies) @@ -303,10 +291,7 @@ class InvenTreeTree(MPTTModel): """ def api_instance_filters(self): - """ - Instance filters for InvenTreeTree models - """ - + """Instance filters for InvenTreeTree models.""" return { 'parent': { 'exclude_tree': self.pk, @@ -356,7 +341,7 @@ class InvenTreeTree(MPTTModel): @property def item_count(self): - """ Return the number of items which exist *under* this node in the tree. + """Return the number of items which exist *under* this node in the tree. Here an 'item' is considered to be the 'leaf' at the end of each branch, and the exact nature here will depend on the class implementation. @@ -366,30 +351,29 @@ class InvenTreeTree(MPTTModel): return 0 def getUniqueParents(self): - """ Return a flat set of all parent items that exist above this node. + """Return a flat set of all parent items that exist above this node. + If any parents are repeated (which would be very bad!), the process is halted """ - return self.get_ancestors() def getUniqueChildren(self, include_self=True): - """ Return a flat set of all child items that exist under this node. + """Return a flat set of all child items that exist under this node. + If any child items are repeated, the repetitions are omitted. """ - return self.get_descendants(include_self=include_self) @property def has_children(self): - """ True if there are any children under this item """ + """True if there are any children under this item.""" return self.getUniqueChildren(include_self=False).count() > 0 def getAcceptableParents(self): - """ Returns a list of acceptable parent items within this model - Acceptable parents are ones which are not underneath this item. + """Returns a list of acceptable parent items within this model Acceptable parents are ones which are not underneath this item. + Setting the parent of an item to its own child results in recursion. """ - contents = ContentType.objects.get_for_model(type(self)) available = contents.get_all_objects_for_this_type() @@ -407,17 +391,16 @@ class InvenTreeTree(MPTTModel): @property def parentpath(self): - """ Get the parent path of this category + """Get the parent path of this category. Returns: List of category names from the top level to the parent of this category """ - return [a for a in self.get_ancestors()] @property def path(self): - """ Get the complete part of this category. + """Get the complete part of this category. e.g. ["Top", "Second", "Third", "This"] @@ -428,25 +411,23 @@ class InvenTreeTree(MPTTModel): @property def pathstring(self): - """ Get a string representation for the path of this item. + """Get a string representation for the path of this item. e.g. "Top/Second/Third/This" """ return '/'.join([item.name for item in self.path]) def __str__(self): - """ String representation of a category is the full path to that category """ - + """String representation of a category is the full path to that category.""" return "{path} - {desc}".format(path=self.pathstring, desc=self.description) @receiver(pre_delete, sender=InvenTreeTree, dispatch_uid='tree_pre_delete_log') def before_delete_tree_item(sender, instance, using, **kwargs): - """ Receives pre_delete signal from InvenTreeTree object. + """Receives pre_delete signal from InvenTreeTree object. Before an item is deleted, update each child object to point to the parent of the object being deleted. """ - # Update each tree item below this one for child in instance.children.all(): child.parent = instance.parent diff --git a/InvenTree/InvenTree/permissions.py b/InvenTree/InvenTree/permissions.py index 920e111ce2..cb48487f75 100644 --- a/InvenTree/InvenTree/permissions.py +++ b/InvenTree/InvenTree/permissions.py @@ -4,9 +4,7 @@ import users.models class RolePermission(permissions.BasePermission): - """ - Role mixin for API endpoints, allowing us to specify the user "role" - which is required for certain operations. + """Role mixin for API endpoints, allowing us to specify the user "role" which is required for certain operations. Each endpoint can have one or more of the following actions: - GET @@ -25,14 +23,10 @@ class RolePermission(permissions.BasePermission): to perform the specified action. For example, a DELETE action will be rejected unless the user has the "part.remove" permission - """ def has_permission(self, request, view): - """ - Determine if the current user has the specified permissions - """ - + """Determine if the current user has the specified permissions.""" user = request.user # Superuser can do it all diff --git a/InvenTree/InvenTree/ready.py b/InvenTree/InvenTree/ready.py index e93972cf2e..2dcc8a8c33 100644 --- a/InvenTree/InvenTree/ready.py +++ b/InvenTree/InvenTree/ready.py @@ -2,30 +2,21 @@ import sys def isInTestMode(): - """ - Returns True if the database is in testing mode - """ - + """Returns True if the database is in testing mode.""" return 'test' in sys.argv def isImportingData(): - """ - Returns True if the database is currently importing data, - e.g. 'loaddata' command is performed - """ - + """Returns True if the database is currently importing data, e.g. 'loaddata' command is performed.""" return 'loaddata' in sys.argv def canAppAccessDatabase(allow_test=False): - """ - Returns True if the apps.py file can access database records. + """Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ - # If any of the following management commands are being executed, # prevent custom "on load" code from running! excluded_commands = [ diff --git a/InvenTree/InvenTree/serializers.py b/InvenTree/InvenTree/serializers.py index e91bcab484..1d0e70908d 100644 --- a/InvenTree/InvenTree/serializers.py +++ b/InvenTree/InvenTree/serializers.py @@ -1,6 +1,4 @@ -""" -Serializers used in various InvenTree apps -""" +"""Serializers used in various InvenTree apps.""" import os from collections import OrderedDict @@ -26,9 +24,7 @@ from .models import extract_int class InvenTreeMoneySerializer(MoneyField): - """ - Custom serializer for 'MoneyField', - which ensures that passed values are numerically valid + """Custom serializer for 'MoneyField', which ensures that passed values are numerically valid. Ref: https://github.com/django-money/django-money/blob/master/djmoney/contrib/django_rest_framework/fields.py """ @@ -41,10 +37,7 @@ class InvenTreeMoneySerializer(MoneyField): super().__init__(*args, **kwargs) def get_value(self, data): - """ - Test that the returned amount is a valid Decimal - """ - + """Test that the returned amount is a valid Decimal.""" amount = super(DecimalField, self).get_value(data) # Convert an empty string to None @@ -68,7 +61,7 @@ class InvenTreeMoneySerializer(MoneyField): class UserSerializer(serializers.ModelSerializer): - """ Serializer for User - provides all fields """ + """Serializer for User - provides all fields""" class Meta: model = User @@ -76,7 +69,7 @@ class UserSerializer(serializers.ModelSerializer): class UserSerializerBrief(serializers.ModelSerializer): - """ Serializer for User - provides limited information """ + """Serializer for User - provides limited information""" class Meta: model = User @@ -87,17 +80,10 @@ class UserSerializerBrief(serializers.ModelSerializer): class InvenTreeModelSerializer(serializers.ModelSerializer): - """ - Inherits the standard Django ModelSerializer class, - but also ensures that the underlying model class data are checked on validation. - """ + """Inherits the standard Django ModelSerializer class, but also ensures that the underlying model class data are checked on validation.""" def __init__(self, instance=None, data=empty, **kwargs): - """ - Custom __init__ routine to ensure that *default* values (as specified in the ORM) - are used by the DRF serializers, *if* the values are not provided by the user. - """ - + """Custom __init__ routine to ensure that *default* values (as specified in the ORM) are used by the DRF serializers, *if* the values are not provided by the user.""" # If instance is None, we are creating a new instance if instance is None and data is not empty: @@ -118,6 +104,7 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): """ Update the field IF (and ONLY IF): + - The field has a specified default value - The field does not already have a value set """ @@ -137,11 +124,10 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): super().__init__(instance, data, **kwargs) def get_initial(self): - """ - Construct initial data for the serializer. + """Construct initial data for the serializer. + Use the 'default' values specified by the django model definition """ - initials = super().get_initial().copy() # Are we creating a new instance? @@ -168,11 +154,7 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): return initials def save(self, **kwargs): - """ - Catch any django ValidationError thrown at the moment save() is called, - and re-throw as a DRF ValidationError - """ - + """Catch any django ValidationError thrown at the moment `save` is called, and re-throw as a DRF ValidationError.""" try: super().save(**kwargs) except (ValidationError, DjangoValidationError) as exc: @@ -181,10 +163,7 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): return self.instance def update(self, instance, validated_data): - """ - Catch any django ValidationError, and re-throw as a DRF ValidationError - """ - + """Catch any django ValidationError, and re-throw as a DRF ValidationError.""" try: instance = super().update(instance, validated_data) except (ValidationError, DjangoValidationError) as exc: @@ -193,12 +172,11 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): return instance def run_validation(self, data=empty): - """ - Perform serializer validation. + """Perform serializer validation. + In addition to running validators on the serializer fields, this class ensures that the underlying model is also validated. """ - # Run any native validation checks first (may raise a ValidationError) data = super().run_validation(data) @@ -237,10 +215,7 @@ class InvenTreeModelSerializer(serializers.ModelSerializer): class ReferenceIndexingSerializerMixin(): - """ - This serializer mixin ensures the the reference is not to big / small - for the BigIntegerField - """ + """This serializer mixin ensures the the reference is not to big / small for the BigIntegerField.""" def validate_reference(self, value): if extract_int(value) > models.BigIntegerField.MAX_BIGINT: raise serializers.ValidationError('reference is to to big') @@ -248,9 +223,7 @@ class ReferenceIndexingSerializerMixin(): class InvenTreeAttachmentSerializerField(serializers.FileField): - """ - Override the DRF native FileField serializer, - to remove the leading server path. + """Override the DRF native FileField serializer, to remove the leading server path. For example, the FileField might supply something like: @@ -277,8 +250,7 @@ class InvenTreeAttachmentSerializerField(serializers.FileField): class InvenTreeAttachmentSerializer(InvenTreeModelSerializer): - """ - Special case of an InvenTreeModelSerializer, which handles an "attachment" model. + """Special case of an InvenTreeModelSerializer, which handles an "attachment" model. The only real addition here is that we support "renaming" of the attachment file. """ @@ -298,8 +270,8 @@ class InvenTreeAttachmentSerializer(InvenTreeModelSerializer): class InvenTreeImageSerializerField(serializers.ImageField): - """ - Custom image serializer. + """Custom image serializer. + On upload, validate that the file is a valid image file """ @@ -312,8 +284,7 @@ class InvenTreeImageSerializerField(serializers.ImageField): class InvenTreeDecimalField(serializers.FloatField): - """ - Custom serializer for decimal fields. Solves the following issues: + """Custom serializer for decimal fields. Solves the following issues: - The normal DRF DecimalField renders values with trailing zeros - Using a FloatField can result in rounding issues: https://code.djangoproject.com/ticket/30290 @@ -329,8 +300,7 @@ class InvenTreeDecimalField(serializers.FloatField): class DataFileUploadSerializer(serializers.Serializer): - """ - Generic serializer for uploading a data file, and extracting a dataset. + """Generic serializer for uploading a data file, and extracting a dataset. - Validates uploaded file - Extracts column names @@ -353,10 +323,7 @@ class DataFileUploadSerializer(serializers.Serializer): ) def validate_data_file(self, data_file): - """ - Perform validation checks on the uploaded data file. - """ - + """Perform validation checks on the uploaded data file.""" self.filename = data_file.name name, ext = os.path.splitext(data_file.name) @@ -406,15 +373,13 @@ class DataFileUploadSerializer(serializers.Serializer): return data_file def match_column(self, column_name, field_names, exact=False): - """ - Attempt to match a column name (from the file) to a field (defined in the model) + """Attempt to match a column name (from the file) to a field (defined in the model) Order of matching is: - Direct match - Case insensitive match - Fuzzy match """ - if not column_name: return None @@ -439,10 +404,7 @@ class DataFileUploadSerializer(serializers.Serializer): return None def extract_data(self): - """ - Returns dataset extracted from the file - """ - + """Returns dataset extracted from the file.""" # Provide a dict of available import fields for the model model_fields = {} @@ -487,8 +449,7 @@ class DataFileUploadSerializer(serializers.Serializer): class DataFileExtractSerializer(serializers.Serializer): - """ - Generic serializer for extracting data from an imported dataset. + """Generic serializer for extracting data from an imported dataset. - User provides an array of matched headers - User provides an array of raw data rows @@ -548,9 +509,7 @@ class DataFileExtractSerializer(serializers.Serializer): rows = [] for row in self.rows: - """ - Optionally pre-process each row, before sending back to the client - """ + """Optionally pre-process each row, before sending back to the client.""" processed_row = self.process_row(self.row_to_dict(row)) @@ -567,22 +526,17 @@ class DataFileExtractSerializer(serializers.Serializer): } def process_row(self, row): - """ - Process a 'row' of data, which is a mapped column:value dict + """Process a 'row' of data, which is a mapped column:value dict. Returns either a mapped column:value dict, or None. If the function returns None, the column is ignored! """ - # Default implementation simply returns the original row data return row def row_to_dict(self, row): - """ - Convert a "row" to a named data dict - """ - + """Convert a "row" to a named data dict.""" row_dict = { 'errors': {}, } @@ -598,10 +552,7 @@ class DataFileExtractSerializer(serializers.Serializer): return row_dict def validate_extracted_columns(self): - """ - Perform custom validation of header mapping. - """ - + """Perform custom validation of header mapping.""" if self.TARGET_MODEL: try: model_fields = self.TARGET_MODEL.get_import_fields() @@ -631,7 +582,5 @@ class DataFileExtractSerializer(serializers.Serializer): cols_seen.add(col) def save(self): - """ - No "save" action for this serializer - """ + """No "save" action for this serializer.""" ... diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index 2f99274bd4..9a6b81d16f 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -1,5 +1,4 @@ -""" -Django settings for InvenTree project. +"""Django settings for InvenTree project. In practice the settings in this file should not be adjusted, instead settings can be configured in the config.yaml file @@ -8,7 +7,6 @@ located in the top level project directory. This allows implementation configuration to be hidden from source control, as well as separate configuration parameters from the more complex database setup in this file. - """ import logging diff --git a/InvenTree/InvenTree/status.py b/InvenTree/InvenTree/status.py index 9ea57024d8..cc74b850ea 100644 --- a/InvenTree/InvenTree/status.py +++ b/InvenTree/InvenTree/status.py @@ -1,6 +1,4 @@ -""" -Provides system status functionality checks. -""" +"""Provides system status functionality checks.""" # -*- coding: utf-8 -*- import logging @@ -19,10 +17,7 @@ logger = logging.getLogger("inventree") def is_worker_running(**kwargs): - """ - Return True if the background worker process is oprational - """ - + """Return True if the background worker process is oprational.""" clusters = Stat.get_all() if len(clusters) > 0: @@ -48,12 +43,10 @@ def is_worker_running(**kwargs): def is_email_configured(): - """ - Check if email backend is configured. + """Check if email backend is configured. NOTE: This does not check if the configuration is valid! """ - configured = True if InvenTree.ready.isInTestMode(): @@ -87,12 +80,10 @@ def is_email_configured(): def check_system_health(**kwargs): - """ - Check that the InvenTree system is running OK. + """Check that the InvenTree system is running OK. Returns True if all system checks pass. """ - result = True if InvenTree.ready.isInTestMode(): diff --git a/InvenTree/InvenTree/status_codes.py b/InvenTree/InvenTree/status_codes.py index 15f3d872bb..83373f43fd 100644 --- a/InvenTree/InvenTree/status_codes.py +++ b/InvenTree/InvenTree/status_codes.py @@ -2,8 +2,8 @@ from django.utils.translation import gettext_lazy as _ class StatusCode: - """ - Base class for representing a set of StatusCodes. + """Base class for representing a set of StatusCodes. + This is used to map a set of integer values to text. """ @@ -11,10 +11,7 @@ class StatusCode: @classmethod def render(cls, key, large=False): - """ - Render the value as a HTML label. - """ - + """Render the value as a HTML label.""" # If the key cannot be found, pass it back if key not in cls.options.keys(): return key @@ -31,10 +28,7 @@ class StatusCode: @classmethod def list(cls): - """ - Return the StatusCode options as a list of mapped key / value items - """ - + """Return the StatusCode options as a list of mapped key / value items.""" codes = [] for key in cls.options.keys(): @@ -71,12 +65,12 @@ class StatusCode: @classmethod def label(cls, value): - """ Return the status code label associated with the provided value """ + """Return the status code label associated with the provided value.""" return cls.options.get(value, value) @classmethod def value(cls, label): - """ Return the value associated with the provided label """ + """Return the value associated with the provided label.""" for k in cls.options.keys(): if cls.options[k].lower() == label.lower(): return k @@ -85,9 +79,7 @@ class StatusCode: class PurchaseOrderStatus(StatusCode): - """ - Defines a set of status codes for a PurchaseOrder - """ + """Defines a set of status codes for a PurchaseOrder.""" # Order status codes PENDING = 10 # Order is pending (not yet placed) @@ -130,7 +122,7 @@ class PurchaseOrderStatus(StatusCode): class SalesOrderStatus(StatusCode): - """ Defines a set of status codes for a SalesOrder """ + """Defines a set of status codes for a SalesOrder.""" PENDING = 10 # Order is pending SHIPPED = 20 # Order has been shipped to customer diff --git a/InvenTree/InvenTree/tasks.py b/InvenTree/InvenTree/tasks.py index e118c607fb..33bbecb4a2 100644 --- a/InvenTree/InvenTree/tasks.py +++ b/InvenTree/InvenTree/tasks.py @@ -16,11 +16,10 @@ logger = logging.getLogger("inventree") def schedule_task(taskname, **kwargs): - """ - Create a scheduled task. + """Create a scheduled task. + If the task has already been scheduled, ignore! """ - # If unspecified, repeat indefinitely repeats = kwargs.pop('repeats', -1) kwargs['repeats'] = repeats @@ -52,7 +51,7 @@ def schedule_task(taskname, **kwargs): def raise_warning(msg): - """Log and raise a warning""" + """Log and raise a warning.""" logger.warning(msg) # If testing is running raise a warning that can be asserted @@ -61,15 +60,11 @@ def raise_warning(msg): def offload_task(taskname, *args, force_sync=False, **kwargs): - """ - Create an AsyncTask if workers are running. - This is different to a 'scheduled' task, - in that it only runs once! + """Create an AsyncTask if workers are running. This is different to a 'scheduled' task, in that it only runs once! - If workers are not running or force_sync flag - is set then the task is ran synchronously. + If workers are not running or force_sync flag + is set then the task is ran synchronously. """ - try: import importlib @@ -129,14 +124,10 @@ def offload_task(taskname, *args, force_sync=False, **kwargs): def heartbeat(): - """ - Simple task which runs at 5 minute intervals, - so we can determine that the background worker - is actually running. + """Simple task which runs at 5 minute intervals, so we can determine that the background worker is actually running. (There is probably a less "hacky" way of achieving this)? """ - try: from django_q.models import Success except AppRegistryNotReady: # pragma: no cover @@ -156,11 +147,7 @@ def heartbeat(): def delete_successful_tasks(): - """ - Delete successful task logs - which are more than a month old. - """ - + """Delete successful task logs which are more than a month old.""" try: from django_q.models import Success except AppRegistryNotReady: # pragma: no cover @@ -179,10 +166,7 @@ def delete_successful_tasks(): def delete_old_error_logs(): - """ - Delete old error logs from the server - """ - + """Delete old error logs from the server.""" try: from error_report.models import Error @@ -204,10 +188,7 @@ def delete_old_error_logs(): def check_for_updates(): - """ - Check if there is an update for InvenTree - """ - + """Check if there is an update for InvenTree.""" try: import common.models except AppRegistryNotReady: # pragma: no cover @@ -249,10 +230,7 @@ def check_for_updates(): def update_exchange_rates(): - """ - Update currency exchange rates - """ - + """Update currency exchange rates.""" try: from djmoney.contrib.exchange.models import ExchangeBackend, Rate @@ -293,11 +271,7 @@ def update_exchange_rates(): def send_email(subject, body, recipients, from_email=None, html_message=None): - """ - Send an email with the specified subject and body, - to the specified recipients list. - """ - + """Send an email with the specified subject and body, to the specified recipients list.""" if type(recipients) == str: recipients = [recipients] diff --git a/InvenTree/InvenTree/test_api.py b/InvenTree/InvenTree/test_api.py index 889ff674b3..a0e1ddee3a 100644 --- a/InvenTree/InvenTree/test_api.py +++ b/InvenTree/InvenTree/test_api.py @@ -1,4 +1,4 @@ -""" Low level tests for the InvenTree API """ +"""Low level tests for the InvenTree API.""" from base64 import b64encode @@ -12,8 +12,7 @@ from users.models import RuleSet class HTMLAPITests(InvenTreeTestCase): - """ - Test that we can access the REST API endpoints via the HTML interface. + """Test that we can access the REST API endpoints via the HTML interface. History: Discovered on 2021-06-28 a bug in InvenTreeModelSerializer, which raised an AssertionError when using the HTML API interface, @@ -66,14 +65,13 @@ class HTMLAPITests(InvenTreeTestCase): self.assertEqual(response.status_code, 200) def test_not_found(self): - """Test that the NotFoundView is working""" - + """Test that the NotFoundView is working.""" response = self.client.get('/api/anc') self.assertEqual(response.status_code, 404) class APITests(InvenTreeAPITestCase): - """ Tests for the InvenTree API """ + """Tests for the InvenTree API.""" fixtures = [ 'location', @@ -125,10 +123,7 @@ class APITests(InvenTreeAPITestCase): self.assertIsNotNone(self.token) def test_info_view(self): - """ - Test that we can read the 'info-view' endpoint. - """ - + """Test that we can read the 'info-view' endpoint.""" url = reverse('api-inventree-info') response = self.client.get(url, format='json') @@ -141,12 +136,10 @@ class APITests(InvenTreeAPITestCase): self.assertEqual('InvenTree', data['server']) def test_role_view(self): - """ - Test that we can access the 'roles' view for the logged in user. + """Test that we can access the 'roles' view for the logged in user. Also tests that it is *not* accessible if the client is not logged in. """ - url = reverse('api-user-roles') response = self.client.get(url, format='json') @@ -182,10 +175,7 @@ class APITests(InvenTreeAPITestCase): self.assertNotIn('delete', roles[rule]) def test_with_superuser(self): - """ - Superuser should have *all* roles assigned - """ - + """Superuser should have *all* roles assigned.""" self.user.is_superuser = True self.user.save() @@ -202,10 +192,7 @@ class APITests(InvenTreeAPITestCase): self.assertIn(perm, roles[rule]) def test_with_roles(self): - """ - Assign some roles to the user - """ - + """Assign some roles to the user.""" self.basicAuth() response = self.get(reverse('api-user-roles')) @@ -220,10 +207,7 @@ class APITests(InvenTreeAPITestCase): self.assertIn('change', roles['build']) def test_list_endpoint_actions(self): - """ - Tests for the OPTIONS method for API endpoints. - """ - + """Tests for the OPTIONS method for API endpoints.""" self.basicAuth() # Without any 'part' permissions, we should not see any available actions @@ -252,10 +236,7 @@ class APITests(InvenTreeAPITestCase): self.assertIn('GET', actions) def test_detail_endpoint_actions(self): - """ - Tests for detail API endpoint actions - """ - + """Tests for detail API endpoint actions.""" self.basicAuth() url = reverse('api-part-detail', kwargs={'pk': 1}) diff --git a/InvenTree/InvenTree/test_middleware.py b/InvenTree/InvenTree/test_middleware.py index e9e5e4846f..e404ba3af8 100644 --- a/InvenTree/InvenTree/test_middleware.py +++ b/InvenTree/InvenTree/test_middleware.py @@ -1,4 +1,4 @@ -"""Tests for middleware functions""" +"""Tests for middleware functions.""" from django.urls import reverse @@ -6,7 +6,7 @@ from InvenTree.helpers import InvenTreeTestCase class MiddlewareTests(InvenTreeTestCase): - """Test for middleware functions""" + """Test for middleware functions.""" def check_path(self, url, code=200, **kwargs): response = self.client.get(url, HTTP_ACCEPT='application/json', **kwargs) @@ -14,8 +14,7 @@ class MiddlewareTests(InvenTreeTestCase): return response def test_AuthRequiredMiddleware(self): - """Test the auth middleware""" - + """Test the auth middleware.""" # test that /api/ routes go through self.check_path(reverse('api-inventree-info')) @@ -40,7 +39,7 @@ class MiddlewareTests(InvenTreeTestCase): self.check_path(reverse('settings.js'), 401) def test_token_auth(self): - """Test auth with token auth""" + """Test auth with token auth.""" # get token response = self.client.get(reverse('api-token'), format='json', data={}) token = response.data['token'] diff --git a/InvenTree/InvenTree/test_tasks.py b/InvenTree/InvenTree/test_tasks.py index 1b04e7da5b..369f021756 100644 --- a/InvenTree/InvenTree/test_tasks.py +++ b/InvenTree/InvenTree/test_tasks.py @@ -1,6 +1,4 @@ -""" -Unit tests for task management -""" +"""Unit tests for task management.""" from datetime import timedelta @@ -18,19 +16,14 @@ threshold_low = threshold - timedelta(days=1) class ScheduledTaskTests(TestCase): - """ - Unit tests for scheduled tasks - """ + """Unit tests for scheduled tasks.""" def get_tasks(self, name): return Schedule.objects.filter(func=name) def test_add_task(self): - """ - Ensure that duplicate tasks cannot be added. - """ - + """Ensure that duplicate tasks cannot be added.""" task = 'InvenTree.tasks.heartbeat' self.assertEqual(self.get_tasks(task).count(), 0) @@ -53,16 +46,15 @@ class ScheduledTaskTests(TestCase): def get_result(): - """Demo function for test_offloading""" + """Demo function for test_offloading.""" return 'abc' class InvenTreeTaskTests(TestCase): - """Unit tests for tasks""" + """Unit tests for tasks.""" def test_offloading(self): - """Test task offloading""" - + """Test task offloading.""" # Run with function ref InvenTree.tasks.offload_task(get_result) @@ -83,11 +75,11 @@ class InvenTreeTaskTests(TestCase): InvenTree.tasks.offload_task('InvenTree.test_tasks.doesnotexsist') def test_task_hearbeat(self): - """Test the task heartbeat""" + """Test the task heartbeat.""" InvenTree.tasks.offload_task(InvenTree.tasks.heartbeat) def test_task_delete_successful_tasks(self): - """Test the task delete_successful_tasks""" + """Test the task delete_successful_tasks.""" from django_q.models import Success Success.objects.create(name='abc', func='abc', stopped=threshold, started=threshold_low) @@ -96,8 +88,7 @@ class InvenTreeTaskTests(TestCase): self.assertEqual(len(results), 0) def test_task_delete_old_error_logs(self): - """Test the task delete_old_error_logs""" - + """Test the task delete_old_error_logs.""" # Create error error_obj = Error.objects.create() error_obj.when = threshold_low @@ -115,7 +106,7 @@ class InvenTreeTaskTests(TestCase): self.assertEqual(len(errors), 0) def test_task_check_for_updates(self): - """Test the task check_for_updates""" + """Test the task check_for_updates.""" # Check that setting should be empty self.assertEqual(InvenTreeSetting.get_setting('INVENTREE_LATEST_VERSION'), '') diff --git a/InvenTree/InvenTree/test_urls.py b/InvenTree/InvenTree/test_urls.py index 7f41f6e9fe..cbd80bc690 100644 --- a/InvenTree/InvenTree/test_urls.py +++ b/InvenTree/InvenTree/test_urls.py @@ -1,6 +1,4 @@ -""" -Validate that all URLs specified in template files are correct. -""" +"""Validate that all URLs specified in template files are correct.""" import os import re @@ -35,11 +33,7 @@ class URLTest(TestCase): ] def find_files(self, suffix): - """ - Search for all files in the template directories, - which can have URLs rendered - """ - + """Search for all files in the template directories, which can have URLs rendered.""" template_dirs = [ ('build', 'templates'), ('common', 'templates'), @@ -71,10 +65,7 @@ class URLTest(TestCase): return template_files def find_urls(self, input_file): - """ - Search for all instances of {% url %} in supplied template file - """ - + """Search for all instances of {% url %} in supplied template file.""" urls = [] pattern = "{% url ['\"]([^'\"]+)['\"]([^%]*)%}" @@ -100,10 +91,7 @@ class URLTest(TestCase): return urls def reverse_url(self, url_pair): - """ - Perform lookup on the URL - """ - + """Perform lookup on the URL.""" url, pk = url_pair # Ignore "renaming" @@ -125,10 +113,7 @@ class URLTest(TestCase): reverse(url) def check_file(self, f): - """ - Run URL checks for the provided file - """ - + """Run URL checks for the provided file.""" urls = self.find_urls(f) for url in urls: diff --git a/InvenTree/InvenTree/test_views.py b/InvenTree/InvenTree/test_views.py index 425de5e46c..c4d4cfd513 100644 --- a/InvenTree/InvenTree/test_views.py +++ b/InvenTree/InvenTree/test_views.py @@ -1,6 +1,4 @@ -""" -Unit tests for the main web views -""" +"""Unit tests for the main web views.""" import os import re @@ -11,33 +9,26 @@ from InvenTree.helpers import InvenTreeTestCase class ViewTests(InvenTreeTestCase): - """ Tests for various top-level views """ + """Tests for various top-level views.""" username = 'test_user' password = 'test_pass' def test_api_doc(self): - """ Test that the api-doc view works """ - + """Test that the api-doc view works.""" api_url = os.path.join(reverse('index'), 'api-doc') + '/' response = self.client.get(api_url) self.assertEqual(response.status_code, 200) def test_index_redirect(self): - """ - top-level URL should redirect to "index" page - """ - + """Top-level URL should redirect to "index" page.""" response = self.client.get("/") self.assertEqual(response.status_code, 302) def get_index_page(self): - """ - Retrieve the index page (used for subsequent unit tests) - """ - + """Retrieve the index page (used for subsequent unit tests)""" response = self.client.get("/index/") self.assertEqual(response.status_code, 200) @@ -45,10 +36,7 @@ class ViewTests(InvenTreeTestCase): return str(response.content.decode()) def test_panels(self): - """ - Test that the required 'panels' are present - """ - + """Test that the required 'panels' are present.""" content = self.get_index_page() self.assertIn("
", content) @@ -56,10 +44,7 @@ class ViewTests(InvenTreeTestCase): # TODO: In future, run the javascript and ensure that the panels get created! def test_js_load(self): - """ - Test that the required javascript files are loaded correctly - """ - + """Test that the required javascript files are loaded correctly.""" # Change this number as more javascript files are added to the index page N_SCRIPT_FILES = 40 diff --git a/InvenTree/InvenTree/tests.py b/InvenTree/InvenTree/tests.py index f306cce32a..fa6390a6d2 100644 --- a/InvenTree/InvenTree/tests.py +++ b/InvenTree/InvenTree/tests.py @@ -24,20 +24,17 @@ from .validators import validate_overage, validate_part_name class ValidatorTest(TestCase): - - """ Simple tests for custom field validators """ + """Simple tests for custom field validators.""" def test_part_name(self): - """ Test part name validator """ - + """Test part name validator.""" validate_part_name('hello world') with self.assertRaises(django_exceptions.ValidationError): validate_part_name('This | name is not } valid') def test_overage(self): - """ Test overage validator """ - + """Test overage validator.""" validate_overage("100%") validate_overage("10") validate_overage("45.2 %") @@ -59,11 +56,10 @@ class ValidatorTest(TestCase): class TestHelpers(TestCase): - """ Tests for InvenTree helper functions """ + """Tests for InvenTree helper functions.""" def test_image_url(self): - """ Test if a filename looks like an image """ - + """Test if a filename looks like an image.""" for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']: self.assertTrue(helpers.TestIfImageURL(name)) @@ -71,8 +67,7 @@ class TestHelpers(TestCase): self.assertFalse(helpers.TestIfImageURL(name)) def test_str2bool(self): - """ Test string to boolean conversion """ - + """Test string to boolean conversion.""" for s in ['yes', 'Y', 'ok', '1', 'OK', 'Ok', 'tRuE', 'oN']: self.assertTrue(helpers.str2bool(s)) self.assertFalse(helpers.str2bool(s, test=False)) @@ -110,7 +105,7 @@ class TestHelpers(TestCase): class TestQuoteWrap(TestCase): - """ Tests for string wrapping """ + """Tests for string wrapping.""" def test_single(self): @@ -121,8 +116,7 @@ class TestQuoteWrap(TestCase): class TestIncrement(TestCase): def tests(self): - """ Test 'intelligent' incrementing function """ - + """Test 'intelligent' incrementing function.""" tests = [ ("", ""), (1, "2"), @@ -142,7 +136,7 @@ class TestIncrement(TestCase): class TestMakeBarcode(TestCase): - """ Tests for barcode string creation """ + """Tests for barcode string creation.""" def test_barcode_extended(self): @@ -185,7 +179,7 @@ class TestDownloadFile(TestCase): class TestMPTT(TestCase): - """ Tests for the MPTT tree models """ + """Tests for the MPTT tree models.""" fixtures = [ 'location', @@ -197,8 +191,7 @@ class TestMPTT(TestCase): StockLocation.objects.rebuild() def test_self_as_parent(self): - """ Test that we cannot set self as parent """ - + """Test that we cannot set self as parent.""" loc = StockLocation.objects.get(pk=4) loc.parent = loc @@ -206,8 +199,7 @@ class TestMPTT(TestCase): loc.save() def test_child_as_parent(self): - """ Test that we cannot set a child as parent """ - + """Test that we cannot set a child as parent.""" parent = StockLocation.objects.get(pk=4) child = StockLocation.objects.get(pk=5) @@ -217,8 +209,7 @@ class TestMPTT(TestCase): parent.save() def test_move(self): - """ Move an item to a different tree """ - + """Move an item to a different tree.""" drawer = StockLocation.objects.get(name='Drawer_1') # Record the tree ID @@ -233,7 +224,7 @@ class TestMPTT(TestCase): class TestSerialNumberExtraction(TestCase): - """ Tests for serial number extraction code """ + """Tests for serial number extraction code.""" def test_simple(self): @@ -352,9 +343,7 @@ class TestSerialNumberExtraction(TestCase): class TestVersionNumber(TestCase): - """ - Unit tests for version number functions - """ + """Unit tests for version number functions.""" def test_tuple(self): @@ -366,10 +355,7 @@ class TestVersionNumber(TestCase): self.assertTrue(s in version.inventreeVersion()) def test_comparison(self): - """ - Test direct comparison of version numbers - """ - + """Test direct comparison of version numbers.""" v_a = version.inventreeVersionTuple('1.2.0') v_b = version.inventreeVersionTuple('1.2.3') v_c = version.inventreeVersionTuple('1.2.4') @@ -382,9 +368,7 @@ class TestVersionNumber(TestCase): class CurrencyTests(TestCase): - """ - Unit tests for currency / exchange rate functionality - """ + """Unit tests for currency / exchange rate functionality.""" def test_rates(self): @@ -435,12 +419,10 @@ class CurrencyTests(TestCase): class TestStatus(TestCase): - """ - Unit tests for status functions - """ + """Unit tests for status functions.""" def test_check_system_healt(self): - """test that the system health check is false in testing -> background worker not running""" + """Test that the system health check is false in testing -> background worker not running.""" self.assertEqual(status.check_system_health(), False) def test_TestMode(self): @@ -451,14 +433,12 @@ class TestStatus(TestCase): class TestSettings(helpers.InvenTreeTestCase): - """ - Unit tests for settings - """ + """Unit tests for settings.""" superuser = True def in_env_context(self, envs={}): - """Patch the env to include the given dict""" + """Patch the env to include the given dict.""" return mock.patch.dict(os.environ, envs) def run_reload(self, envs={}): @@ -513,7 +493,7 @@ class TestSettings(helpers.InvenTreeTestCase): settings.TESTING_ENV = False def test_initial_install(self): - """Test if install of plugins on startup works""" + """Test if install of plugins on startup works.""" from plugin import registry # Check an install run @@ -567,9 +547,7 @@ class TestSettings(helpers.InvenTreeTestCase): class TestInstanceName(helpers.InvenTreeTestCase): - """ - Unit tests for instance name - """ + """Unit tests for instance name.""" def test_instance_name(self): diff --git a/InvenTree/InvenTree/urls.py b/InvenTree/InvenTree/urls.py index c3f5b87169..e1ac6ed1f3 100644 --- a/InvenTree/InvenTree/urls.py +++ b/InvenTree/InvenTree/urls.py @@ -1,5 +1,4 @@ -""" -Top-level URL lookup for InvenTree application. +"""Top-level URL lookup for InvenTree application. Passes URL lookup downstream to each app as required. """ diff --git a/InvenTree/InvenTree/validators.py b/InvenTree/InvenTree/validators.py index 8a23eae39b..bd4c6d1485 100644 --- a/InvenTree/InvenTree/validators.py +++ b/InvenTree/InvenTree/validators.py @@ -1,6 +1,4 @@ -""" -Custom field validators for InvenTree -""" +"""Custom field validators for InvenTree.""" import re from decimal import Decimal, InvalidOperation @@ -15,20 +13,18 @@ import common.models def validate_currency_code(code): - """ - Check that a given code is a valid currency code. - """ - + """Check that a given code is a valid currency code.""" if code not in CURRENCIES: raise ValidationError(_('Not a valid currency code')) def allowable_url_schemes(): - """ Return the list of allowable URL schemes. + """Return the list of allowable URL schemes. + In addition to the default schemes allowed by Django, the install configuration file (config.yaml) can specify - extra schemas """ - + extra schemas + """ # Default schemes schemes = ['http', 'https', 'ftp', 'ftps'] @@ -42,9 +38,7 @@ def allowable_url_schemes(): def validate_part_name(value): - """ Prevent some illegal characters in part names. - """ - + """Prevent some illegal characters in part names.""" for c in ['|', '#', '$', '{', '}']: if c in str(value): raise ValidationError( @@ -53,8 +47,7 @@ def validate_part_name(value): def validate_part_ipn(value): - """ Validate the Part IPN against regex rule """ - + """Validate the Part IPN against regex rule.""" pattern = common.models.InvenTreeSetting.get_setting('PART_IPN_REGEX') if pattern: @@ -65,10 +58,7 @@ def validate_part_ipn(value): def validate_build_order_reference(value): - """ - Validate the 'reference' field of a BuildOrder - """ - + """Validate the 'reference' field of a BuildOrder.""" pattern = common.models.InvenTreeSetting.get_setting('BUILDORDER_REFERENCE_REGEX') if pattern: @@ -79,10 +69,7 @@ def validate_build_order_reference(value): def validate_purchase_order_reference(value): - """ - Validate the 'reference' field of a PurchaseOrder - """ - + """Validate the 'reference' field of a PurchaseOrder.""" pattern = common.models.InvenTreeSetting.get_setting('PURCHASEORDER_REFERENCE_REGEX') if pattern: @@ -93,10 +80,7 @@ def validate_purchase_order_reference(value): def validate_sales_order_reference(value): - """ - Validate the 'reference' field of a SalesOrder - """ - + """Validate the 'reference' field of a SalesOrder.""" pattern = common.models.InvenTreeSetting.get_setting('SALESORDER_REFERENCE_REGEX') if pattern: @@ -107,16 +91,14 @@ def validate_sales_order_reference(value): def validate_tree_name(value): - """ Prevent illegal characters in tree item names """ - + """Prevent illegal characters in tree item names.""" for c in "!@#$%^&*'\"\\/[]{}<>,|+=~`\"": if c in str(value): raise ValidationError(_('Illegal character in name ({x})'.format(x=c))) def validate_overage(value): - """ - Validate that a BOM overage string is properly formatted. + """Validate that a BOM overage string is properly formatted. An overage string can look like: @@ -124,7 +106,6 @@ def validate_overage(value): - A decimal number ('0.123') - A percentage ('5%' / '10 %') """ - value = str(value).lower().strip() # First look for a simple numerical value @@ -162,11 +143,10 @@ def validate_overage(value): def validate_part_name_format(self): - """ - Validate part name format. + """Validate part name format. + Make sure that each template container has a field of Part Model """ - jinja_template_regex = re.compile('{{.*?}}') field_name_regex = re.compile('(?<=part\\.)[A-z]+') for jinja_template in jinja_template_regex.findall(str(self)): diff --git a/InvenTree/InvenTree/version.py b/InvenTree/InvenTree/version.py index f1190ec7ba..9e58f318de 100644 --- a/InvenTree/InvenTree/version.py +++ b/InvenTree/InvenTree/version.py @@ -1,5 +1,5 @@ -""" -Version information for InvenTree. +"""Version information for InvenTree. + Provides information on the current InvenTree version """ @@ -16,12 +16,12 @@ INVENTREE_SW_VERSION = "0.8.0 dev" def inventreeInstanceName(): - """ Returns the InstanceName settings for the current database """ + """Returns the InstanceName settings for the current database.""" return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "") def inventreeInstanceTitle(): - """ Returns the InstanceTitle for the current database """ + """Returns the InstanceTitle for the current database.""" if common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE_TITLE", False): return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "") else: @@ -29,13 +29,12 @@ def inventreeInstanceTitle(): def inventreeVersion(): - """ Returns the InvenTree version string """ + """Returns the InvenTree version string.""" return INVENTREE_SW_VERSION.lower().strip() def inventreeVersionTuple(version=None): - """ Return the InvenTree version string as (maj, min, sub) tuple """ - + """Return the InvenTree version string as (maj, min, sub) tuple.""" if version is None: version = INVENTREE_SW_VERSION @@ -45,21 +44,16 @@ def inventreeVersionTuple(version=None): def isInvenTreeDevelopmentVersion(): - """ - Return True if current InvenTree version is a "development" version - """ + """Return True if current InvenTree version is a "development" version.""" return inventreeVersion().endswith('dev') def inventreeDocsVersion(): - """ - Return the version string matching the latest documentation. + """Return the version string matching the latest documentation. Development -> "latest" Release -> "major.minor.sub" e.g. "0.5.2" - """ - if isInvenTreeDevelopmentVersion(): return "latest" else: @@ -67,13 +61,10 @@ def inventreeDocsVersion(): def isInvenTreeUpToDate(): - """ - Test if the InvenTree instance is "up to date" with the latest version. + """Test if the InvenTree instance is "up to date" with the latest version. - A background task periodically queries GitHub for latest version, - and stores it to the database as INVENTREE_LATEST_VERSION + A background task periodically queries GitHub for latest version, and stores it to the database as INVENTREE_LATEST_VERSION """ - latest = common.models.InvenTreeSetting.get_setting('INVENTREE_LATEST_VERSION', backup_value=None, create=False) # No record for "latest" version - we must assume we are up to date! @@ -92,13 +83,12 @@ def inventreeApiVersion(): def inventreeDjangoVersion(): - """ Return the version of Django library """ + """Return the version of Django library.""" return django.get_version() def inventreeCommitHash(): - """ Returns the git commit hash for the running codebase """ - + """Returns the git commit hash for the running codebase.""" try: return str(subprocess.check_output('git rev-parse --short HEAD'.split()), 'utf-8').strip() except: # pragma: no cover @@ -106,8 +96,7 @@ def inventreeCommitHash(): def inventreeCommitDate(): - """ Returns the git commit date for the running codebase """ - + """Returns the git commit date for the running codebase.""" try: d = str(subprocess.check_output('git show -s --format=%ci'.split()), 'utf-8').strip() return d.split(' ')[0] diff --git a/InvenTree/InvenTree/views.py b/InvenTree/InvenTree/views.py index b29ea7cd44..325ffa9242 100644 --- a/InvenTree/InvenTree/views.py +++ b/InvenTree/InvenTree/views.py @@ -1,5 +1,4 @@ -""" -Various Views which provide extra functionality over base Django Views. +"""Various Views which provide extra functionality over base Django Views. In particular these views provide base functionality for rendering Django forms as JSON objects and passing them to modal forms (using jQuery / bootstrap). @@ -41,12 +40,10 @@ from .helpers import str2bool def auth_request(request): - """ - Simple 'auth' endpoint used to determine if the user is authenticated. - Useful for (for example) redirecting authentication requests through - django's permission framework. - """ + """Simple 'auth' endpoint used to determine if the user is authenticated. + Useful for (for example) redirecting authentication requests through django's permission framework. + """ if request.user.is_authenticated: return HttpResponse(status=200) else: @@ -54,8 +51,7 @@ def auth_request(request): class InvenTreeRoleMixin(PermissionRequiredMixin): - """ - Permission class based on user roles, not user 'permissions'. + """Permission class based on user roles, not user 'permissions'. There are a number of ways that the permissions can be specified for a view: @@ -97,10 +93,7 @@ class InvenTreeRoleMixin(PermissionRequiredMixin): role_required = None def has_permission(self): - """ - Determine if the current user has specified permissions - """ - + """Determine if the current user has specified permissions.""" roles_required = [] if type(self.role_required) is str: @@ -163,8 +156,7 @@ class InvenTreeRoleMixin(PermissionRequiredMixin): return True def get_permission_class(self): - """ - Return the 'permission_class' required for the current View. + """Return the 'permission_class' required for the current View. Must be one of: @@ -177,7 +169,6 @@ class InvenTreeRoleMixin(PermissionRequiredMixin): 'permission_class' attribute, or it can be "guessed" by looking at the type of class """ - perm = getattr(self, 'permission_class', None) # Permission is specified by the class itself @@ -204,13 +195,10 @@ class InvenTreeRoleMixin(PermissionRequiredMixin): class AjaxMixin(InvenTreeRoleMixin): - """ AjaxMixin provides basic functionality for rendering a Django form to JSON. - Handles jsonResponse rendering, and adds extra data for the modal forms to process - on the client side. + """AjaxMixin provides basic functionality for rendering a Django form to JSON. Handles jsonResponse rendering, and adds extra data for the modal forms to process on the client side. Any view which inherits the AjaxMixin will need correct permissions set using the 'role_required' attribute - """ # By default, allow *any* role @@ -223,11 +211,11 @@ class AjaxMixin(InvenTreeRoleMixin): ajax_form_title = '' def get_form_title(self): - """ Default implementation - return the ajax_form_title variable """ + """Default implementation - return the ajax_form_title variable""" return self.ajax_form_title def get_param(self, name, method='GET'): - """ Get a request query parameter value from URL e.g. ?part=3 + """Get a request query parameter value from URL e.g. ?part=3. Args: name: Variable name e.g. 'part' @@ -236,14 +224,13 @@ class AjaxMixin(InvenTreeRoleMixin): Returns: Value of the supplier parameter or None if parameter is not available """ - if method == 'POST': return self.request.POST.get(name, None) else: return self.request.GET.get(name, None) def get_data(self): - """ Get extra context data (default implementation is empty dict) + """Get extra context data (default implementation is empty dict) Returns: dict object (empty) @@ -251,20 +238,18 @@ class AjaxMixin(InvenTreeRoleMixin): return {} def validate(self, obj, form, **kwargs): - """ - Hook for performing custom form validation steps. + """Hook for performing custom form validation steps. If a form error is detected, add it to the form, with 'form.add_error()' Ref: https://docs.djangoproject.com/en/dev/topics/forms/ """ - # Do nothing by default pass def renderJsonResponse(self, request, form=None, data=None, context=None): - """ Render a JSON response based on specific class context. + """Render a JSON response based on specific class context. Args: request: HTTP request object (e.g. GET / POST) @@ -318,8 +303,7 @@ class AjaxMixin(InvenTreeRoleMixin): class AjaxView(AjaxMixin, View): - """ An 'AJAXified' View for displaying an object - """ + """An 'AJAXified' View for displaying an object.""" def post(self, request, *args, **kwargs): return self.renderJsonResponse(request) @@ -330,7 +314,7 @@ class AjaxView(AjaxMixin, View): class QRCodeView(AjaxView): - """ An 'AJAXified' view for displaying a QR code. + """An 'AJAXified' view for displaying a QR code. Subclasses should implement the get_qr_data(self) function. """ @@ -343,17 +327,17 @@ class QRCodeView(AjaxView): return self.renderJsonResponse(request, None, context=self.get_context_data()) def get_qr_data(self): - """ Returns the text object to render to a QR code. - The actual rendering will be handled by the template """ + """Returns the text object to render to a QR code. + The actual rendering will be handled by the template + """ return None def get_context_data(self): - """ Get context data for passing to the rendering template. + """Get context data for passing to the rendering template. Explicity passes the parameter 'qr_data' """ - context = {} qr = self.get_qr_data() @@ -367,15 +351,14 @@ class QRCodeView(AjaxView): class AjaxCreateView(AjaxMixin, CreateView): + """An 'AJAXified' CreateView for creating a new object in the db. - """ An 'AJAXified' CreateView for creating a new object in the db - Returns a form in JSON format (for delivery to a modal window) - Handles form validation via AJAX POST requests """ def get(self, request, *args, **kwargs): - """ Creates form with initial data, and renders JSON response """ - + """Creates form with initial data, and renders JSON response.""" super(CreateView, self).get(request, *args, **kwargs) self.request = request @@ -383,18 +366,16 @@ class AjaxCreateView(AjaxMixin, CreateView): return self.renderJsonResponse(request, form) def save(self, form): - """ - Method for actually saving the form to the database. - Default implementation is very simple, - but can be overridden if required. - """ + """Method for actually saving the form to the database. + Default implementation is very simple, but can be overridden if required. + """ self.object = form.save() return self.object def post(self, request, *args, **kwargs): - """ Responds to form POST. Validates POST data and returns status info. + """Responds to form POST. Validates POST data and returns status info. - Validate POST form data - If valid, save form @@ -441,45 +422,41 @@ class AjaxCreateView(AjaxMixin, CreateView): class AjaxUpdateView(AjaxMixin, UpdateView): - """ An 'AJAXified' UpdateView for updating an object in the db + """An 'AJAXified' UpdateView for updating an object in the db. + - Returns form in JSON format (for delivery to a modal window) - Handles repeated form validation (via AJAX) until the form is valid """ def get(self, request, *args, **kwargs): - """ Respond to GET request. + """Respond to GET request. - Populates form with object data - Renders form to JSON and returns to client """ - super(UpdateView, self).get(request, *args, **kwargs) return self.renderJsonResponse(request, self.get_form(), context=self.get_context_data()) def save(self, object, form, **kwargs): - """ - Method for updating the object in the database. - Default implementation is very simple, but can be overridden if required. + """Method for updating the object in the database. Default implementation is very simple, but can be overridden if required. Args: object - The current object, to be updated form - The validated form """ - self.object = form.save() return self.object def post(self, request, *args, **kwargs): - """ Respond to POST request. + """Respond to POST request. - Updates model with POST field data - Performs form and object validation - If errors exist, re-render the form - Otherwise, return sucess status """ - self.request = request # Make sure we have an object to point to @@ -524,8 +501,8 @@ class AjaxUpdateView(AjaxMixin, UpdateView): class AjaxDeleteView(AjaxMixin, UpdateView): + """An 'AJAXified DeleteView for removing an object from the DB. - """ An 'AJAXified DeleteView for removing an object from the DB - Returns a HTML object (not a form!) in JSON format (for delivery to a modal window) - Handles deletion """ @@ -546,12 +523,11 @@ class AjaxDeleteView(AjaxMixin, UpdateView): return self.form_class(self.get_form_kwargs()) def get(self, request, *args, **kwargs): - """ Respond to GET request + """Respond to GET request. - Render a DELETE confirmation form to JSON - Return rendered form to client """ - super(UpdateView, self).get(request, *args, **kwargs) form = self.get_form() @@ -563,12 +539,11 @@ class AjaxDeleteView(AjaxMixin, UpdateView): return self.renderJsonResponse(request, form, context=context) def post(self, request, *args, **kwargs): - """ Respond to POST request + """Respond to POST request. - DELETE the object - Render success message to JSON and return to client """ - obj = self.get_object() pk = obj.id @@ -592,7 +567,7 @@ class AjaxDeleteView(AjaxMixin, UpdateView): class EditUserView(AjaxUpdateView): - """ View for editing user information """ + """View for editing user information.""" ajax_template_name = "modal_form.html" ajax_form_title = _("Edit User Information") @@ -603,7 +578,7 @@ class EditUserView(AjaxUpdateView): class SetPasswordView(AjaxUpdateView): - """ View for setting user password """ + """View for setting user password.""" ajax_template_name = "InvenTree/password.html" ajax_form_title = _("Set Password") @@ -645,7 +620,7 @@ class SetPasswordView(AjaxUpdateView): class IndexView(TemplateView): - """ View for InvenTree index page """ + """View for InvenTree index page.""" template_name = 'InvenTree/index.html' @@ -657,7 +632,7 @@ class IndexView(TemplateView): class SearchView(TemplateView): - """ View for InvenTree search page. + """View for InvenTree search page. Displays results of search query """ @@ -665,11 +640,10 @@ class SearchView(TemplateView): template_name = 'InvenTree/search.html' def post(self, request, *args, **kwargs): - """ Handle POST request (which contains search query). + """Handle POST request (which contains search query). Pass the search query to the page template """ - context = self.get_context_data() query = request.POST.get('search', '') @@ -680,19 +654,14 @@ class SearchView(TemplateView): class DynamicJsView(TemplateView): - """ - View for returning javacsript files, - which instead of being served dynamically, - are passed through the django translation engine! - """ + """View for returning javacsript files, which instead of being served dynamically, are passed through the django translation engine!""" template_name = "" content_type = 'text/javascript' class SettingsView(TemplateView): - """ View for configuring User settings - """ + """View for configuring User settings.""" template_name = "InvenTree/settings/settings.html" @@ -739,37 +708,29 @@ class SettingsView(TemplateView): class AllauthOverrides(LoginRequiredMixin): - """ - Override allauths views to always redirect to success_url - """ + """Override allauths views to always redirect to success_url.""" def get(self, request, *args, **kwargs): # always redirect to settings return HttpResponseRedirect(self.success_url) class CustomEmailView(AllauthOverrides, EmailView): - """ - Override of allauths EmailView to always show the settings but leave the functions allow - """ + """Override of allauths EmailView to always show the settings but leave the functions allow.""" success_url = reverse_lazy("settings") class CustomConnectionsView(AllauthOverrides, ConnectionsView): - """ - Override of allauths ConnectionsView to always show the settings but leave the functions allow - """ + """Override of allauths ConnectionsView to always show the settings but leave the functions allow.""" success_url = reverse_lazy("settings") class CustomPasswordResetFromKeyView(PasswordResetFromKeyView): - """ - Override of allauths PasswordResetFromKeyView to always show the settings but leave the functions allow - """ + """Override of allauths PasswordResetFromKeyView to always show the settings but leave the functions allow.""" success_url = reverse_lazy("account_login") class UserSessionOverride(): - """overrides sucessurl to lead to settings""" + """overrides sucessurl to lead to settings.""" def get_success_url(self): return str(reverse_lazy('settings')) @@ -783,17 +744,12 @@ class CustomSessionDeleteOtherView(UserSessionOverride, SessionDeleteOtherView): class CurrencyRefreshView(RedirectView): - """ - POST endpoint to refresh / update exchange rates - """ + """POST endpoint to refresh / update exchange rates.""" url = reverse_lazy("settings-currencies") def post(self, request, *args, **kwargs): - """ - On a POST request we will attempt to refresh the exchange rates - """ - + """On a POST request we will attempt to refresh the exchange rates.""" from InvenTree.tasks import offload_task, update_exchange_rates offload_task(update_exchange_rates, force_sync=True) @@ -802,10 +758,10 @@ class CurrencyRefreshView(RedirectView): class AppearanceSelectView(RedirectView): - """ View for selecting a color theme """ + """View for selecting a color theme.""" def get_user_theme(self): - """ Get current user color theme """ + """Get current user color theme.""" try: user_theme = ColorTheme.objects.filter(user=self.request.user).get() except ColorTheme.DoesNotExist: @@ -814,8 +770,7 @@ class AppearanceSelectView(RedirectView): return user_theme def post(self, request, *args, **kwargs): - """ Save user color theme selection """ - + """Save user color theme selection.""" theme = request.POST.get('theme', None) # Get current user theme @@ -833,15 +788,14 @@ class AppearanceSelectView(RedirectView): class SettingCategorySelectView(FormView): - """ View for selecting categories in settings """ + """View for selecting categories in settings.""" form_class = SettingCategorySelectForm success_url = reverse_lazy('settings-category') template_name = "InvenTree/settings/category.html" def get_initial(self): - """ Set category selection """ - + """Set category selection.""" initial = super().get_initial() category = self.request.GET.get('category', None) @@ -851,11 +805,10 @@ class SettingCategorySelectView(FormView): return initial def post(self, request, *args, **kwargs): - """ Handle POST request (which contains category selection). + """Handle POST request (which contains category selection). Pass the selected category to the page template """ - form = self.get_form() if form.is_valid(): @@ -869,14 +822,13 @@ class SettingCategorySelectView(FormView): class DatabaseStatsView(AjaxView): - """ View for displaying database statistics """ + """View for displaying database statistics.""" ajax_template_name = "stats.html" ajax_form_title = _("System Information") class NotificationsView(TemplateView): - """ View for showing notifications - """ + """View for showing notifications.""" template_name = "InvenTree/notifications/notifications.html" diff --git a/InvenTree/InvenTree/wsgi.py b/InvenTree/InvenTree/wsgi.py index 9c4d72edbc..dfced329a8 100644 --- a/InvenTree/InvenTree/wsgi.py +++ b/InvenTree/InvenTree/wsgi.py @@ -1,5 +1,4 @@ -""" -WSGI config for InvenTree project. +"""WSGI config for InvenTree project. It exposes the WSGI callable as a module-level variable named ``application``. diff --git a/InvenTree/build/__init__.py b/InvenTree/build/__init__.py index 747a20f837..924a19b982 100644 --- a/InvenTree/build/__init__.py +++ b/InvenTree/build/__init__.py @@ -1,5 +1,4 @@ -""" -The Build module is responsible for managing "Build" transactions. +"""The Build module is responsible for managing "Build" transactions. A Build consumes parts from stock to create new parts """ diff --git a/InvenTree/build/admin.py b/InvenTree/build/admin.py index 5988850fe4..640cf0778a 100644 --- a/InvenTree/build/admin.py +++ b/InvenTree/build/admin.py @@ -11,7 +11,7 @@ import part.models class BuildResource(ModelResource): - """Class for managing import/export of Build data""" + """Class for managing import/export of Build data.""" # For some reason, we need to specify the fields individually for this ModelResource, # but we don't for other ones. # TODO: 2022-05-12 - Need to investigate why this is the case! diff --git a/InvenTree/build/api.py b/InvenTree/build/api.py index c6c1c73128..143e3643f9 100644 --- a/InvenTree/build/api.py +++ b/InvenTree/build/api.py @@ -1,6 +1,4 @@ -""" -JSON API for the Build app -""" +"""JSON API for the Build app.""" from django.urls import include, re_path @@ -22,9 +20,7 @@ from users.models import Owner class BuildFilter(rest_filters.FilterSet): - """ - Custom filterset for BuildList API endpoint - """ + """Custom filterset for BuildList API endpoint.""" status = rest_filters.NumberFilter(label='Status') @@ -53,10 +49,7 @@ class BuildFilter(rest_filters.FilterSet): assigned_to_me = rest_filters.BooleanFilter(label='assigned_to_me', method='filter_assigned_to_me') def filter_assigned_to_me(self, queryset, name, value): - """ - Filter by orders which are assigned to the current user - """ - + """Filter by orders which are assigned to the current user.""" value = str2bool(value) # Work out who "me" is! @@ -71,7 +64,7 @@ class BuildFilter(rest_filters.FilterSet): class BuildList(APIDownloadMixin, generics.ListCreateAPIView): - """ API endpoint for accessing a list of Build objects. + """API endpoint for accessing a list of Build objects. - GET: Return list of objects (with filters) - POST: Create a new Build object @@ -111,11 +104,7 @@ class BuildList(APIDownloadMixin, generics.ListCreateAPIView): ] def get_queryset(self): - """ - Override the queryset filtering, - as some of the fields don't natively play nicely with DRF - """ - + """Override the queryset filtering, as some of the fields don't natively play nicely with DRF.""" queryset = super().get_queryset().select_related('part') queryset = build.serializers.BuildSerializer.annotate_queryset(queryset) @@ -207,15 +196,14 @@ class BuildList(APIDownloadMixin, generics.ListCreateAPIView): class BuildDetail(generics.RetrieveUpdateAPIView): - """ API endpoint for detail view of a Build object """ + """API endpoint for detail view of a Build object.""" queryset = Build.objects.all() serializer_class = build.serializers.BuildSerializer class BuildUnallocate(generics.CreateAPIView): - """ - API endpoint for unallocating stock items from a build order + """API endpoint for unallocating stock items from a build order. - The BuildOrder object is specified by the URL - "output" (StockItem) can optionally be specified @@ -241,7 +229,7 @@ class BuildUnallocate(generics.CreateAPIView): class BuildOrderContextMixin: - """ Mixin class which adds build order as serializer context variable """ + """Mixin class which adds build order as serializer context variable.""" def get_serializer_context(self): ctx = super().get_serializer_context() @@ -258,9 +246,7 @@ class BuildOrderContextMixin: class BuildOutputCreate(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for creating new build output(s) - """ + """API endpoint for creating new build output(s)""" queryset = Build.objects.none() @@ -268,9 +254,7 @@ class BuildOutputCreate(BuildOrderContextMixin, generics.CreateAPIView): class BuildOutputComplete(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for completing build outputs - """ + """API endpoint for completing build outputs.""" queryset = Build.objects.none() @@ -278,9 +262,7 @@ class BuildOutputComplete(BuildOrderContextMixin, generics.CreateAPIView): class BuildOutputDelete(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for deleting multiple build outputs - """ + """API endpoint for deleting multiple build outputs.""" def get_serializer_context(self): ctx = super().get_serializer_context() @@ -295,9 +277,7 @@ class BuildOutputDelete(BuildOrderContextMixin, generics.CreateAPIView): class BuildFinish(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for marking a build as finished (completed) - """ + """API endpoint for marking a build as finished (completed)""" queryset = Build.objects.none() @@ -305,8 +285,7 @@ class BuildFinish(BuildOrderContextMixin, generics.CreateAPIView): class BuildAutoAllocate(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for 'automatically' allocating stock against a build order. + """API endpoint for 'automatically' allocating stock against a build order. - Only looks at 'untracked' parts - If stock exists in a single location, easy! @@ -320,8 +299,7 @@ class BuildAutoAllocate(BuildOrderContextMixin, generics.CreateAPIView): class BuildAllocate(BuildOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to allocate stock items to a build order + """API endpoint to allocate stock items to a build order. - The BuildOrder object is specified by the URL - Items to allocate are specified as a list called "items" with the following options: @@ -337,23 +315,21 @@ class BuildAllocate(BuildOrderContextMixin, generics.CreateAPIView): class BuildCancel(BuildOrderContextMixin, generics.CreateAPIView): - """ API endpoint for cancelling a BuildOrder """ + """API endpoint for cancelling a BuildOrder.""" queryset = Build.objects.all() serializer_class = build.serializers.BuildCancelSerializer class BuildItemDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for detail view of a BuildItem object - """ + """API endpoint for detail view of a BuildItem object.""" queryset = BuildItem.objects.all() serializer_class = build.serializers.BuildItemSerializer class BuildItemList(generics.ListCreateAPIView): - """ API endpoint for accessing a list of BuildItem objects + """API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object @@ -375,10 +351,7 @@ class BuildItemList(generics.ListCreateAPIView): return self.serializer_class(*args, **kwargs) def get_queryset(self): - """ Override the queryset method, - to allow filtering by stock_item.part - """ - + """Override the queryset method, to allow filtering by stock_item.part.""" query = BuildItem.objects.all() query = query.select_related('stock_item__location') @@ -436,9 +409,7 @@ class BuildItemList(generics.ListCreateAPIView): class BuildAttachmentList(generics.ListCreateAPIView, AttachmentMixin): - """ - API endpoint for listing (and creating) BuildOrderAttachment objects - """ + """API endpoint for listing (and creating) BuildOrderAttachment objects.""" queryset = BuildOrderAttachment.objects.all() serializer_class = build.serializers.BuildAttachmentSerializer @@ -453,9 +424,7 @@ class BuildAttachmentList(generics.ListCreateAPIView, AttachmentMixin): class BuildAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin): - """ - Detail endpoint for a BuildOrderAttachment object - """ + """Detail endpoint for a BuildOrderAttachment object.""" queryset = BuildOrderAttachment.objects.all() serializer_class = build.serializers.BuildAttachmentSerializer diff --git a/InvenTree/build/models.py b/InvenTree/build/models.py index 0f539dc158..3a960c5019 100644 --- a/InvenTree/build/models.py +++ b/InvenTree/build/models.py @@ -1,6 +1,4 @@ -""" -Build database model definitions -""" +"""Build database model definitions.""" import decimal @@ -42,10 +40,7 @@ from users import models as UserModels def get_next_build_number(): - """ - Returns the next available BuildOrder reference number - """ - + """Returns the next available BuildOrder reference number.""" if Build.objects.count() == 0: return '0001' @@ -71,7 +66,7 @@ def get_next_build_number(): class Build(MPTTModel, ReferenceIndexingMixin): - """ A Build object organises the creation of new StockItem objects from other existing StockItem objects. + """A Build object organises the creation of new StockItem objects from other existing StockItem objects. Attributes: part: The part to be built (from component BOM items) @@ -109,10 +104,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @classmethod def api_defaults(cls, request): - """ - Return default values for this model when issuing an API OPTIONS request - """ - + """Return default values for this model when issuing an API OPTIONS request.""" defaults = { 'reference': get_next_build_number(), } @@ -138,10 +130,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): verbose_name_plural = _("Build Orders") def format_barcode(self, **kwargs): - """ - Return a JSON string to represent this build as a barcode - """ - + """Return a JSON string to represent this build as a barcode.""" return MakeBarcode( "buildorder", self.pk, @@ -153,13 +142,11 @@ class Build(MPTTModel, ReferenceIndexingMixin): @staticmethod def filterByDate(queryset, min_date, max_date): - """ - Filter by 'minimum and maximum date range' + """Filter by 'minimum and maximum date range'. - Specified as min_date, max_date - Both must be specified for filter to be applied """ - date_fmt = '%Y-%m-%d' # ISO format date string # Ensure that both dates are valid @@ -336,10 +323,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): ) def sub_builds(self, cascade=True): - """ - Return all Build Order objects under this one. - """ - + """Return all Build Order objects under this one.""" if cascade: return Build.objects.filter(parent=self.pk) else: @@ -347,23 +331,19 @@ class Build(MPTTModel, ReferenceIndexingMixin): Build.objects.filter(parent__pk__in=[d.pk for d in descendants]) def sub_build_count(self, cascade=True): - """ - Return the number of sub builds under this one. + """Return the number of sub builds under this one. Args: cascade: If True (defualt), include cascading builds under sub builds """ - return self.sub_builds(cascade=cascade).count() @property def is_overdue(self): - """ - Returns true if this build is "overdue": + """Returns true if this build is "overdue": Makes use of the OVERDUE_FILTER to avoid code duplication """ - query = Build.objects.filter(pk=self.pk) query = query.filter(Build.OVERDUE_FILTER) @@ -371,62 +351,41 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def active(self): - """ - Return True if this build is active - """ - + """Return True if this build is active.""" return self.status in BuildStatus.ACTIVE_CODES @property def bom_items(self): - """ - Returns the BOM items for the part referenced by this BuildOrder - """ - + """Returns the BOM items for the part referenced by this BuildOrder.""" return self.part.get_bom_items() @property def tracked_bom_items(self): - """ - Returns the "trackable" BOM items for this BuildOrder - """ - + """Returns the "trackable" BOM items for this BuildOrder.""" items = self.bom_items items = items.filter(sub_part__trackable=True) return items def has_tracked_bom_items(self): - """ - Returns True if this BuildOrder has trackable BomItems - """ - + """Returns True if this BuildOrder has trackable BomItems.""" return self.tracked_bom_items.count() > 0 @property def untracked_bom_items(self): - """ - Returns the "non trackable" BOM items for this BuildOrder - """ - + """Returns the "non trackable" BOM items for this BuildOrder.""" items = self.bom_items items = items.filter(sub_part__trackable=False) return items def has_untracked_bom_items(self): - """ - Returns True if this BuildOrder has non trackable BomItems - """ - + """Returns True if this BuildOrder has non trackable BomItems.""" return self.untracked_bom_items.count() > 0 @property def remaining(self): - """ - Return the number of outputs remaining to be completed. - """ - + """Return the number of outputs remaining to be completed.""" return max(0, self.quantity - self.completed) @property @@ -437,14 +396,12 @@ class Build(MPTTModel, ReferenceIndexingMixin): return self.output_count > 0 def get_build_outputs(self, **kwargs): - """ - Return a list of build outputs. + """Return a list of build outputs. kwargs: complete = (True / False) - If supplied, filter by completed status in_stock = (True / False) - If supplied, filter by 'in-stock' status """ - outputs = self.build_outputs.all() # Filter by 'in stock' status @@ -469,10 +426,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def complete_outputs(self): - """ - Return all the "completed" build outputs - """ - + """Return all the "completed" build outputs.""" outputs = self.get_build_outputs(complete=True) return outputs @@ -489,20 +443,14 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def incomplete_outputs(self): - """ - Return all the "incomplete" build outputs - """ - + """Return all the "incomplete" build outputs.""" outputs = self.get_build_outputs(complete=False) return outputs @property def incomplete_count(self): - """ - Return the total number of "incomplete" outputs - """ - + """Return the total number of "incomplete" outputs.""" quantity = 0 for output in self.incomplete_outputs: @@ -512,10 +460,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @classmethod def getNextBuildNumber(cls): - """ - Try to predict the next Build Order reference: - """ - + """Try to predict the next Build Order reference.""" if cls.objects.count() == 0: return None @@ -552,13 +497,11 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def can_complete(self): - """ - Returns True if this build can be "completed" + """Returns True if this build can be "completed". - Must not have any outstanding build outputs - 'completed' value must meet (or exceed) the 'quantity' value """ - if self.incomplete_count > 0: return False @@ -573,10 +516,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def complete_build(self, user): - """ - Mark this build as complete - """ - + """Mark this build as complete.""" if self.incomplete_count > 0: return @@ -597,13 +537,12 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def cancel_build(self, user, **kwargs): - """ Mark the Build as CANCELLED + """Mark the Build as CANCELLED. - Delete any pending BuildItem objects (but do not remove items from stock) - Set build status to CANCELLED - Save the Build object """ - remove_allocated_stock = kwargs.get('remove_allocated_stock', False) remove_incomplete_outputs = kwargs.get('remove_incomplete_outputs', False) @@ -633,14 +572,12 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def unallocateStock(self, bom_item=None, output=None): - """ - Unallocate stock from this Build + """Unallocate stock from this Build. - arguments: + Arguments: - bom_item: Specify a particular BomItem to unallocate stock against - output: Specify a particular StockItem (output) to unallocate stock against """ - allocations = BuildItem.objects.filter( build=self, install_into=output @@ -653,19 +590,17 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def create_build_output(self, quantity, **kwargs): - """ - Create a new build output against this BuildOrder. + """Create a new build output against this BuildOrder. - args: + Args: quantity: The quantity of the item to produce - kwargs: + Kwargs: batch: Override batch code serials: Serial numbers location: Override location auto_allocate: Automatically allocate stock with matching serial numbers """ - batch = kwargs.get('batch', self.batch) location = kwargs.get('location', self.destination) serials = kwargs.get('serials', None) @@ -687,9 +622,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): multiple = True if multiple: - """ - Create multiple build outputs with a single quantity of 1 - """ + """Create multiple build outputs with a single quantity of 1.""" # Quantity *must* be an integer at this point! quantity = int(quantity) @@ -743,9 +676,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): ) else: - """ - Create a single build output of the given quantity - """ + """Create a single build output of the given quantity.""" StockModels.StockItem.objects.create( quantity=quantity, @@ -762,13 +693,11 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def delete_output(self, output): - """ - Remove a build output from the database: + """Remove a build output from the database: - Unallocate any build items against the output - Delete the output StockItem """ - if not output: raise ValidationError(_("No build output specified")) @@ -786,11 +715,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def subtract_allocated_stock(self, user): - """ - Called when the Build is marked as "complete", - this function removes the allocated untracked items from stock. - """ - + """Called when the Build is marked as "complete", this function removes the allocated untracked items from stock.""" items = self.allocated_stock.filter( stock_item__part__trackable=False ) @@ -804,13 +729,11 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def complete_build_output(self, output, user, **kwargs): - """ - Complete a particular build output + """Complete a particular build output. - Remove allocated StockItems - Mark the output as complete """ - # Select the location for the build output location = kwargs.get('location', self.destination) status = kwargs.get('status', StockStatus.OK) @@ -850,10 +773,9 @@ class Build(MPTTModel, ReferenceIndexingMixin): @transaction.atomic def auto_allocate_stock(self, **kwargs): - """ - Automatically allocate stock items against this build order, - following a number of 'guidelines': + """Automatically allocate stock items against this build order. + Following a number of 'guidelines': - Only "untracked" BOM items are considered (tracked BOM items must be manually allocated) - If a particular BOM item is already fully allocated, it is skipped - Extract all available stock items for the BOM part @@ -863,7 +785,6 @@ class Build(MPTTModel, ReferenceIndexingMixin): - If multiple stock items are found, we *may* be able to allocate: - If the calling function has specified that items are interchangeable """ - location = kwargs.get('location', None) exclude_location = kwargs.get('exclude_location', None) interchangeable = kwargs.get('interchangeable', False) @@ -958,14 +879,12 @@ class Build(MPTTModel, ReferenceIndexingMixin): break def required_quantity(self, bom_item, output=None): - """ - Get the quantity of a part required to complete the particular build output. + """Get the quantity of a part required to complete the particular build output. Args: part: The Part object output - The particular build output (StockItem) """ - quantity = bom_item.quantity if output: @@ -976,8 +895,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): return quantity def allocated_bom_items(self, bom_item, output=None): - """ - Return all BuildItem objects which allocate stock of to + """Return all BuildItem objects which allocate stock of to Note that the bom_item may allow variants, or direct substitutes, making things difficult. @@ -986,7 +904,6 @@ class Build(MPTTModel, ReferenceIndexingMixin): bom_item - The BomItem object output - Build output (StockItem). """ - allocations = BuildItem.objects.filter( build=self, bom_item=bom_item, @@ -996,10 +913,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): return allocations def allocated_quantity(self, bom_item, output=None): - """ - Return the total quantity of given part allocated to a given build output. - """ - + """Return the total quantity of given part allocated to a given build output.""" allocations = self.allocated_bom_items(bom_item, output) allocated = allocations.aggregate( @@ -1013,27 +927,18 @@ class Build(MPTTModel, ReferenceIndexingMixin): return allocated['q'] def unallocated_quantity(self, bom_item, output=None): - """ - Return the total unallocated (remaining) quantity of a part against a particular output. - """ - + """Return the total unallocated (remaining) quantity of a part against a particular output.""" required = self.required_quantity(bom_item, output) allocated = self.allocated_quantity(bom_item, output) return max(required - allocated, 0) def is_bom_item_allocated(self, bom_item, output=None): - """ - Test if the supplied BomItem has been fully allocated! - """ - + """Test if the supplied BomItem has been fully allocated!""" return self.unallocated_quantity(bom_item, output) == 0 def is_fully_allocated(self, output): - """ - Returns True if the particular build output is fully allocated. - """ - + """Returns True if the particular build output is fully allocated.""" # If output is not specified, we are talking about "untracked" items if output is None: bom_items = self.untracked_bom_items @@ -1049,10 +954,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): return True def is_partially_allocated(self, output): - """ - Returns True if the particular build output is (at least) partially allocated - """ - + """Returns True if the particular build output is (at least) partially allocated.""" # If output is not specified, we are talking about "untracked" items if output is None: bom_items = self.untracked_bom_items @@ -1067,17 +969,11 @@ class Build(MPTTModel, ReferenceIndexingMixin): return False def are_untracked_parts_allocated(self): - """ - Returns True if the un-tracked parts are fully allocated for this BuildOrder - """ - + """Returns True if the un-tracked parts are fully allocated for this BuildOrder.""" return self.is_fully_allocated(None) def unallocated_bom_items(self, output): - """ - Return a list of bom items which have *not* been fully allocated against a particular output - """ - + """Return a list of bom items which have *not* been fully allocated against a particular output.""" unallocated = [] # If output is not specified, we are talking about "untracked" items @@ -1095,7 +991,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def required_parts(self): - """ Returns a list of parts required to build this part (BOM) """ + """Returns a list of parts required to build this part (BOM)""" parts = [] for item in self.bom_items: @@ -1105,7 +1001,7 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def required_parts_to_complete_build(self): - """ Returns a list of parts required to complete the full build """ + """Returns a list of parts required to complete the full build.""" parts = [] for bom_item in self.bom_items: @@ -1119,26 +1015,23 @@ class Build(MPTTModel, ReferenceIndexingMixin): @property def is_active(self): - """ Is this build active? An active build is either: + """Is this build active? + An active build is either: - PENDING - HOLDING """ - return self.status in BuildStatus.ACTIVE_CODES @property def is_complete(self): - """ Returns True if the build status is COMPLETE """ - + """Returns True if the build status is COMPLETE.""" return self.status == BuildStatus.COMPLETE @receiver(post_save, sender=Build, dispatch_uid='build_post_save_log') def after_save_build(sender, instance: Build, created: bool, **kwargs): - """ - Callback function to be executed after a Build instance is saved - """ + """Callback function to be executed after a Build instance is saved.""" from . import tasks as build_tasks if created: @@ -1149,9 +1042,7 @@ def after_save_build(sender, instance: Build, created: bool, **kwargs): class BuildOrderAttachment(InvenTreeAttachment): - """ - Model for storing file attachments against a BuildOrder object - """ + """Model for storing file attachments against a BuildOrder object.""" def getSubdir(self): return os.path.join('bo_files', str(self.build.id)) @@ -1160,10 +1051,9 @@ class BuildOrderAttachment(InvenTreeAttachment): class BuildItem(models.Model): - """ A BuildItem links multiple StockItem objects to a Build. - These are used to allocate part stock to a build. - Once the Build is completed, the parts are removed from stock and the - BuildItemAllocation objects are removed. + """A BuildItem links multiple StockItem objects to a Build. + + These are used to allocate part stock to a build. Once the Build is completed, the parts are removed from stock and the BuildItemAllocation objects are removed. Attributes: build: Link to a Build object @@ -1194,14 +1084,12 @@ class BuildItem(models.Model): super().save() def clean(self): - """ - Check validity of this BuildItem instance. - The following checks are performed: + """Check validity of this BuildItem instance. + The following checks are performed: - StockItem.part must be in the BOM of the Part object referenced by Build - Allocation quantity cannot exceed available quantity """ - self.validate_unique() super().clean() @@ -1303,13 +1191,11 @@ class BuildItem(models.Model): @transaction.atomic def complete_allocation(self, user, notes=''): - """ - Complete the allocation of this BuildItem into the output stock item. + """Complete the allocation of this BuildItem into the output stock item. - If the referenced part is trackable, the stock item will be *installed* into the build output - If the referenced part is *not* trackable, the stock item will be removed from stock """ - item = self.stock_item # For a trackable part, special consideration needed! @@ -1344,10 +1230,7 @@ class BuildItem(models.Model): ) def getStockItemThumbnail(self): - """ - Return qualified URL for part thumbnail image - """ - + """Return qualified URL for part thumbnail image.""" thumb_url = None if self.stock_item and self.stock_item.part: diff --git a/InvenTree/build/serializers.py b/InvenTree/build/serializers.py index e4919f1433..ea4321c04b 100644 --- a/InvenTree/build/serializers.py +++ b/InvenTree/build/serializers.py @@ -1,6 +1,4 @@ -""" -JSON serializers for Build API -""" +"""JSON serializers for Build API.""" from django.db import transaction from django.core.exceptions import ValidationError as DjangoValidationError @@ -31,9 +29,7 @@ from .models import Build, BuildItem, BuildOrderAttachment class BuildSerializer(ReferenceIndexingSerializerMixin, InvenTreeModelSerializer): - """ - Serializes a Build object - """ + """Serializes a Build object.""" url = serializers.CharField(source='get_absolute_url', read_only=True) status_text = serializers.CharField(source='get_status_display', read_only=True) @@ -50,16 +46,12 @@ class BuildSerializer(ReferenceIndexingSerializerMixin, InvenTreeModelSerializer @staticmethod def annotate_queryset(queryset): - """ - Add custom annotations to the BuildSerializer queryset, - performing database queries as efficiently as possible. + """Add custom annotations to the BuildSerializer queryset, performing database queries as efficiently as possible. The following annoted fields are added: - overdue: True if the build is outstanding *and* the completion date has past - """ - # Annotate a boolean 'overdue' flag queryset = queryset.annotate( @@ -121,8 +113,7 @@ class BuildSerializer(ReferenceIndexingSerializerMixin, InvenTreeModelSerializer class BuildOutputSerializer(serializers.Serializer): - """ - Serializer for a "BuildOutput" + """Serializer for a "BuildOutput". Note that a "BuildOutput" is really just a StockItem which is "in production"! """ @@ -174,8 +165,7 @@ class BuildOutputSerializer(serializers.Serializer): class BuildOutputCreateSerializer(serializers.Serializer): - """ - Serializer for creating a new BuildOutput against a BuildOrder. + """Serializer for creating a new BuildOutput against a BuildOrder. URL pattern is "/api/build//create-output/", where is the PK of a Build. @@ -243,10 +233,7 @@ class BuildOutputCreateSerializer(serializers.Serializer): ) def validate(self, data): - """ - Perform form validation - """ - + """Perform form validation.""" part = self.get_part() # Cache a list of serial numbers (to be used in the "save" method) @@ -284,10 +271,7 @@ class BuildOutputCreateSerializer(serializers.Serializer): return data def save(self): - """ - Generate the new build output(s) - """ - + """Generate the new build output(s)""" data = self.validated_data quantity = data['quantity'] @@ -305,9 +289,7 @@ class BuildOutputCreateSerializer(serializers.Serializer): class BuildOutputDeleteSerializer(serializers.Serializer): - """ - DRF serializer for deleting (cancelling) one or more build outputs - """ + """DRF serializer for deleting (cancelling) one or more build outputs.""" class Meta: fields = [ @@ -331,10 +313,7 @@ class BuildOutputDeleteSerializer(serializers.Serializer): return data def save(self): - """ - 'save' the serializer to delete the build outputs - """ - + """'save' the serializer to delete the build outputs.""" data = self.validated_data outputs = data.get('outputs', []) @@ -347,9 +326,7 @@ class BuildOutputDeleteSerializer(serializers.Serializer): class BuildOutputCompleteSerializer(serializers.Serializer): - """ - DRF serializer for completing one or more build outputs - """ + """DRF serializer for completing one or more build outputs.""" class Meta: fields = [ @@ -404,10 +381,7 @@ class BuildOutputCompleteSerializer(serializers.Serializer): return data def save(self): - """ - "save" the serializer to complete the build outputs - """ - + """Save the serializer to complete the build outputs.""" build = self.context['build'] request = self.context['request'] @@ -481,9 +455,7 @@ class BuildCancelSerializer(serializers.Serializer): class BuildCompleteSerializer(serializers.Serializer): - """ - DRF serializer for marking a BuildOrder as complete - """ + """DRF serializer for marking a BuildOrder as complete.""" accept_unallocated = serializers.BooleanField( label=_('Accept Unallocated'), @@ -538,14 +510,12 @@ class BuildCompleteSerializer(serializers.Serializer): class BuildUnallocationSerializer(serializers.Serializer): - """ - DRF serializer for unallocating stock from a BuildOrder + """DRF serializer for unallocating stock from a BuildOrder. Allocated stock can be unallocated with a number of filters: - output: Filter against a particular build output (blank = untracked stock) - bom_item: Filter against a particular BOM line item - """ bom_item = serializers.PrimaryKeyRelatedField( @@ -577,11 +547,10 @@ class BuildUnallocationSerializer(serializers.Serializer): return stock_item def save(self): - """ - 'Save' the serializer data. + """Save the serializer data. + This performs the actual unallocation against the build order """ - build = self.context['build'] data = self.validated_data @@ -593,9 +562,7 @@ class BuildUnallocationSerializer(serializers.Serializer): class BuildAllocationItemSerializer(serializers.Serializer): - """ - A serializer for allocating a single stock item against a build order - """ + """A serializer for allocating a single stock item against a build order.""" bom_item = serializers.PrimaryKeyRelatedField( queryset=BomItem.objects.all(), @@ -606,10 +573,7 @@ class BuildAllocationItemSerializer(serializers.Serializer): ) def validate_bom_item(self, bom_item): - """ - Check if the parts match! - """ - + """Check if the parts match!""" build = self.context['build'] # BomItem should point to the same 'part' as the parent build @@ -715,9 +679,7 @@ class BuildAllocationItemSerializer(serializers.Serializer): class BuildAllocationSerializer(serializers.Serializer): - """ - DRF serializer for allocation stock items against a build order - """ + """DRF serializer for allocation stock items against a build order.""" items = BuildAllocationItemSerializer(many=True) @@ -727,10 +689,7 @@ class BuildAllocationSerializer(serializers.Serializer): ] def validate(self, data): - """ - Validation - """ - + """Validation.""" data = super().validate(data) items = data.get('items', []) @@ -770,9 +729,7 @@ class BuildAllocationSerializer(serializers.Serializer): class BuildAutoAllocationSerializer(serializers.Serializer): - """ - DRF serializer for auto allocating stock items against a build order - """ + """DRF serializer for auto allocating stock items against a build order.""" class Meta: fields = [ @@ -827,7 +784,7 @@ class BuildAutoAllocationSerializer(serializers.Serializer): class BuildItemSerializer(InvenTreeModelSerializer): - """ Serializes a BuildItem object """ + """Serializes a BuildItem object.""" bom_part = serializers.IntegerField(source='bom_item.sub_part.pk', read_only=True) part = serializers.IntegerField(source='stock_item.part.pk', read_only=True) @@ -877,9 +834,7 @@ class BuildItemSerializer(InvenTreeModelSerializer): class BuildAttachmentSerializer(InvenTreeAttachmentSerializer): - """ - Serializer for a BuildAttachment - """ + """Serializer for a BuildAttachment.""" class Meta: model = BuildOrderAttachment diff --git a/InvenTree/build/tasks.py b/InvenTree/build/tasks.py index daf231d951..8192e83a43 100644 --- a/InvenTree/build/tasks.py +++ b/InvenTree/build/tasks.py @@ -18,11 +18,10 @@ logger = logging.getLogger('inventree') def check_build_stock(build: build.models.Build): - """ - Check the required stock for a newly created build order, - and send an email out to any subscribed users if stock is low. - """ + """Check the required stock for a newly created build order. + Send an email out to any subscribed users if stock is low. + """ # Do not notify if we are importing data if isImportingData(): return diff --git a/InvenTree/build/test_api.py b/InvenTree/build/test_api.py index 1adf38935e..95fbf9a17b 100644 --- a/InvenTree/build/test_api.py +++ b/InvenTree/build/test_api.py @@ -13,8 +13,8 @@ from InvenTree.api_tester import InvenTreeAPITestCase class TestBuildAPI(InvenTreeAPITestCase): - """ - Series of tests for the Build DRF API + """Series of tests for the Build DRF API. + - Tests for Build API - Tests for BuildItem API """ @@ -33,10 +33,7 @@ class TestBuildAPI(InvenTreeAPITestCase): ] def test_get_build_list(self): - """ - Test that we can retrieve list of build objects - """ - + """Test that we can retrieve list of build objects.""" url = reverse('api-build-list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) @@ -65,7 +62,7 @@ class TestBuildAPI(InvenTreeAPITestCase): self.assertEqual(len(response.data), 0) def test_get_build_item_list(self): - """ Test that we can retrieve list of BuildItem objects """ + """Test that we can retrieve list of BuildItem objects.""" url = reverse('api-build-item-list') response = self.client.get(url, format='json') @@ -77,9 +74,7 @@ class TestBuildAPI(InvenTreeAPITestCase): class BuildAPITest(InvenTreeAPITestCase): - """ - Series of tests for the Build DRF API - """ + """Series of tests for the Build DRF API.""" fixtures = [ 'category', @@ -102,9 +97,7 @@ class BuildAPITest(InvenTreeAPITestCase): class BuildTest(BuildAPITest): - """ - Unit testing for the build complete API endpoint - """ + """Unit testing for the build complete API endpoint.""" def setUp(self): @@ -115,10 +108,7 @@ class BuildTest(BuildAPITest): self.url = reverse('api-build-output-complete', kwargs={'pk': self.build.pk}) def test_invalid(self): - """ - Test with invalid data - """ - + """Test with invalid data.""" # Test with an invalid build ID self.post( reverse('api-build-output-complete', kwargs={'pk': 99999}), @@ -199,10 +189,7 @@ class BuildTest(BuildAPITest): ) def test_complete(self): - """ - Test build order completion - """ - + """Test build order completion.""" # Initially, build should not be able to be completed self.assertFalse(self.build.can_complete) @@ -270,8 +257,7 @@ class BuildTest(BuildAPITest): self.assertTrue(self.build.is_complete) def test_cancel(self): - """ Test that we can cancel a BuildOrder via the API """ - + """Test that we can cancel a BuildOrder via the API.""" bo = Build.objects.get(pk=1) url = reverse('api-build-cancel', kwargs={'pk': bo.pk}) @@ -285,10 +271,7 @@ class BuildTest(BuildAPITest): self.assertEqual(bo.status, BuildStatus.CANCELLED) def test_create_delete_output(self): - """ - Test that we can create and delete build outputs via the API - """ - + """Test that we can create and delete build outputs via the API.""" bo = Build.objects.get(pk=1) n_outputs = bo.output_count @@ -539,15 +522,13 @@ class BuildTest(BuildAPITest): class BuildAllocationTest(BuildAPITest): - """ - Unit tests for allocation of stock items against a build order. + """Unit tests for allocation of stock items against a build order. For this test, we will be using Build ID=1; - This points to Part 100 (see fixture data in part.yaml) - This Part already has a BOM with 4 items (see fixture data in bom.yaml) - There are no BomItem objects yet created for this build - """ def setUp(self): @@ -565,10 +546,7 @@ class BuildAllocationTest(BuildAPITest): self.n = BuildItem.objects.count() def test_build_data(self): - """ - Check that our assumptions about the particular BuildOrder are correct - """ - + """Check that our assumptions about the particular BuildOrder are correct.""" self.assertEqual(self.build.part.pk, 100) # There should be 4x BOM items we can use @@ -578,26 +556,17 @@ class BuildAllocationTest(BuildAPITest): self.assertEqual(self.build.allocated_stock.count(), 0) def test_get(self): - """ - A GET request to the endpoint should return an error - """ - + """A GET request to the endpoint should return an error.""" self.get(self.url, expected_code=405) def test_options(self): - """ - An OPTIONS request to the endpoint should return information about the endpoint - """ - + """An OPTIONS request to the endpoint should return information about the endpoint.""" response = self.options(self.url, expected_code=200) self.assertIn("API endpoint to allocate stock items to a build order", str(response.data)) def test_empty(self): - """ - Test without any POST data - """ - + """Test without any POST data.""" # Initially test with an empty data set data = self.post(self.url, {}, expected_code=400).data @@ -618,10 +587,7 @@ class BuildAllocationTest(BuildAPITest): self.assertEqual(self.n, BuildItem.objects.count()) def test_missing(self): - """ - Test with missing data - """ - + """Test with missing data.""" # Missing quantity data = self.post( self.url, @@ -674,10 +640,7 @@ class BuildAllocationTest(BuildAPITest): self.assertEqual(self.n, BuildItem.objects.count()) def test_invalid_bom_item(self): - """ - Test by passing an invalid BOM item - """ - + """Test by passing an invalid BOM item.""" data = self.post( self.url, { @@ -695,11 +658,10 @@ class BuildAllocationTest(BuildAPITest): self.assertIn('must point to the same part', str(data)) def test_valid_data(self): - """ - Test with valid data. + """Test with valid data. + This should result in creation of a new BuildItem object """ - self.post( self.url, { @@ -725,17 +687,12 @@ class BuildAllocationTest(BuildAPITest): class BuildListTest(BuildAPITest): - """ - Tests for the BuildOrder LIST API - """ + """Tests for the BuildOrder LIST API.""" url = reverse('api-build-list') def test_get_all_builds(self): - """ - Retrieve *all* builds via the API - """ - + """Retrieve *all* builds via the API.""" builds = self.get(self.url) self.assertEqual(len(builds.data), 5) @@ -753,10 +710,7 @@ class BuildListTest(BuildAPITest): self.assertEqual(len(builds.data), 0) def test_overdue(self): - """ - Create a new build, in the past - """ - + """Create a new build, in the past.""" in_the_past = datetime.now().date() - timedelta(days=50) part = Part.objects.get(pk=50) @@ -776,10 +730,7 @@ class BuildListTest(BuildAPITest): self.assertEqual(len(builds), 1) def test_sub_builds(self): - """ - Test the build / sub-build relationship - """ - + """Test the build / sub-build relationship.""" parent = Build.objects.get(pk=5) part = Part.objects.get(pk=50) diff --git a/InvenTree/build/test_build.py b/InvenTree/build/test_build.py index e2cda00ec9..a7a5f7106b 100644 --- a/InvenTree/build/test_build.py +++ b/InvenTree/build/test_build.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from django.test import TestCase from django.core.exceptions import ValidationError @@ -13,13 +11,10 @@ from stock.models import StockItem class BuildTestBase(TestCase): - """ - Run some tests to ensure that the Build model is working properly. - """ + """Run some tests to ensure that the Build model is working properly.""" def setUp(self): - """ - Initialize data to use for these tests. + """Initialize data to use for these tests. The base Part 'assembly' has a BOM consisting of three parts: @@ -31,9 +26,7 @@ class BuildTestBase(TestCase): - 3 x output_1 - 7 x output_2 - """ - # Create a base "Part" self.assembly = Part.objects.create( name="An assembled part", @@ -122,10 +115,7 @@ class BuildTestBase(TestCase): class BuildTest(BuildTestBase): def test_ref_int(self): - """ - Test the "integer reference" field used for natural sorting - """ - + """Test the "integer reference" field used for natural sorting.""" for ii in range(10): build = Build( reference=f"{ii}_abcde", @@ -204,14 +194,12 @@ class BuildTest(BuildTestBase): ) def allocate_stock(self, output, allocations): - """ - Allocate stock to this build, against a particular output + """Allocate stock to this build, against a particular output. Args: output - StockItem object (or None) allocations - Map of {StockItem: quantity} """ - for item, quantity in allocations.items(): BuildItem.objects.create( build=self.build, @@ -221,10 +209,7 @@ class BuildTest(BuildTestBase): ) def test_partial_allocation(self): - """ - Test partial allocation of stock - """ - + """Test partial allocation of stock.""" # Fully allocate tracked stock against build output 1 self.allocate_stock( self.output_1, @@ -296,10 +281,7 @@ class BuildTest(BuildTestBase): self.assertTrue(self.build.are_untracked_parts_allocated()) def test_cancel(self): - """ - Test cancellation of the build - """ - + """Test cancellation of the build.""" # TODO """ @@ -311,10 +293,7 @@ class BuildTest(BuildTestBase): pass def test_complete(self): - """ - Test completion of a build output - """ - + """Test completion of a build output.""" self.stock_1_1.quantity = 1000 self.stock_1_1.save() @@ -387,9 +366,7 @@ class BuildTest(BuildTestBase): class AutoAllocationTests(BuildTestBase): - """ - Tests for auto allocating stock against a build order - """ + """Tests for auto allocating stock against a build order.""" def setUp(self): @@ -413,8 +390,7 @@ class AutoAllocationTests(BuildTestBase): ) def test_auto_allocate(self): - """ - Run the 'auto-allocate' function. What do we expect to happen? + """Run the 'auto-allocate' function. What do we expect to happen? There are two "untracked" parts: - sub_part_1 (quantity 5 per BOM = 50 required total) / 103 in stock (2 items) @@ -422,7 +398,6 @@ class AutoAllocationTests(BuildTestBase): A "fully auto" allocation should allocate *all* of these stock items to the build """ - # No build item allocations have been made against the build self.assertEqual(self.build.allocated_stock.count(), 0) @@ -476,10 +451,7 @@ class AutoAllocationTests(BuildTestBase): self.assertTrue(self.build.is_bom_item_allocated(self.bom_item_2)) def test_fully_auto(self): - """ - We should be able to auto-allocate against a build in a single go - """ - + """We should be able to auto-allocate against a build in a single go.""" self.build.auto_allocate_stock( interchangeable=True, substitutes=True diff --git a/InvenTree/build/test_migrations.py b/InvenTree/build/test_migrations.py index 1e95cfb54e..831d1fda67 100644 --- a/InvenTree/build/test_migrations.py +++ b/InvenTree/build/test_migrations.py @@ -1,6 +1,4 @@ -""" -Tests for the build model database migrations -""" +"""Tests for the build model database migrations.""" from django_test_migrations.contrib.unittest_case import MigratorTestCase @@ -8,18 +6,13 @@ from InvenTree import helpers class TestForwardMigrations(MigratorTestCase): - """ - Test entire schema migration sequence for the build app - """ + """Test entire schema migration sequence for the build app.""" migrate_from = ('build', helpers.getOldestMigrationFile('build')) migrate_to = ('build', helpers.getNewestMigrationFile('build')) def prepare(self): - """ - Create initial data! - """ - + """Create initial data!""" Part = self.old_state.apps.get_model('part', 'part') buildable_part = Part.objects.create( @@ -63,18 +56,13 @@ class TestForwardMigrations(MigratorTestCase): class TestReferenceMigration(MigratorTestCase): - """ - Test custom migration which adds 'reference' field to Build model - """ + """Test custom migration which adds 'reference' field to Build model.""" migrate_from = ('build', helpers.getOldestMigrationFile('build')) migrate_to = ('build', '0018_build_reference') def prepare(self): - """ - Create some builds - """ - + """Create some builds.""" Part = self.old_state.apps.get_model('part', 'part') part = Part.objects.create( diff --git a/InvenTree/build/tests.py b/InvenTree/build/tests.py index 8bd7553a52..89534fae19 100644 --- a/InvenTree/build/tests.py +++ b/InvenTree/build/tests.py @@ -48,10 +48,7 @@ class BuildTestSimple(InvenTreeTestCase): self.assertEqual(b2.status, BuildStatus.COMPLETE) def test_overdue(self): - """ - Test overdue status functionality - """ - + """Test overdue status functionality.""" today = datetime.now().date() build = Build.objects.get(pk=1) @@ -77,8 +74,7 @@ class BuildTestSimple(InvenTreeTestCase): pass def test_cancel_build(self): - """ Test build cancellation function """ - + """Test build cancellation function.""" build = Build.objects.get(id=1) self.assertEqual(build.status, BuildStatus.PENDING) @@ -89,7 +85,7 @@ class BuildTestSimple(InvenTreeTestCase): class TestBuildViews(InvenTreeTestCase): - """ Tests for Build app views """ + """Tests for Build app views.""" fixtures = [ 'category', @@ -118,14 +114,12 @@ class TestBuildViews(InvenTreeTestCase): ) def test_build_index(self): - """ test build index view """ - + """Test build index view.""" response = self.client.get(reverse('build-index')) self.assertEqual(response.status_code, 200) def test_build_detail(self): - """ Test the detail view for a Build object """ - + """Test the detail view for a Build object.""" pk = 1 response = self.client.get(reverse('build-detail', args=(pk,))) diff --git a/InvenTree/build/urls.py b/InvenTree/build/urls.py index 0788a1de37..b524df5627 100644 --- a/InvenTree/build/urls.py +++ b/InvenTree/build/urls.py @@ -1,6 +1,4 @@ -""" -URL lookup for Build app -""" +"""URL lookup for Build app.""" from django.urls import include, re_path diff --git a/InvenTree/build/views.py b/InvenTree/build/views.py index 57d8f8bd37..87790b04ac 100644 --- a/InvenTree/build/views.py +++ b/InvenTree/build/views.py @@ -1,6 +1,4 @@ -""" -Django views for interacting with Build objects -""" +"""Django views for interacting with Build objects.""" from django.utils.translation import gettext_lazy as _ from django.views.generic import DetailView, ListView @@ -15,15 +13,13 @@ from plugin.views import InvenTreePluginViewMixin class BuildIndex(InvenTreeRoleMixin, ListView): - """ - View for displaying list of Builds - """ + """View for displaying list of Builds.""" model = Build template_name = 'build/index.html' context_object_name = 'builds' def get_queryset(self): - """ Return all Build objects (order by date, newest first) """ + """Return all Build objects (order by date, newest first)""" return Build.objects.order_by('status', '-completion_date') def get_context_data(self, **kwargs): @@ -41,9 +37,7 @@ class BuildIndex(InvenTreeRoleMixin, ListView): class BuildDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """ - Detail view of a single Build object. - """ + """Detail view of a single Build object.""" model = Build template_name = 'build/detail.html' @@ -71,9 +65,7 @@ class BuildDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): class BuildDelete(AjaxDeleteView): - """ - View to delete a build - """ + """View to delete a build.""" model = Build ajax_template_name = 'build/delete_build.html' diff --git a/InvenTree/common/admin.py b/InvenTree/common/admin.py index f9ae7b557f..fa09e5df80 100644 --- a/InvenTree/common/admin.py +++ b/InvenTree/common/admin.py @@ -10,10 +10,7 @@ class SettingsAdmin(ImportExportModelAdmin): list_display = ('key', 'value') def get_readonly_fields(self, request, obj=None): # pragma: no cover - """ - Prevent the 'key' field being edited once the setting is created - """ - + """Prevent the 'key' field being edited once the setting is created.""" if obj: return ['key'] else: @@ -25,10 +22,7 @@ class UserSettingsAdmin(ImportExportModelAdmin): list_display = ('key', 'value', 'user', ) def get_readonly_fields(self, request, obj=None): # pragma: no cover - """ - Prevent the 'key' field being edited once the setting is created - """ - + """Prevent the 'key' field being edited once the setting is created.""" if obj: return ['key'] else: diff --git a/InvenTree/common/api.py b/InvenTree/common/api.py index d805626da7..cb3b05130f 100644 --- a/InvenTree/common/api.py +++ b/InvenTree/common/api.py @@ -1,6 +1,4 @@ -""" -Provides a JSON API for common components. -""" +"""Provides a JSON API for common components.""" import json @@ -24,9 +22,7 @@ from plugin.serializers import NotificationUserSettingSerializer class CsrfExemptMixin(object): - """ - Exempts the view from CSRF requirements. - """ + """Exempts the view from CSRF requirements.""" @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): @@ -34,9 +30,7 @@ class CsrfExemptMixin(object): class WebhookView(CsrfExemptMixin, APIView): - """ - Endpoint for receiving webhooks. - """ + """Endpoint for receiving webhooks.""" authentication_classes = [] permission_classes = [] model_class = common.models.WebhookEndpoint @@ -120,24 +114,17 @@ class SettingsList(generics.ListAPIView): class GlobalSettingsList(SettingsList): - """ - API endpoint for accessing a list of global settings objects - """ + """API endpoint for accessing a list of global settings objects.""" queryset = common.models.InvenTreeSetting.objects.all() serializer_class = common.serializers.GlobalSettingsSerializer class GlobalSettingsPermissions(permissions.BasePermission): - """ - Special permission class to determine if the user is "staff" - """ + """Special permission class to determine if the user is "staff".""" def has_permission(self, request, view): - """ - Check that the requesting user is 'admin' - """ - + """Check that the requesting user is 'admin'.""" try: user = request.user @@ -152,8 +139,7 @@ class GlobalSettingsPermissions(permissions.BasePermission): class GlobalSettingsDetail(generics.RetrieveUpdateAPIView): - """ - Detail view for an individual "global setting" object. + """Detail view for an individual "global setting" object. - User must have 'staff' status to view / edit """ @@ -163,10 +149,7 @@ class GlobalSettingsDetail(generics.RetrieveUpdateAPIView): serializer_class = common.serializers.GlobalSettingsSerializer def get_object(self): - """ - Attempt to find a global setting object with the provided key. - """ - + """Attempt to find a global setting object with the provided key.""" key = self.kwargs['key'] if key not in common.models.InvenTreeSetting.SETTINGS.keys(): @@ -181,18 +164,13 @@ class GlobalSettingsDetail(generics.RetrieveUpdateAPIView): class UserSettingsList(SettingsList): - """ - API endpoint for accessing a list of user settings objects - """ + """API endpoint for accessing a list of user settings objects.""" queryset = common.models.InvenTreeUserSetting.objects.all() serializer_class = common.serializers.UserSettingsSerializer def filter_queryset(self, queryset): - """ - Only list settings which apply to the current user - """ - + """Only list settings which apply to the current user.""" try: user = self.request.user except AttributeError: # pragma: no cover @@ -206,9 +184,7 @@ class UserSettingsList(SettingsList): class UserSettingsPermissions(permissions.BasePermission): - """ - Special permission class to determine if the user can view / edit a particular setting - """ + """Special permission class to determine if the user can view / edit a particular setting.""" def has_object_permission(self, request, view, obj): @@ -221,8 +197,7 @@ class UserSettingsPermissions(permissions.BasePermission): class UserSettingsDetail(generics.RetrieveUpdateAPIView): - """ - Detail view for an individual "user setting" object + """Detail view for an individual "user setting" object. - User can only view / edit settings their own settings objects """ @@ -232,10 +207,7 @@ class UserSettingsDetail(generics.RetrieveUpdateAPIView): serializer_class = common.serializers.UserSettingsSerializer def get_object(self): - """ - Attempt to find a user setting object with the provided key. - """ - + """Attempt to find a user setting object with the provided key.""" key = self.kwargs['key'] if key not in common.models.InvenTreeUserSetting.SETTINGS.keys(): @@ -249,18 +221,13 @@ class UserSettingsDetail(generics.RetrieveUpdateAPIView): class NotificationUserSettingsList(SettingsList): - """ - API endpoint for accessing a list of notification user settings objects - """ + """API endpoint for accessing a list of notification user settings objects.""" queryset = NotificationUserSetting.objects.all() serializer_class = NotificationUserSettingSerializer def filter_queryset(self, queryset): - """ - Only list settings which apply to the current user - """ - + """Only list settings which apply to the current user.""" try: user = self.request.user except AttributeError: @@ -272,8 +239,7 @@ class NotificationUserSettingsList(SettingsList): class NotificationUserSettingsDetail(generics.RetrieveUpdateAPIView): - """ - Detail view for an individual "notification user setting" object + """Detail view for an individual "notification user setting" object. - User can only view / edit settings their own settings objects """ @@ -313,10 +279,7 @@ class NotificationList(generics.ListAPIView): ] def filter_queryset(self, queryset): - """ - Only list notifications which apply to the current user - """ - + """Only list notifications which apply to the current user.""" try: user = self.request.user except AttributeError: @@ -328,8 +291,7 @@ class NotificationList(generics.ListAPIView): class NotificationDetail(generics.RetrieveUpdateDestroyAPIView): - """ - Detail view for an individual notification object + """Detail view for an individual notification object. - User can only view / delete their own notification objects """ @@ -342,9 +304,7 @@ class NotificationDetail(generics.RetrieveUpdateDestroyAPIView): class NotificationReadEdit(generics.CreateAPIView): - """ - general API endpoint to manipulate read state of a notification - """ + """General API endpoint to manipulate read state of a notification.""" queryset = common.models.NotificationMessage.objects.all() serializer_class = common.serializers.NotificationReadSerializer @@ -369,23 +329,17 @@ class NotificationReadEdit(generics.CreateAPIView): class NotificationRead(NotificationReadEdit): - """ - API endpoint to mark a notification as read. - """ + """API endpoint to mark a notification as read.""" target = True class NotificationUnread(NotificationReadEdit): - """ - API endpoint to mark a notification as unread. - """ + """API endpoint to mark a notification as unread.""" target = False class NotificationReadAll(generics.RetrieveAPIView): - """ - API endpoint to mark all notifications as read. - """ + """API endpoint to mark all notifications as read.""" queryset = common.models.NotificationMessage.objects.all() diff --git a/InvenTree/common/apps.py b/InvenTree/common/apps.py index 629b5179e6..8ab31fcdf1 100644 --- a/InvenTree/common/apps.py +++ b/InvenTree/common/apps.py @@ -15,10 +15,7 @@ class CommonConfig(AppConfig): self.clear_restart_flag() def clear_restart_flag(self): - """ - Clear the SERVER_RESTART_REQUIRED setting - """ - + """Clear the SERVER_RESTART_REQUIRED setting.""" try: import common.models diff --git a/InvenTree/common/files.py b/InvenTree/common/files.py index 704d02a681..a1817747aa 100644 --- a/InvenTree/common/files.py +++ b/InvenTree/common/files.py @@ -1,6 +1,4 @@ -""" -Files management tools. -""" +"""Files management tools.""" import os @@ -12,7 +10,7 @@ from rapidfuzz import fuzz class FileManager: - """ Class for managing an uploaded file """ + """Class for managing an uploaded file.""" name = '' @@ -32,8 +30,7 @@ class FileManager: HEADERS = [] def __init__(self, file, name=None): - """ Initialize the FileManager class with a user-uploaded file object """ - + """Initialize the FileManager class with a user-uploaded file object.""" # Set name if name: self.name = name @@ -46,8 +43,7 @@ class FileManager: @classmethod def validate(cls, file): - """ Validate file extension and data """ - + """Validate file extension and data.""" cleaned_data = None ext = os.path.splitext(file.name)[-1].lower().replace('.', '') @@ -79,21 +75,15 @@ class FileManager: return cleaned_data def process(self, file): - """ Process file """ - + """Process file.""" self.data = self.__class__.validate(file) def update_headers(self): - """ Update headers """ - + """Update headers.""" self.HEADERS = self.REQUIRED_HEADERS + self.ITEM_MATCH_HEADERS + self.OPTIONAL_MATCH_HEADERS + self.OPTIONAL_HEADERS def setup(self): - """ - Setup headers - should be overriden in usage to set the Different Headers - """ - + """Setup headers should be overriden in usage to set the Different Headers.""" if not self.name: return @@ -101,14 +91,12 @@ class FileManager: self.update_headers() def guess_header(self, header, threshold=80): - """ - Try to match a header (from the file) to a list of known headers + """Try to match a header (from the file) to a list of known headers. Args: header - Header name to look for threshold - Match threshold for fuzzy search """ - # Replace null values with empty string if header is None: header = '' @@ -143,7 +131,7 @@ class FileManager: return None def columns(self): - """ Return a list of headers for the thingy """ + """Return a list of headers for the thingy.""" headers = [] for header in self.data.headers: @@ -176,15 +164,14 @@ class FileManager: return len(self.data.headers) def row_count(self): - """ Return the number of rows in the file. """ - + """Return the number of rows in the file.""" if self.data is None: return 0 return len(self.data) def rows(self): - """ Return a list of all rows """ + """Return a list of all rows.""" rows = [] for i in range(self.row_count()): @@ -221,15 +208,14 @@ class FileManager: return rows def get_row_data(self, index): - """ Retrieve row data at a particular index """ + """Retrieve row data at a particular index.""" if self.data is None or index >= len(self.data): return None return self.data[index] def get_row_dict(self, index): - """ Retrieve a dict object representing the data row at a particular offset """ - + """Retrieve a dict object representing the data row at a particular offset.""" if self.data is None or index >= len(self.data): return None diff --git a/InvenTree/common/forms.py b/InvenTree/common/forms.py index 7fcdf8535c..9d0f426cbf 100644 --- a/InvenTree/common/forms.py +++ b/InvenTree/common/forms.py @@ -1,6 +1,4 @@ -""" -Django forms for interacting with common objects -""" +"""Django forms for interacting with common objects.""" from django import forms from django.utils.translation import gettext as _ @@ -12,9 +10,7 @@ from .models import InvenTreeSetting class SettingEditForm(HelperForm): - """ - Form for creating / editing a settings object - """ + """Form for creating / editing a settings object.""" class Meta: model = InvenTreeSetting @@ -25,7 +21,7 @@ class SettingEditForm(HelperForm): class UploadFileForm(forms.Form): - """ Step 1 of FileManagementFormView """ + """Step 1 of FileManagementFormView.""" file = forms.FileField( label=_('File'), @@ -33,8 +29,7 @@ class UploadFileForm(forms.Form): ) def __init__(self, *args, **kwargs): - """ Update label and help_text """ - + """Update label and help_text.""" # Get file name name = None if 'name' in kwargs: @@ -48,11 +43,10 @@ class UploadFileForm(forms.Form): self.fields['file'].help_text = _(f'Select {name} file to upload') def clean_file(self): - """ - Run tabular file validation. - If anything is wrong with the file, it will raise ValidationError - """ + """Run tabular file validation. + If anything is wrong with the file, it will raise ValidationError + """ file = self.cleaned_data['file'] # Validate file using FileManager class - will perform initial data validation @@ -63,7 +57,7 @@ class UploadFileForm(forms.Form): class MatchFieldForm(forms.Form): - """ Step 2 of FileManagementFormView """ + """Step 2 of FileManagementFormView.""" def __init__(self, *args, **kwargs): @@ -96,7 +90,7 @@ class MatchFieldForm(forms.Form): class MatchItemForm(forms.Form): - """ Step 3 of FileManagementFormView """ + """Step 3 of FileManagementFormView.""" def __init__(self, *args, **kwargs): @@ -194,6 +188,5 @@ class MatchItemForm(forms.Form): ) def get_special_field(self, col_guess, row, file_manager): - """ Function to be overriden in inherited forms to add specific form settings """ - + """Function to be overriden in inherited forms to add specific form settings.""" return None diff --git a/InvenTree/common/models.py b/InvenTree/common/models.py index 79c449002e..10610d1b48 100644 --- a/InvenTree/common/models.py +++ b/InvenTree/common/models.py @@ -1,5 +1,5 @@ -""" -Common database model definitions. +"""Common database model definitions. + These models are 'generic' and do not fit a particular business logic object. """ @@ -55,10 +55,7 @@ class EmptyURLValidator(URLValidator): class BaseInvenTreeSetting(models.Model): - """ - An base InvenTreeSetting object is a key:value pair used for storing - single values (e.g. one-off settings values). - """ + """An base InvenTreeSetting object is a key:value pair used for storing single values (e.g. one-off settings values).""" SETTINGS = {} @@ -66,10 +63,7 @@ class BaseInvenTreeSetting(models.Model): abstract = True def save(self, *args, **kwargs): - """ - Enforce validation and clean before saving - """ - + """Enforce validation and clean before saving.""" self.key = str(self.key).upper() self.clean(**kwargs) @@ -79,14 +73,12 @@ class BaseInvenTreeSetting(models.Model): @classmethod def allValues(cls, user=None, exclude_hidden=False): - """ - Return a dict of "all" defined global settings. + """Return a dict of "all" defined global settings. This performs a single database lookup, and then any settings which are not *in* the database are assigned their default values """ - results = cls.objects.all() # Optionally filter by user @@ -131,28 +123,23 @@ class BaseInvenTreeSetting(models.Model): return settings def get_kwargs(self): - """ - Construct kwargs for doing class-based settings lookup, - depending on *which* class we are. + """Construct kwargs for doing class-based settings lookup, depending on *which* class we are. This is necessary to abtract the settings object from the implementing class (e.g plugins) Subclasses should override this function to ensure the kwargs are correctly set. """ - return {} @classmethod def get_setting_definition(cls, key, **kwargs): - """ - Return the 'definition' of a particular settings value, as a dict object. + """Return the 'definition' of a particular settings value, as a dict object. - The 'settings' dict can be passed as a kwarg - If not passed, look for cls.SETTINGS - Returns an empty dict if the key is not found """ - settings = kwargs.get('settings', cls.SETTINGS) key = str(key).strip().upper() @@ -164,69 +151,56 @@ class BaseInvenTreeSetting(models.Model): @classmethod def get_setting_name(cls, key, **kwargs): - """ - Return the name of a particular setting. + """Return the name of a particular setting. If it does not exist, return an empty string. """ - setting = cls.get_setting_definition(key, **kwargs) return setting.get('name', '') @classmethod def get_setting_description(cls, key, **kwargs): - """ - Return the description for a particular setting. + """Return the description for a particular setting. If it does not exist, return an empty string. """ - setting = cls.get_setting_definition(key, **kwargs) return setting.get('description', '') @classmethod def get_setting_units(cls, key, **kwargs): - """ - Return the units for a particular setting. + """Return the units for a particular setting. If it does not exist, return an empty string. """ - setting = cls.get_setting_definition(key, **kwargs) return setting.get('units', '') @classmethod def get_setting_validator(cls, key, **kwargs): - """ - Return the validator for a particular setting. + """Return the validator for a particular setting. If it does not exist, return None """ - setting = cls.get_setting_definition(key, **kwargs) return setting.get('validator', None) @classmethod def get_setting_default(cls, key, **kwargs): - """ - Return the default value for a particular setting. + """Return the default value for a particular setting. If it does not exist, return an empty string """ - setting = cls.get_setting_definition(key, **kwargs) return setting.get('default', '') @classmethod def get_setting_choices(cls, key, **kwargs): - """ - Return the validator choices available for a particular setting. - """ - + """Return the validator choices available for a particular setting.""" setting = cls.get_setting_definition(key, **kwargs) choices = setting.get('choices', None) @@ -239,13 +213,11 @@ class BaseInvenTreeSetting(models.Model): @classmethod def get_setting_object(cls, key, **kwargs): - """ - Return an InvenTreeSetting object matching the given key. + """Return an InvenTreeSetting object matching the given key. - Key is case-insensitive - Returns None if no match is made """ - key = str(key).strip().upper() settings = cls.objects.all() @@ -311,11 +283,10 @@ class BaseInvenTreeSetting(models.Model): @classmethod def get_setting(cls, key, backup_value=None, **kwargs): - """ - Get the value of a particular setting. + """Get the value of a particular setting. + If it does not exist, return the backup value (default = None) """ - # If no backup value is specified, atttempt to retrieve a "default" value if backup_value is None: backup_value = cls.get_setting_default(key, **kwargs) @@ -343,9 +314,7 @@ class BaseInvenTreeSetting(models.Model): @classmethod def set_setting(cls, key, value, change_user, create=True, **kwargs): - """ - Set the value of a particular setting. - If it does not exist, option to create it. + """Set the value of a particular setting. If it does not exist, option to create it. Args: key: settings key @@ -353,7 +322,6 @@ class BaseInvenTreeSetting(models.Model): change_user: User object (must be staff member to update a core setting) create: If True, create a new setting if the specified key does not exist. """ - if change_user is not None and not change_user.is_staff: return @@ -412,11 +380,7 @@ class BaseInvenTreeSetting(models.Model): return self.__class__.get_setting_units(self.key, **self.get_kwargs()) def clean(self, **kwargs): - """ - If a validator (or multiple validators) are defined for a particular setting key, - run them against the 'value' field. - """ - + """If a validator (or multiple validators) are defined for a particular setting key, run them against the 'value' field.""" super().clean() # Encode as native values @@ -437,10 +401,7 @@ class BaseInvenTreeSetting(models.Model): raise ValidationError(_("Chosen value is not a valid option")) def run_validator(self, validator): - """ - Run a validator against the 'value' field for this InvenTreeSetting object. - """ - + """Run a validator against the 'value' field for this InvenTreeSetting object.""" if validator is None: return @@ -485,15 +446,11 @@ class BaseInvenTreeSetting(models.Model): validator(value) def validate_unique(self, exclude=None, **kwargs): - """ - Ensure that the key:value pair is unique. - In addition to the base validators, this ensures that the 'key' - is unique, using a case-insensitive comparison. + """Ensure that the key:value pair is unique. In addition to the base validators, this ensures that the 'key' is unique, using a case-insensitive comparison. Note that sub-classes (UserSetting, PluginSetting) use other filters to determine if the setting is 'unique' or not """ - super().validate_unique(exclude) filters = { @@ -520,17 +477,11 @@ class BaseInvenTreeSetting(models.Model): pass def choices(self): - """ - Return the available choices for this setting (or None if no choices are defined) - """ - + """Return the available choices for this setting (or None if no choices are defined)""" return self.__class__.get_setting_choices(self.key, **self.get_kwargs()) def valid_options(self): - """ - Return a list of valid options for this setting - """ - + """Return a list of valid options for this setting.""" choices = self.choices() if not choices: @@ -539,21 +490,17 @@ class BaseInvenTreeSetting(models.Model): return [opt[0] for opt in choices] def is_choice(self): - """ - Check if this setting is a "choice" field - """ - + """Check if this setting is a "choice" field.""" return self.__class__.get_setting_choices(self.key, **self.get_kwargs()) is not None def as_choice(self): - """ - Render this setting as the "display" value of a choice field, - e.g. if the choices are: + """Render this setting as the "display" value of a choice field. + + E.g. if the choices are: [('A4', 'A4 paper'), ('A3', 'A3 paper')], and the value is 'A4', then display 'A4 paper' """ - choices = self.get_setting_choices(self.key, **self.get_kwargs()) if not choices: @@ -566,30 +513,23 @@ class BaseInvenTreeSetting(models.Model): return self.value def is_model(self): - """ - Check if this setting references a model instance in the database - """ - + """Check if this setting references a model instance in the database.""" return self.model_name() is not None def model_name(self): - """ - Return the model name associated with this setting - """ - + """Return the model name associated with this setting.""" setting = self.get_setting_definition(self.key, **self.get_kwargs()) return setting.get('model', None) def model_class(self): - """ - Return the model class associated with this setting, if (and only if): + """Return the model class associated with this setting. + If (and only if): - It has a defined 'model' parameter - The 'model' parameter is of the form app.model - The 'model' parameter has matches a known app model """ - model_name = self.model_name() if not model_name: @@ -617,11 +557,7 @@ class BaseInvenTreeSetting(models.Model): return model def api_url(self): - """ - Return the API url associated with the linked model, - if provided, and valid! - """ - + """Return the API url associated with the linked model, if provided, and valid!""" model_class = self.model_class() if model_class: @@ -634,28 +570,20 @@ class BaseInvenTreeSetting(models.Model): return None def is_bool(self): - """ - Check if this setting is required to be a boolean value - """ - + """Check if this setting is required to be a boolean value.""" validator = self.__class__.get_setting_validator(self.key, **self.get_kwargs()) return self.__class__.validator_is_bool(validator) def as_bool(self): - """ - Return the value of this setting converted to a boolean value. + """Return the value of this setting converted to a boolean value. Warning: Only use on values where is_bool evaluates to true! """ - return InvenTree.helpers.str2bool(self.value) def setting_type(self): - """ - Return the field type identifier for this setting object - """ - + """Return the field type identifier for this setting object.""" if self.is_bool(): return 'boolean' @@ -682,10 +610,7 @@ class BaseInvenTreeSetting(models.Model): return False def is_int(self,): - """ - Check if the setting is required to be an integer value: - """ - + """Check if the setting is required to be an integer value.""" validator = self.__class__.get_setting_validator(self.key, **self.get_kwargs()) return self.__class__.validator_is_int(validator) @@ -704,12 +629,10 @@ class BaseInvenTreeSetting(models.Model): return False def as_int(self): - """ - Return the value of this setting converted to a boolean value. + """Return the value of this setting converted to a boolean value. If an error occurs, return the default value """ - try: value = int(self.value) except (ValueError, TypeError): @@ -719,10 +642,7 @@ class BaseInvenTreeSetting(models.Model): @classmethod def is_protected(cls, key, **kwargs): - """ - Check if the setting value is protected - """ - + """Check if the setting value is protected.""" setting = cls.get_setting_definition(key, **kwargs) return setting.get('protected', False) @@ -733,27 +653,22 @@ class BaseInvenTreeSetting(models.Model): def settings_group_options(): - """ - Build up group tuple for settings based on your choices - """ + """Build up group tuple for settings based on your choices.""" return [('', _('No group')), *[(str(a.id), str(a)) for a in Group.objects.all()]] class InvenTreeSetting(BaseInvenTreeSetting): - """ - An InvenTreeSetting object is a key:value pair used for storing - single values (e.g. one-off settings values). + """An InvenTreeSetting object is a key:value pair used for storing single values (e.g. one-off settings values). The class provides a way of retrieving the value for a particular key, even if that key does not exist. """ def save(self, *args, **kwargs): - """ - When saving a global setting, check to see if it requires a server restart. + """When saving a global setting, check to see if it requires a server restart. + If so, set the "SERVER_RESTART_REQUIRED" setting to True """ - super().save() if self.requires_restart(): @@ -1246,18 +1161,11 @@ class InvenTreeSetting(BaseInvenTreeSetting): ) def to_native_value(self): - """ - Return the "pythonic" value, - e.g. convert "True" to True, and "1" to 1 - """ - + """Return the "pythonic" value, e.g. convert "True" to True, and "1" to 1.""" return self.__class__.get_setting(self.key) def requires_restart(self): - """ - Return True if this setting requires a server restart after changing - """ - + """Return True if this setting requires a server restart after changing.""" options = InvenTreeSetting.SETTINGS.get(self.key, None) if options: @@ -1267,9 +1175,7 @@ class InvenTreeSetting(BaseInvenTreeSetting): class InvenTreeUserSetting(BaseInvenTreeSetting): - """ - An InvenTreeSetting object with a usercontext - """ + """An InvenTreeSetting object with a usercontext.""" SETTINGS = { 'HOMEPAGE_PART_STARRED': { @@ -1576,28 +1482,18 @@ class InvenTreeUserSetting(BaseInvenTreeSetting): return super().validate_unique(exclude=exclude, user=self.user) def to_native_value(self): - """ - Return the "pythonic" value, - e.g. convert "True" to True, and "1" to 1 - """ - + """Return the "pythonic" value, e.g. convert "True" to True, and "1" to 1.""" return self.__class__.get_setting(self.key, user=self.user) def get_kwargs(self): - """ - Explicit kwargs required to uniquely identify a particular setting object, - in addition to the 'key' parameter - """ - + """Explicit kwargs required to uniquely identify a particular setting object, in addition to the 'key' parameter.""" return { 'user': self.user, } class PriceBreak(models.Model): - """ - Represents a PriceBreak model - """ + """Represents a PriceBreak model.""" class Meta: abstract = True @@ -1620,13 +1516,11 @@ class PriceBreak(models.Model): ) def convert_to(self, currency_code): - """ - Convert the unit-price at this price break to the specified currency code. + """Convert the unit-price at this price break to the specified currency code. Args: currency_code - The currency code to convert to (e.g "USD" or "AUD") """ - try: converted = convert_money(self.price, currency_code) except MissingRate: @@ -1637,7 +1531,7 @@ class PriceBreak(models.Model): def get_price(instance, quantity, moq=True, multiples=True, currency=None, break_name: str = 'price_breaks'): - """ Calculate the price based on quantity price breaks. + """Calculate the price based on quantity price breaks. - Don't forget to add in flat-fee cost (base_cost field) - If MOQ (minimum order quantity) is required, bump quantity @@ -1707,7 +1601,7 @@ def get_price(instance, quantity, moq=True, multiples=True, currency=None, break class ColorTheme(models.Model): - """ Color Theme Setting """ + """Color Theme Setting.""" name = models.CharField(max_length=20, default='', blank=True) @@ -1717,7 +1611,7 @@ class ColorTheme(models.Model): @classmethod def get_color_themes_choices(cls): - """ Get all color themes from static folder """ + """Get all color themes from static folder.""" if settings.TESTING and not os.path.exists(settings.STATIC_COLOR_THEMES_DIR): logger.error('Theme directory does not exsist') return [] @@ -1736,7 +1630,7 @@ class ColorTheme(models.Model): @classmethod def is_valid_choice(cls, user_color_theme): - """ Check if color theme is valid choice """ + """Check if color theme is valid choice.""" try: user_color_theme_name = user_color_theme.name except AttributeError: @@ -1756,7 +1650,7 @@ class VerificationMethod: class WebhookEndpoint(models.Model): - """ Defines a Webhook entdpoint + """Defines a Webhook entdpoint. Attributes: endpoint_id: Path to the webhook, @@ -1868,7 +1762,7 @@ class WebhookEndpoint(models.Model): class WebhookMessage(models.Model): - """ Defines a webhook message + """Defines a webhook message. Attributes: message_id: Unique identifier for this message, @@ -1925,8 +1819,7 @@ class WebhookMessage(models.Model): class NotificationEntry(models.Model): - """ - A NotificationEntry records the last time a particular notifaction was sent out. + """A NotificationEntry records the last time a particular notifaction was sent out. It is recorded to ensure that notifications are not sent out "too often" to users. @@ -1956,10 +1849,7 @@ class NotificationEntry(models.Model): @classmethod def check_recent(cls, key: str, uid: int, delta: timedelta): - """ - Test if a particular notification has been sent in the specified time period - """ - + """Test if a particular notification has been sent in the specified time period.""" since = datetime.now().date() - delta entries = cls.objects.filter( @@ -1972,10 +1862,7 @@ class NotificationEntry(models.Model): @classmethod def notify(cls, key: str, uid: int): - """ - Notify the database that a particular notification has been sent out - """ - + """Notify the database that a particular notification has been sent out.""" entry, created = cls.objects.get_or_create( key=key, uid=uid @@ -1985,8 +1872,7 @@ class NotificationEntry(models.Model): class NotificationMessage(models.Model): - """ - A NotificationEntry records the last time a particular notifaction was sent out. + """A NotificationEntry records the last time a particular notifaction was sent out. It is recorded to ensure that notifications are not sent out "too often" to users. @@ -2062,10 +1948,10 @@ class NotificationMessage(models.Model): return reverse('api-notifications-list') def age(self): - """age of the message in seconds""" + """Age of the message in seconds.""" delta = now() - self.creation return delta.seconds def age_human(self): - """humanized age""" + """Humanized age.""" return naturaltime(self.creation) diff --git a/InvenTree/common/notifications.py b/InvenTree/common/notifications.py index c2e4f2d6aa..f775442376 100644 --- a/InvenTree/common/notifications.py +++ b/InvenTree/common/notifications.py @@ -12,9 +12,7 @@ logger = logging.getLogger('inventree') # region methods class NotificationMethod: - """ - Base class for notification methods - """ + """Base class for notification methods.""" METHOD_NAME = '' METHOD_ICON = None @@ -92,11 +90,11 @@ class NotificationMethod: # region plugins def get_plugin(self): - """Returns plugin class""" + """Returns plugin class.""" return False def global_setting_disable(self): - """Check if the method is defined in a plugin and has a global setting""" + """Check if the method is defined in a plugin and has a global setting.""" # Check if plugin has a setting if not self.GLOBAL_SETTING: return False @@ -115,9 +113,7 @@ class NotificationMethod: return False def usersetting(self, target): - """ - Returns setting for this method for a given user - """ + """Returns setting for this method for a given user.""" return NotificationUserSetting.get_setting(f'NOTIFICATION_METHOD_{self.METHOD_NAME.upper()}', user=target, method=self.METHOD_NAME) # endregion @@ -204,10 +200,7 @@ class UIMessageNotification(SingleNotificationMethod): def trigger_notifaction(obj, category=None, obj_ref='pk', **kwargs): - """ - Send out a notification - """ - + """Send out a notification.""" targets = kwargs.get('targets', None) target_fnc = kwargs.get('target_fnc', None) target_args = kwargs.get('target_args', []) diff --git a/InvenTree/common/serializers.py b/InvenTree/common/serializers.py index c91ad0f45d..79bc6da898 100644 --- a/InvenTree/common/serializers.py +++ b/InvenTree/common/serializers.py @@ -1,6 +1,4 @@ -""" -JSON serializers for common components -""" +"""JSON serializers for common components.""" from rest_framework import serializers @@ -11,9 +9,7 @@ from InvenTree.serializers import InvenTreeModelSerializer class SettingsSerializer(InvenTreeModelSerializer): - """ - Base serializer for a settings object - """ + """Base serializer for a settings object.""" key = serializers.CharField(read_only=True) @@ -30,10 +26,7 @@ class SettingsSerializer(InvenTreeModelSerializer): api_url = serializers.CharField(read_only=True) def get_choices(self, obj): - """ - Returns the choices available for a given item - """ - + """Returns the choices available for a given item.""" results = [] choices = obj.choices() @@ -48,10 +41,7 @@ class SettingsSerializer(InvenTreeModelSerializer): return results def get_value(self, obj): - """ - Make sure protected values are not returned - """ - + """Make sure protected values are not returned.""" # never return protected values if obj.protected: result = '***' @@ -62,9 +52,7 @@ class SettingsSerializer(InvenTreeModelSerializer): class GlobalSettingsSerializer(SettingsSerializer): - """ - Serializer for the InvenTreeSetting model - """ + """Serializer for the InvenTreeSetting model.""" class Meta: model = InvenTreeSetting @@ -82,9 +70,7 @@ class GlobalSettingsSerializer(SettingsSerializer): class UserSettingsSerializer(SettingsSerializer): - """ - Serializer for the InvenTreeUserSetting model - """ + """Serializer for the InvenTreeUserSetting model.""" user = serializers.PrimaryKeyRelatedField(read_only=True) @@ -105,8 +91,7 @@ class UserSettingsSerializer(SettingsSerializer): class GenericReferencedSettingSerializer(SettingsSerializer): - """ - Serializer for a GenericReferencedSetting model + """Serializer for a GenericReferencedSetting model. Args: MODEL: model class for the serializer @@ -118,9 +103,9 @@ class GenericReferencedSettingSerializer(SettingsSerializer): EXTRA_FIELDS = None def __init__(self, *args, **kwargs): - """Init overrides the Meta class to make it dynamic""" + """Init overrides the Meta class to make it dynamic.""" class CustomMeta: - """Scaffold for custom Meta class""" + """Scaffold for custom Meta class.""" fields = [ 'pk', 'key', @@ -144,9 +129,7 @@ class GenericReferencedSettingSerializer(SettingsSerializer): class NotificationMessageSerializer(InvenTreeModelSerializer): - """ - Serializer for the InvenTreeUserSetting model - """ + """Serializer for the InvenTreeUserSetting model.""" target = serializers.SerializerMethodField(read_only=True) diff --git a/InvenTree/common/settings.py b/InvenTree/common/settings.py index f010e65567..3bf544e13e 100644 --- a/InvenTree/common/settings.py +++ b/InvenTree/common/settings.py @@ -1,6 +1,4 @@ -""" -User-configurable settings for the common app -""" +"""User-configurable settings for the common app.""" from django.conf import settings @@ -8,9 +6,7 @@ from moneyed import CURRENCIES def currency_code_default(): - """ - Returns the default currency code (or USD if not specified) - """ + """Returns the default currency code (or USD if not specified)""" from django.db.utils import ProgrammingError from common.models import InvenTreeSetting @@ -28,23 +24,17 @@ def currency_code_default(): def currency_code_mappings(): - """ - Returns the current currency choices - """ + """Returns the current currency choices.""" return [(a, CURRENCIES[a].name) for a in settings.CURRENCIES] def currency_codes(): - """ - Returns the current currency codes - """ + """Returns the current currency codes.""" return [a for a in settings.CURRENCIES] def stock_expiry_enabled(): - """ - Returns True if the stock expiry feature is enabled - """ + """Returns True if the stock expiry feature is enabled.""" from common.models import InvenTreeSetting return InvenTreeSetting.get_setting('STOCK_ENABLE_EXPIRY') diff --git a/InvenTree/common/tasks.py b/InvenTree/common/tasks.py index 7fdd57999a..ec95214b5f 100644 --- a/InvenTree/common/tasks.py +++ b/InvenTree/common/tasks.py @@ -7,12 +7,10 @@ logger = logging.getLogger('inventree') def delete_old_notifications(): - """ - Remove old notifications from the database. + """Remove old notifications from the database. Anything older than ~3 months is removed """ - try: from common.models import NotificationEntry except AppRegistryNotReady: # pragma: no cover diff --git a/InvenTree/common/test_notifications.py b/InvenTree/common/test_notifications.py index 41e6303a81..ccaf298d84 100644 --- a/InvenTree/common/test_notifications.py +++ b/InvenTree/common/test_notifications.py @@ -8,7 +8,7 @@ from plugin.models import NotificationUserSetting class BaseNotificationTests(BaseNotificationIntegrationTest): def test_NotificationMethod(self): - """ensure the implementation requirements are tested""" + """Ensure the implementation requirements are tested.""" class FalseNotificationMethod(NotificationMethod): METHOD_NAME = 'FalseNotification' @@ -17,12 +17,12 @@ class BaseNotificationTests(BaseNotificationIntegrationTest): METHOD_NAME = 'AnotherFalseNotification' def send(self): - """a comment so we do not need a pass""" + """A comment so we do not need a pass.""" class NoNameNotificationMethod(NotificationMethod): def send(self): - """a comment so we do not need a pass""" + """A comment so we do not need a pass.""" class WrongContextNotificationMethod(NotificationMethod): METHOD_NAME = 'WrongContextNotification' @@ -34,7 +34,7 @@ class BaseNotificationTests(BaseNotificationIntegrationTest): ] def send(self): - """a comment so we do not need a pass""" + """A comment so we do not need a pass.""" # no send / send bulk with self.assertRaises(NotImplementedError): @@ -57,7 +57,7 @@ class BaseNotificationTests(BaseNotificationIntegrationTest): self._notification_run() def test_errors_passing(self): - """ensure that errors do not kill the whole delivery""" + """Ensure that errors do not kill the whole delivery.""" class ErrorImplementation(SingleNotificationMethod): METHOD_NAME = 'ErrorImplementation' @@ -74,8 +74,8 @@ class BaseNotificationTests(BaseNotificationIntegrationTest): class BulkNotificationMethodTests(BaseNotificationIntegrationTest): def test_BulkNotificationMethod(self): - """ - Ensure the implementation requirements are tested. + """Ensure the implementation requirements are tested. + MixinNotImplementedError needs to raise if the send_bulk() method is not set. """ @@ -92,8 +92,8 @@ class BulkNotificationMethodTests(BaseNotificationIntegrationTest): class SingleNotificationMethodTests(BaseNotificationIntegrationTest): def test_SingleNotificationMethod(self): - """ - Ensure the implementation requirements are tested. + """Ensure the implementation requirements are tested. + MixinNotImplementedError needs to raise if the send() method is not set. """ @@ -110,14 +110,14 @@ class SingleNotificationMethodTests(BaseNotificationIntegrationTest): class NotificationUserSettingTests(BaseNotificationIntegrationTest): - """ Tests for NotificationUserSetting """ + """Tests for NotificationUserSetting.""" def setUp(self): super().setUp() self.client.login(username=self.user.username, password='password') def test_setting_attributes(self): - """check notification method plugin methods: usersettings and tags """ + """Check notification method plugin methods: usersettings and tags.""" class SampleImplementation(BulkNotificationMethod): METHOD_NAME = 'test' diff --git a/InvenTree/common/test_tasks.py b/InvenTree/common/test_tasks.py index 0f19720b95..9d09eb64e0 100644 --- a/InvenTree/common/test_tasks.py +++ b/InvenTree/common/test_tasks.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from django.test import TestCase from common.models import NotificationEntry @@ -8,9 +7,7 @@ from . import tasks as common_tasks class TaskTest(TestCase): - """ - Tests for common tasks - """ + """Tests for common tasks.""" def test_delete(self): diff --git a/InvenTree/common/test_views.py b/InvenTree/common/test_views.py index 2394913c73..0e43770f02 100644 --- a/InvenTree/common/test_views.py +++ b/InvenTree/common/test_views.py @@ -1,3 +1 @@ -""" -Unit tests for the views associated with the 'common' app -""" +"""Unit tests for the views associated with the 'common' app.""" diff --git a/InvenTree/common/tests.py b/InvenTree/common/tests.py index b325d50170..e763f52ca5 100644 --- a/InvenTree/common/tests.py +++ b/InvenTree/common/tests.py @@ -19,9 +19,7 @@ CONTENT_TYPE_JSON = 'application/json' class SettingsTest(InvenTreeTestCase): - """ - Tests for the 'settings' model - """ + """Tests for the 'settings' model.""" fixtures = [ 'settings', @@ -42,9 +40,7 @@ class SettingsTest(InvenTreeTestCase): self.assertEqual(InvenTreeSetting.get_setting_object('iNvEnTrEE_inSTanCE').pk, 1) def test_settings_functions(self): - """ - Test settings functions and properties - """ + """Test settings functions and properties.""" # define settings to check instance_ref = 'INVENTREE_INSTANCE' instance_obj = InvenTreeSetting.get_setting_object(instance_ref) @@ -90,9 +86,7 @@ class SettingsTest(InvenTreeTestCase): self.assertEqual(stale_days.to_native_value(), 0) def test_allValues(self): - """ - Make sure that the allValues functions returns correctly - """ + """Make sure that the allValues functions returns correctly.""" # define testing settings # check a few keys @@ -147,11 +141,11 @@ class SettingsTest(InvenTreeTestCase): self.assertIn(default, [True, False]) def test_setting_data(self): - """ + """Test for settings data. + - Ensure that every setting has a name, which is translated - Ensure that every setting has a description, which is translated """ - for key, setting in InvenTreeSetting.SETTINGS.items(): try: @@ -168,10 +162,7 @@ class SettingsTest(InvenTreeTestCase): raise exc def test_defaults(self): - """ - Populate the settings with default values - """ - + """Populate the settings with default values.""" for key in InvenTreeSetting.SETTINGS.keys(): value = InvenTreeSetting.get_setting_default(key) @@ -192,14 +183,10 @@ class SettingsTest(InvenTreeTestCase): class GlobalSettingsApiTest(InvenTreeAPITestCase): - """ - Tests for the global settings API - """ + """Tests for the global settings API.""" def test_global_settings_api_list(self): - """ - Test list URL for global settings - """ + """Test list URL for global settings.""" url = reverse('api-global-setting-list') # Read out each of the global settings value, to ensure they are instantiated in the database @@ -246,7 +233,6 @@ class GlobalSettingsApiTest(InvenTreeAPITestCase): def test_api_detail(self): """Test that we can access the detail view for a setting based on the """ - # These keys are invalid, and should return 404 for key in ["apple", "carrot", "dog"]: response = self.get( @@ -287,28 +273,22 @@ class GlobalSettingsApiTest(InvenTreeAPITestCase): class UserSettingsApiTest(InvenTreeAPITestCase): - """ - Tests for the user settings API - """ + """Tests for the user settings API.""" def test_user_settings_api_list(self): - """ - Test list URL for user settings - """ + """Test list URL for user settings.""" url = reverse('api-user-setting-list') self.get(url, expected_code=200) def test_user_setting_invalid(self): - """Test a user setting with an invalid key""" - + """Test a user setting with an invalid key.""" url = reverse('api-user-setting-detail', kwargs={'key': 'DONKEY'}) self.get(url, expected_code=404) def test_user_setting_init(self): - """Test we can retrieve a setting which has not yet been initialized""" - + """Test we can retrieve a setting which has not yet been initialized.""" key = 'HOMEPAGE_PART_LATEST' # Ensure it does not actually exist in the database @@ -328,10 +308,7 @@ class UserSettingsApiTest(InvenTreeAPITestCase): self.assertEqual(setting.to_native_value(), False) def test_user_setting_boolean(self): - """ - Test a boolean user setting value - """ - + """Test a boolean user setting value.""" # Ensure we have a boolean setting available setting = InvenTreeUserSetting.get_setting_object( 'SEARCH_PREVIEW_SHOW_PARTS', @@ -480,25 +457,25 @@ class UserSettingsApiTest(InvenTreeAPITestCase): class NotificationUserSettingsApiTest(InvenTreeAPITestCase): - """Tests for the notification user settings API""" + """Tests for the notification user settings API.""" def test_api_list(self): - """Test list URL""" + """Test list URL.""" url = reverse('api-notifcation-setting-list') self.get(url, expected_code=200) def test_setting(self): - """Test the string name for NotificationUserSetting""" + """Test the string name for NotificationUserSetting.""" test_setting = NotificationUserSetting.get_setting_object('NOTIFICATION_METHOD_MAIL', user=self.user) self.assertEqual(str(test_setting), 'NOTIFICATION_METHOD_MAIL (for testuser): ') class PluginSettingsApiTest(InvenTreeAPITestCase): - """Tests for the plugin settings API""" + """Tests for the plugin settings API.""" def test_plugin_list(self): - """List installed plugins via API""" + """List installed plugins via API.""" url = reverse('api-plugin-list') # Simple request @@ -508,13 +485,13 @@ class PluginSettingsApiTest(InvenTreeAPITestCase): self.get(url, expected_code=200, data={'mixin': 'settings'}) def test_api_list(self): - """Test list URL""" + """Test list URL.""" url = reverse('api-plugin-setting-list') self.get(url, expected_code=200) def test_valid_plugin_slug(self): - """Test that an valid plugin slug runs through""" + """Test that an valid plugin slug runs through.""" # load plugin configs fixtures = PluginConfig.objects.all() if not fixtures: @@ -544,11 +521,11 @@ class PluginSettingsApiTest(InvenTreeAPITestCase): self.assertIn("Plugin 'sample' has no setting matching 'doesnotexsist'", str(response.data)) def test_invalid_setting_key(self): - """Test that an invalid setting key returns a 404""" + """Test that an invalid setting key returns a 404.""" ... def test_uninitialized_setting(self): - """Test that requesting an uninitialized setting creates the setting""" + """Test that requesting an uninitialized setting creates the setting.""" ... @@ -684,21 +661,16 @@ class NotificationTest(InvenTreeAPITestCase): self.assertTrue(NotificationEntry.check_recent('test.notification', 1, delta)) def test_api_list(self): - """Test list URL""" + """Test list URL.""" url = reverse('api-notifications-list') self.get(url, expected_code=200) class LoadingTest(TestCase): - """ - Tests for the common config - """ + """Tests for the common config.""" def test_restart_flag(self): - """ - Test that the restart flag is reset on start - """ - + """Test that the restart flag is reset on start.""" import common.models from plugin import registry @@ -713,10 +685,10 @@ class LoadingTest(TestCase): class ColorThemeTest(TestCase): - """Tests for ColorTheme""" + """Tests for ColorTheme.""" def test_choices(self): - """Test that default choices are returned""" + """Test that default choices are returned.""" result = ColorTheme.get_color_themes_choices() # skip @@ -725,7 +697,7 @@ class ColorThemeTest(TestCase): self.assertIn(('default', 'Default'), result) def test_valid_choice(self): - """Check that is_valid_choice works correctly""" + """Check that is_valid_choice works correctly.""" result = ColorTheme.get_color_themes_choices() # skip diff --git a/InvenTree/common/urls.py b/InvenTree/common/urls.py index 261ea1a691..4803d86236 100644 --- a/InvenTree/common/urls.py +++ b/InvenTree/common/urls.py @@ -1,6 +1,4 @@ -""" -URL lookup for common views -""" +"""URL lookup for common views.""" common_urls = [ ] diff --git a/InvenTree/common/views.py b/InvenTree/common/views.py index ee5a02a288..ff7cc71526 100644 --- a/InvenTree/common/views.py +++ b/InvenTree/common/views.py @@ -1,6 +1,4 @@ -""" -Django views for interacting with common models -""" +"""Django views for interacting with common models.""" import os @@ -18,10 +16,10 @@ from .files import FileManager class MultiStepFormView(SessionWizardView): - """ Setup basic methods of multi-step form + """Setup basic methods of multi-step form. - form_list: list of forms - form_steps_description: description for each form + form_list: list of forms + form_steps_description: description for each form """ form_steps_template = [] @@ -31,14 +29,13 @@ class MultiStepFormView(SessionWizardView): file_storage = FileSystemStorage(settings.MEDIA_ROOT) def __init__(self, *args, **kwargs): - """ Override init method to set media folder """ + """Override init method to set media folder.""" super().__init__(**kwargs) self.process_media_folder() def process_media_folder(self): - """ Process media folder """ - + """Process media folder.""" if self.media_folder: media_folder_abs = os.path.join(settings.MEDIA_ROOT, self.media_folder) if not os.path.exists(media_folder_abs): @@ -46,8 +43,7 @@ class MultiStepFormView(SessionWizardView): self.file_storage = FileSystemStorage(location=media_folder_abs) def get_template_names(self): - """ Select template """ - + """Select template.""" try: # Get template template = self.form_steps_template[self.steps.index] @@ -57,8 +53,7 @@ class MultiStepFormView(SessionWizardView): return template def get_context_data(self, **kwargs): - """ Update context data """ - + """Update context data.""" # Retrieve current context context = super().get_context_data(**kwargs) @@ -74,7 +69,9 @@ class MultiStepFormView(SessionWizardView): class FileManagementFormView(MultiStepFormView): - """ Setup form wizard to perform the following steps: + """File management form wizard + + Perform the following steps: 1. Upload tabular data file 2. Match headers to InvenTree fields 3. Edit row data and match InvenTree items @@ -95,8 +92,7 @@ class FileManagementFormView(MultiStepFormView): extra_context_data = {} def __init__(self, *args, **kwargs): - """ Initialize the FormView """ - + """Initialize the FormView.""" # Perform all checks and inits for MultiStepFormView super().__init__(self, *args, **kwargs) @@ -105,8 +101,7 @@ class FileManagementFormView(MultiStepFormView): raise NotImplementedError('A subclass of a file manager class needs to be set!') def get_context_data(self, form=None, **kwargs): - """ Handle context data """ - + """Handle context data.""" if form is None: form = self.get_form() @@ -136,8 +131,7 @@ class FileManagementFormView(MultiStepFormView): return context def get_file_manager(self, step=None, form=None): - """ Get FileManager instance from uploaded file """ - + """Get FileManager instance from uploaded file.""" if self.file_manager: return @@ -151,8 +145,7 @@ class FileManagementFormView(MultiStepFormView): self.file_manager = self.file_manager_class(file=file, name=self.name) def get_form_kwargs(self, step=None): - """ Update kwargs to dynamically build forms """ - + """Update kwargs to dynamically build forms.""" # Always retrieve FileManager instance from uploaded file self.get_file_manager(step) @@ -191,7 +184,7 @@ class FileManagementFormView(MultiStepFormView): return super().get_form_kwargs() def get_form(self, step=None, data=None, files=None): - """ add crispy-form helper to form """ + """Add crispy-form helper to form.""" form = super().get_form(step=step, data=data, files=files) form.helper = FormHelper() @@ -200,17 +193,14 @@ class FileManagementFormView(MultiStepFormView): return form def get_form_table_data(self, form_data): - """ Extract table cell data from form data and fields. - These data are used to maintain state between sessions. + """Extract table cell data from form data and fields. These data are used to maintain state between sessions. Table data keys are as follows: col_name_ - Column name at idx as provided in the uploaded file col_guess_ - Column guess at idx as selected row__col - Cell data as provided in the uploaded file - """ - # Map the columns self.column_names = {} self.column_selections = {} @@ -264,8 +254,7 @@ class FileManagementFormView(MultiStepFormView): self.row_data[row_id][col_id] = value def set_form_table_data(self, form=None): - """ Set the form table data """ - + """Set the form table data.""" if self.column_names: # Re-construct the column data self.columns = [] @@ -324,10 +313,10 @@ class FileManagementFormView(MultiStepFormView): row[field_key] = field_key + '-' + str(row['index']) def get_column_index(self, name): - """ Return the index of the column with the given name. + """Return the index of the column with the given name. + It named column is not found, return -1 """ - try: idx = list(self.column_selections.values()).index(name) except ValueError: @@ -336,9 +325,7 @@ class FileManagementFormView(MultiStepFormView): return idx def get_field_selection(self): - """ Once data columns have been selected, attempt to pre-select the proper data from the database. - This function is called once the field selection has been validated. - The pre-fill data are then passed through to the part selection form. + """Once data columns have been selected, attempt to pre-select the proper data from the database. This function is called once the field selection has been validated. The pre-fill data are then passed through to the part selection form. This method is very specific to the type of data found in the file, therefore overwrite it in the subclass. @@ -346,7 +333,7 @@ class FileManagementFormView(MultiStepFormView): pass def get_clean_items(self): - """ returns dict with all cleaned values """ + """Returns dict with all cleaned values.""" items = {} for form_key, form_value in self.get_all_cleaned_data().items(): @@ -373,8 +360,7 @@ class FileManagementFormView(MultiStepFormView): return items def check_field_selection(self, form): - """ Check field matching """ - + """Check field matching.""" # Are there any missing columns? missing_columns = [] @@ -422,8 +408,7 @@ class FileManagementFormView(MultiStepFormView): return valid def validate(self, step, form): - """ Validate forms """ - + """Validate forms.""" valid = True # Get form table data @@ -442,8 +427,7 @@ class FileManagementFormView(MultiStepFormView): return valid def post(self, request, *args, **kwargs): - """ Perform validations before posting data """ - + """Perform validations before posting data.""" wizard_goto_step = self.request.POST.get('wizard_goto_step', None) form = self.get_form(data=self.request.POST, files=self.request.FILES) @@ -458,8 +442,7 @@ class FileManagementFormView(MultiStepFormView): class FileManagementAjaxView(AjaxView): - """ Use a FileManagementFormView as base for a AjaxView - Inherit this class before inheriting the base FileManagementFormView + """Use a FileManagementFormView as base for a AjaxView Inherit this class before inheriting the base FileManagementFormView. ajax_form_steps_template: templates for rendering ajax validate: function to validate the current form -> normally point to the same function in the base FileManagementFormView @@ -504,7 +487,7 @@ class FileManagementAjaxView(AjaxView): return self.renderJsonResponse(request) def renderJsonResponse(self, request, form=None, data={}, context=None): - """ always set the right templates before rendering """ + """Always set the right templates before rendering.""" self.setTemplate() return super().renderJsonResponse(request, form=form, data=data, context=context) @@ -516,7 +499,7 @@ class FileManagementAjaxView(AjaxView): return data def setTemplate(self): - """ set template name and title """ + """Set template name and title.""" self.ajax_template_name = self.ajax_form_steps_template[self.get_step_index()] self.ajax_form_title = self.form_steps_description[self.get_step_index()] diff --git a/InvenTree/company/__init__.py b/InvenTree/company/__init__.py index 6c89578ac3..38da11ee68 100644 --- a/InvenTree/company/__init__.py +++ b/InvenTree/company/__init__.py @@ -1,5 +1,4 @@ -""" -The Company module is responsible for managing Company interactions. +"""The Company module is responsible for managing Company interactions. A company can be either (or both): diff --git a/InvenTree/company/admin.py b/InvenTree/company/admin.py index d3bf75dab3..3720c94555 100644 --- a/InvenTree/company/admin.py +++ b/InvenTree/company/admin.py @@ -13,7 +13,7 @@ from .models import (Company, ManufacturerPart, ManufacturerPartAttachment, class CompanyResource(ModelResource): - """ Class for managing Company data import/export """ + """Class for managing Company data import/export.""" class Meta: model = Company @@ -35,9 +35,7 @@ class CompanyAdmin(ImportExportModelAdmin): class SupplierPartResource(ModelResource): - """ - Class for managing SupplierPart data import/export - """ + """Class for managing SupplierPart data import/export.""" part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part)) @@ -71,9 +69,7 @@ class SupplierPartAdmin(ImportExportModelAdmin): class ManufacturerPartResource(ModelResource): - """ - Class for managing ManufacturerPart data import/export - """ + """Class for managing ManufacturerPart data import/export.""" part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part)) @@ -91,9 +87,7 @@ class ManufacturerPartResource(ModelResource): class ManufacturerPartAdmin(ImportExportModelAdmin): - """ - Admin class for ManufacturerPart model - """ + """Admin class for ManufacturerPart model.""" resource_class = ManufacturerPartResource @@ -109,9 +103,7 @@ class ManufacturerPartAdmin(ImportExportModelAdmin): class ManufacturerPartAttachmentAdmin(ImportExportModelAdmin): - """ - Admin class for ManufacturerPartAttachment model - """ + """Admin class for ManufacturerPartAttachment model.""" list_display = ('manufacturer_part', 'attachment', 'comment') @@ -119,9 +111,7 @@ class ManufacturerPartAttachmentAdmin(ImportExportModelAdmin): class ManufacturerPartParameterResource(ModelResource): - """ - Class for managing ManufacturerPartParameter data import/export - """ + """Class for managing ManufacturerPartParameter data import/export.""" class Meta: model = ManufacturerPartParameter @@ -131,9 +121,7 @@ class ManufacturerPartParameterResource(ModelResource): class ManufacturerPartParameterAdmin(ImportExportModelAdmin): - """ - Admin class for ManufacturerPartParameter model - """ + """Admin class for ManufacturerPartParameter model.""" resource_class = ManufacturerPartParameterResource @@ -149,7 +137,7 @@ class ManufacturerPartParameterAdmin(ImportExportModelAdmin): class SupplierPriceBreakResource(ModelResource): - """ Class for managing SupplierPriceBreak data import/export """ + """Class for managing SupplierPriceBreak data import/export.""" part = Field(attribute='part', widget=widgets.ForeignKeyWidget(SupplierPart)) diff --git a/InvenTree/company/api.py b/InvenTree/company/api.py index b63cd65c83..44bfab7458 100644 --- a/InvenTree/company/api.py +++ b/InvenTree/company/api.py @@ -1,6 +1,4 @@ -""" -Provides a JSON API for the Company app -""" +"""Provides a JSON API for the Company app.""" from django.db.models import Q from django.urls import include, re_path @@ -23,7 +21,7 @@ from .serializers import (CompanySerializer, class CompanyList(generics.ListCreateAPIView): - """ API endpoint for accessing a list of Company objects + """API endpoint for accessing a list of Company objects. Provides two methods: @@ -70,7 +68,7 @@ class CompanyList(generics.ListCreateAPIView): class CompanyDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail of a single Company object """ + """API endpoint for detail of a single Company object.""" queryset = Company.objects.all() serializer_class = CompanySerializer @@ -84,9 +82,7 @@ class CompanyDetail(generics.RetrieveUpdateDestroyAPIView): class ManufacturerPartFilter(rest_filters.FilterSet): - """ - Custom API filters for the ManufacturerPart list endpoint. - """ + """Custom API filters for the ManufacturerPart list endpoint.""" class Meta: model = ManufacturerPart @@ -101,7 +97,7 @@ class ManufacturerPartFilter(rest_filters.FilterSet): class ManufacturerPartList(generics.ListCreateAPIView): - """ API endpoint for list view of ManufacturerPart object + """API endpoint for list view of ManufacturerPart object. - GET: Return list of ManufacturerPart objects - POST: Create a new ManufacturerPart object @@ -149,7 +145,7 @@ class ManufacturerPartList(generics.ListCreateAPIView): class ManufacturerPartDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of ManufacturerPart object + """API endpoint for detail view of ManufacturerPart object. - GET: Retrieve detail view - PATCH: Update object @@ -161,9 +157,7 @@ class ManufacturerPartDetail(generics.RetrieveUpdateDestroyAPIView): class ManufacturerPartAttachmentList(AttachmentMixin, generics.ListCreateAPIView): - """ - API endpoint for listing (and creating) a ManufacturerPartAttachment (file upload). - """ + """API endpoint for listing (and creating) a ManufacturerPartAttachment (file upload).""" queryset = ManufacturerPartAttachment.objects.all() serializer_class = ManufacturerPartAttachmentSerializer @@ -178,18 +172,14 @@ class ManufacturerPartAttachmentList(AttachmentMixin, generics.ListCreateAPIView class ManufacturerPartAttachmentDetail(AttachmentMixin, generics.RetrieveUpdateDestroyAPIView): - """ - Detail endpooint for ManufacturerPartAttachment model - """ + """Detail endpooint for ManufacturerPartAttachment model.""" queryset = ManufacturerPartAttachment.objects.all() serializer_class = ManufacturerPartAttachmentSerializer class ManufacturerPartParameterList(generics.ListCreateAPIView): - """ - API endpoint for list view of ManufacturerPartParamater model. - """ + """API endpoint for list view of ManufacturerPartParamater model.""" queryset = ManufacturerPartParameter.objects.all() serializer_class = ManufacturerPartParameterSerializer @@ -215,10 +205,7 @@ class ManufacturerPartParameterList(generics.ListCreateAPIView): return self.serializer_class(*args, **kwargs) def filter_queryset(self, queryset): - """ - Custom filtering for the queryset - """ - + """Custom filtering for the queryset.""" queryset = super().filter_queryset(queryset) params = self.request.query_params @@ -258,16 +245,14 @@ class ManufacturerPartParameterList(generics.ListCreateAPIView): class ManufacturerPartParameterDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for detail view of ManufacturerPartParameter model - """ + """API endpoint for detail view of ManufacturerPartParameter model.""" queryset = ManufacturerPartParameter.objects.all() serializer_class = ManufacturerPartParameterSerializer class SupplierPartList(generics.ListCreateAPIView): - """ API endpoint for list view of SupplierPart object + """API endpoint for list view of SupplierPart object. - GET: Return list of SupplierPart objects - POST: Create a new SupplierPart object @@ -282,10 +267,7 @@ class SupplierPartList(generics.ListCreateAPIView): return queryset def filter_queryset(self, queryset): - """ - Custom filtering for the queryset. - """ - + """Custom filtering for the queryset.""" queryset = super().filter_queryset(queryset) params = self.request.query_params @@ -369,7 +351,7 @@ class SupplierPartList(generics.ListCreateAPIView): class SupplierPartDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of SupplierPart object + """API endpoint for detail view of SupplierPart object. - GET: Retrieve detail view - PATCH: Update object @@ -384,7 +366,7 @@ class SupplierPartDetail(generics.RetrieveUpdateDestroyAPIView): class SupplierPriceBreakList(generics.ListCreateAPIView): - """ API endpoint for list view of SupplierPriceBreak object + """API endpoint for list view of SupplierPriceBreak object. - GET: Retrieve list of SupplierPriceBreak objects - POST: Create a new SupplierPriceBreak object @@ -403,9 +385,7 @@ class SupplierPriceBreakList(generics.ListCreateAPIView): class SupplierPriceBreakDetail(generics.RetrieveUpdateDestroyAPIView): - """ - Detail endpoint for SupplierPriceBreak object - """ + """Detail endpoint for SupplierPriceBreak object.""" queryset = SupplierPriceBreak.objects.all() serializer_class = SupplierPriceBreakSerializer diff --git a/InvenTree/company/apps.py b/InvenTree/company/apps.py index a0cd4919cf..ee2d5f777d 100644 --- a/InvenTree/company/apps.py +++ b/InvenTree/company/apps.py @@ -5,8 +5,5 @@ class CompanyConfig(AppConfig): name = 'company' def ready(self): - """ - This function is called whenever the Company app is loaded. - """ - + """This function is called whenever the Company app is loaded.""" pass diff --git a/InvenTree/company/forms.py b/InvenTree/company/forms.py index bf15038898..78f6a1ada8 100644 --- a/InvenTree/company/forms.py +++ b/InvenTree/company/forms.py @@ -1,6 +1,4 @@ -""" -Django Forms for interacting with Company app -""" +"""Django Forms for interacting with Company app.""" import django.forms from django.utils.translation import gettext_lazy as _ @@ -12,9 +10,7 @@ from .models import Company, SupplierPriceBreak class CompanyImageDownloadForm(HelperForm): - """ - Form for downloading an image from a URL - """ + """Form for downloading an image from a URL.""" url = django.forms.URLField( label=_('URL'), @@ -30,7 +26,7 @@ class CompanyImageDownloadForm(HelperForm): class EditPriceBreakForm(HelperForm): - """ Form for creating / editing a supplier price break """ + """Form for creating / editing a supplier price break.""" quantity = RoundingDecimalFormField( max_digits=10, diff --git a/InvenTree/company/models.py b/InvenTree/company/models.py index 2391dff749..acdeb9c737 100644 --- a/InvenTree/company/models.py +++ b/InvenTree/company/models.py @@ -1,4 +1,4 @@ -"""Company database model definitions""" +"""Company database model definitions.""" import os @@ -25,7 +25,7 @@ from InvenTree.status_codes import PurchaseOrderStatus def rename_company_image(instance, filename): - """Function to rename a company image after upload + """Function to rename a company image after upload. Args: instance: Company object @@ -50,7 +50,7 @@ def rename_company_image(instance, filename): class Company(models.Model): - """ A Company object represents an external company. + """A Company object represents an external company. It may be a supplier or a customer or a manufacturer (or a combination) @@ -148,8 +148,7 @@ class Company(models.Model): @property def currency_code(self): - """ - Return the currency code associated with this company. + """Return the currency code associated with this company. - If the currency code is invalid, use the default currency - If the currency code is not specified, use the default currency @@ -162,22 +161,22 @@ class Company(models.Model): return code def __str__(self): - """ Get string representation of a Company """ + """Get string representation of a Company.""" return "{n} - {d}".format(n=self.name, d=self.description) def get_absolute_url(self): - """ Get the web URL for the detail view for this Company """ + """Get the web URL for the detail view for this Company.""" return reverse('company-detail', kwargs={'pk': self.id}) def get_image_url(self): - """ Return the URL of the image for this company """ + """Return the URL of the image for this company.""" if self.image: return getMediaUrl(self.image.url) else: return getBlankImage() def get_thumbnail_url(self): - """ Return the URL for the thumbnail image for this Company """ + """Return the URL for the thumbnail image for this Company.""" if self.image: return getMediaUrl(self.image.thumbnail.url) else: @@ -185,7 +184,7 @@ class Company(models.Model): @property def manufactured_part_count(self): - """ The number of parts manufactured by this company """ + """The number of parts manufactured by this company.""" return self.manufactured_parts.count() @property @@ -194,22 +193,22 @@ class Company(models.Model): @property def supplied_part_count(self): - """ The number of parts supplied by this company """ + """The number of parts supplied by this company.""" return self.supplied_parts.count() @property def has_supplied_parts(self): - """ Return True if this company supplies any parts """ + """Return True if this company supplies any parts.""" return self.supplied_part_count > 0 @property def parts(self): - """ Return SupplierPart objects which are supplied or manufactured by this company """ + """Return SupplierPart objects which are supplied or manufactured by this company.""" return SupplierPart.objects.filter(Q(supplier=self.id) | Q(manufacturer_part__manufacturer=self.id)) @property def part_count(self): - """ The number of parts manufactured (or supplied) by this Company """ + """The number of parts manufactured (or supplied) by this Company.""" return self.parts.count() @property @@ -218,25 +217,25 @@ class Company(models.Model): @property def stock_items(self): - """ Return a list of all stock items supplied or manufactured by this company """ + """Return a list of all stock items supplied or manufactured by this company.""" stock = apps.get_model('stock', 'StockItem') return stock.objects.filter(Q(supplier_part__supplier=self.id) | Q(supplier_part__manufacturer_part__manufacturer=self.id)).all() @property def stock_count(self): - """ Return the number of stock items supplied or manufactured by this company """ + """Return the number of stock items supplied or manufactured by this company.""" return self.stock_items.count() def outstanding_purchase_orders(self): - """ Return purchase orders which are 'outstanding' """ + """Return purchase orders which are 'outstanding'.""" return self.purchase_orders.filter(status__in=PurchaseOrderStatus.OPEN) def pending_purchase_orders(self): - """ Return purchase orders which are PENDING (not yet issued) """ + """Return purchase orders which are PENDING (not yet issued)""" return self.purchase_orders.filter(status=PurchaseOrderStatus.PENDING) def closed_purchase_orders(self): - """ Return purchase orders which are not 'outstanding' + """Return purchase orders which are not 'outstanding'. - Complete - Failed / lost @@ -248,13 +247,12 @@ class Company(models.Model): return self.purchase_orders.filter(status=PurchaseOrderStatus.COMPLETE) def failed_purchase_orders(self): - """ Return any purchase orders which were not successful """ + """Return any purchase orders which were not successful.""" return self.purchase_orders.filter(status__in=PurchaseOrderStatus.FAILED) class Contact(models.Model): - """ A Contact represents a person who works at a particular company. - A Company may have zero or more associated Contact objects. + """A Contact represents a person who works at a particular company. A Company may have zero or more associated Contact objects. Attributes: company: Company link for this contact @@ -277,10 +275,7 @@ class Contact(models.Model): class ManufacturerPart(models.Model): - """ Represents a unique part as provided by a Manufacturer - Each ManufacturerPart is identified by a MPN (Manufacturer Part Number) - Each ManufacturerPart is also linked to a Part object. - A Part may be available from multiple manufacturers + """Represents a unique part as provided by a Manufacturer Each ManufacturerPart is identified by a MPN (Manufacturer Part Number) Each ManufacturerPart is also linked to a Part object. A Part may be available from multiple manufacturers. Attributes: part: Link to the master Part @@ -339,7 +334,7 @@ class ManufacturerPart(models.Model): @classmethod def create(cls, part, manufacturer, mpn, description, link=None): - """Check if ManufacturerPart instance does not already exist then create it""" + """Check if ManufacturerPart instance does not already exist then create it.""" manufacturer_part = None try: @@ -366,9 +361,7 @@ class ManufacturerPart(models.Model): class ManufacturerPartAttachment(InvenTreeAttachment): - """ - Model for storing file attachments against a ManufacturerPart object - """ + """Model for storing file attachments against a ManufacturerPart object.""" @staticmethod def get_api_url(): @@ -382,8 +375,7 @@ class ManufacturerPartAttachment(InvenTreeAttachment): class ManufacturerPartParameter(models.Model): - """ - A ManufacturerPartParameter represents a key:value parameter for a MnaufacturerPart. + """A ManufacturerPartParameter represents a key:value parameter for a MnaufacturerPart. This is used to represent parmeters / properties for a particular manufacturer part. @@ -427,10 +419,10 @@ class ManufacturerPartParameter(models.Model): class SupplierPartManager(models.Manager): - """ Define custom SupplierPart objects manager + """Define custom SupplierPart objects manager. - The main purpose of this manager is to improve database hit as the - SupplierPart model involves A LOT of foreign keys lookups + The main purpose of this manager is to improve database hit as the + SupplierPart model involves A LOT of foreign keys lookups """ def get_queryset(self): @@ -443,10 +435,7 @@ class SupplierPartManager(models.Manager): class SupplierPart(models.Model): - """ Represents a unique part as provided by a Supplier - Each SupplierPart is identified by a SKU (Supplier Part Number) - Each SupplierPart is also linked to a Part or ManufacturerPart object. - A Part may be available from multiple suppliers + """Represents a unique part as provided by a Supplier Each SupplierPart is identified by a SKU (Supplier Part Number) Each SupplierPart is also linked to a Part or ManufacturerPart object. A Part may be available from multiple suppliers. Attributes: part: Link to the master Part (Obsolete) @@ -498,7 +487,7 @@ class SupplierPart(models.Model): }) def save(self, *args, **kwargs): - """ Overriding save method to connect an existing ManufacturerPart """ + """Overriding save method to connect an existing ManufacturerPart.""" manufacturer_part = None if all(key in kwargs for key in ('manufacturer', 'MPN')): @@ -602,7 +591,7 @@ class SupplierPart(models.Model): @property def price_breaks(self): - """ Return the associated price breaks in the correct order """ + """Return the associated price breaks in the correct order.""" return self.pricebreaks.order_by('quantity').all() @property @@ -610,9 +599,9 @@ class SupplierPart(models.Model): return self.get_price(1) def add_price_break(self, quantity, price): - """Create a new price break for this part + """Create a new price break for this part. - args: + Args: quantity - Numerical quantity price - Must be a Money object """ @@ -651,7 +640,7 @@ class SupplierPart(models.Model): return max(q - r, 0) def purchase_orders(self): - """Returns a list of purchase orders relating to this supplier part""" + """Returns a list of purchase orders relating to this supplier part.""" return [line.order for line in self.purchase_order_line_items.all().prefetch_related('order')] @property @@ -675,6 +664,7 @@ class SupplierPart(models.Model): class SupplierPriceBreak(common.models.PriceBreak): """Represents a quantity price break for a SupplierPart. + - Suppliers can offer discounts at larger quantities - SupplierPart(s) may have zero-or-more associated SupplierPriceBreak(s) diff --git a/InvenTree/company/serializers.py b/InvenTree/company/serializers.py index e0c34d077f..e31e2cc5b9 100644 --- a/InvenTree/company/serializers.py +++ b/InvenTree/company/serializers.py @@ -1,6 +1,4 @@ -""" -JSON serializers for Company app -""" +"""JSON serializers for Company app.""" from django.utils.translation import gettext_lazy as _ @@ -21,7 +19,7 @@ from .models import (Company, ManufacturerPart, ManufacturerPartAttachment, class CompanyBriefSerializer(InvenTreeModelSerializer): - """ Serializer for Company object (limited detail) """ + """Serializer for Company object (limited detail)""" url = serializers.CharField(source='get_absolute_url', read_only=True) @@ -39,7 +37,7 @@ class CompanyBriefSerializer(InvenTreeModelSerializer): class CompanySerializer(InvenTreeModelSerializer): - """ Serializer for Company object (full detail) """ + """Serializer for Company object (full detail)""" @staticmethod def annotate_queryset(queryset): @@ -96,9 +94,7 @@ class CompanySerializer(InvenTreeModelSerializer): class ManufacturerPartSerializer(InvenTreeModelSerializer): - """ - Serializer for ManufacturerPart object - """ + """Serializer for ManufacturerPart object.""" part_detail = PartBriefSerializer(source='part', many=False, read_only=True) @@ -141,9 +137,7 @@ class ManufacturerPartSerializer(InvenTreeModelSerializer): class ManufacturerPartAttachmentSerializer(InvenTreeAttachmentSerializer): - """ - Serializer for the ManufacturerPartAttachment class - """ + """Serializer for the ManufacturerPartAttachment class.""" class Meta: model = ManufacturerPartAttachment @@ -164,9 +158,7 @@ class ManufacturerPartAttachmentSerializer(InvenTreeAttachmentSerializer): class ManufacturerPartParameterSerializer(InvenTreeModelSerializer): - """ - Serializer for the ManufacturerPartParameter model - """ + """Serializer for the ManufacturerPartParameter model.""" manufacturer_part_detail = ManufacturerPartSerializer(source='manufacturer_part', many=False, read_only=True) @@ -193,7 +185,7 @@ class ManufacturerPartParameterSerializer(InvenTreeModelSerializer): class SupplierPartSerializer(InvenTreeModelSerializer): - """ Serializer for SupplierPart object """ + """Serializer for SupplierPart object.""" part_detail = PartBriefSerializer(source='part', many=False, read_only=True) @@ -255,8 +247,7 @@ class SupplierPartSerializer(InvenTreeModelSerializer): ] def create(self, validated_data): - """ Extract manufacturer data and process ManufacturerPart """ - + """Extract manufacturer data and process ManufacturerPart.""" # Create SupplierPart supplier_part = super().create(validated_data) @@ -275,7 +266,7 @@ class SupplierPartSerializer(InvenTreeModelSerializer): class SupplierPriceBreakSerializer(InvenTreeModelSerializer): - """ Serializer for SupplierPriceBreak object """ + """Serializer for SupplierPriceBreak object.""" quantity = InvenTreeDecimalField() diff --git a/InvenTree/company/test_api.py b/InvenTree/company/test_api.py index e0b54130ff..d3465cd847 100644 --- a/InvenTree/company/test_api.py +++ b/InvenTree/company/test_api.py @@ -8,9 +8,7 @@ from .models import Company class CompanyTest(InvenTreeAPITestCase): - """ - Series of tests for the Company DRF API - """ + """Series of tests for the Company DRF API.""" roles = [ 'purchase_order.add', @@ -45,10 +43,7 @@ class CompanyTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 2) def test_company_detail(self): - """ - Tests for the Company detail endpoint - """ - + """Tests for the Company detail endpoint.""" url = reverse('api-company-detail', kwargs={'pk': self.acme.pk}) response = self.get(url) @@ -71,20 +66,14 @@ class CompanyTest(InvenTreeAPITestCase): self.assertEqual(response.data['currency'], 'NZD') def test_company_search(self): - """ - Test search functionality in company list - """ - + """Test search functionality in company list.""" url = reverse('api-company-list') data = {'search': 'cup'} response = self.get(url, data) self.assertEqual(len(response.data), 2) def test_company_create(self): - """ - Test that we can create a company via the API! - """ - + """Test that we can create a company via the API!""" url = reverse('api-company-list') # Name is required @@ -146,9 +135,7 @@ class CompanyTest(InvenTreeAPITestCase): class ManufacturerTest(InvenTreeAPITestCase): - """ - Series of tests for the Manufacturer DRF API - """ + """Series of tests for the Manufacturer DRF API.""" fixtures = [ 'category', @@ -191,9 +178,7 @@ class ManufacturerTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 2) def test_manufacturer_part_detail(self): - """ - Tests for the ManufacturerPart detail endpoint - """ + """Tests for the ManufacturerPart detail endpoint.""" url = reverse('api-manufacturer-part-detail', kwargs={'pk': 1}) response = self.get(url) diff --git a/InvenTree/company/test_migrations.py b/InvenTree/company/test_migrations.py index 882d54260f..7bfb828a47 100644 --- a/InvenTree/company/test_migrations.py +++ b/InvenTree/company/test_migrations.py @@ -1,6 +1,4 @@ -""" -Tests for the company model database migrations -""" +"""Tests for the company model database migrations.""" from django_test_migrations.contrib.unittest_case import MigratorTestCase @@ -13,10 +11,7 @@ class TestForwardMigrations(MigratorTestCase): migrate_to = ('company', helpers.getNewestMigrationFile('company')) def prepare(self): - """ - Create some simple Company data, and ensure that it migrates OK - """ - + """Create some simple Company data, and ensure that it migrates OK.""" Company = self.old_state.apps.get_model('company', 'company') Company.objects.create( @@ -33,22 +28,18 @@ class TestForwardMigrations(MigratorTestCase): class TestManufacturerField(MigratorTestCase): - """ - Tests for migration 0019 which migrates from old 'manufacturer_name' field to new 'manufacturer' field - """ + """Tests for migration 0019 which migrates from old 'manufacturer_name' field to new 'manufacturer' field.""" migrate_from = ('company', '0018_supplierpart_manufacturer') migrate_to = ('company', '0019_auto_20200413_0642') def prepare(self): - """ - Prepare the database by adding some test data 'before' the change: + """Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object """ - Part = self.old_state.apps.get_model('part', 'part') Company = self.old_state.apps.get_model('company', 'company') SupplierPart = self.old_state.apps.get_model('company', 'supplierpart') @@ -85,10 +76,7 @@ class TestManufacturerField(MigratorTestCase): self.assertEqual(Company.objects.count(), 1) def test_company_objects(self): - """ - Test that the new companies have been created successfully - """ - + """Test that the new companies have been created successfully.""" # Two additional company objects should have been created Company = self.new_state.apps.get_model('company', 'company') self.assertEqual(Company.objects.count(), 3) @@ -108,22 +96,18 @@ class TestManufacturerField(MigratorTestCase): class TestManufacturerPart(MigratorTestCase): - """ - Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model - """ + """Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model.""" migrate_from = ('company', '0033_auto_20210410_1528') migrate_to = ('company', '0037_supplierpart_update_3') def prepare(self): - """ - Prepare the database by adding some test data 'before' the change: + """Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object """ - Part = self.old_state.apps.get_model('part', 'part') Company = self.old_state.apps.get_model('company', 'company') SupplierPart = self.old_state.apps.get_model('company', 'supplierpart') @@ -214,10 +198,7 @@ class TestManufacturerPart(MigratorTestCase): ) def test_manufacturer_part_objects(self): - """ - Test that the new companies have been created successfully - """ - + """Test that the new companies have been created successfully.""" # Check on the SupplierPart objects SupplierPart = self.new_state.apps.get_model('company', 'supplierpart') @@ -238,16 +219,13 @@ class TestManufacturerPart(MigratorTestCase): class TestCurrencyMigration(MigratorTestCase): - """ - Tests for upgrade from basic currency support to django-money - """ + """Tests for upgrade from basic currency support to django-money.""" migrate_from = ('company', '0025_auto_20201110_1001') migrate_to = ('company', '0026_auto_20201110_1011') def prepare(self): - """ - Prepare some data: + """Prepare some data: - A part to buy - A supplier to buy from @@ -255,7 +233,6 @@ class TestCurrencyMigration(MigratorTestCase): - Multiple currency objects - Multiple supplier price breaks """ - Part = self.old_state.apps.get_model('part', 'part') part = Part.objects.create( diff --git a/InvenTree/company/test_views.py b/InvenTree/company/test_views.py index a3ecd1651a..a1e44a4000 100644 --- a/InvenTree/company/test_views.py +++ b/InvenTree/company/test_views.py @@ -1,4 +1,4 @@ -""" Unit tests for Company views (see views.py) """ +"""Unit tests for Company views (see views.py)""" from django.urls import reverse @@ -20,38 +20,31 @@ class CompanyViewTestBase(InvenTreeTestCase): class CompanyViewTest(CompanyViewTestBase): - """ - Tests for various 'Company' views - """ + """Tests for various 'Company' views.""" def test_company_index(self): - """ Test the company index """ - + """Test the company index.""" response = self.client.get(reverse('company-index')) self.assertEqual(response.status_code, 200) def test_manufacturer_index(self): - """ Test the manufacturer index """ - + """Test the manufacturer index.""" response = self.client.get(reverse('manufacturer-index')) self.assertEqual(response.status_code, 200) def test_customer_index(self): - """ Test the customer index """ - + """Test the customer index.""" response = self.client.get(reverse('customer-index')) self.assertEqual(response.status_code, 200) def test_manufacturer_part_detail_view(self): - """ Test the manufacturer part detail view """ - + """Test the manufacturer part detail view.""" response = self.client.get(reverse('manufacturer-part-detail', kwargs={'pk': 1})) self.assertEqual(response.status_code, 200) self.assertContains(response, 'MPN123') def test_supplier_part_detail_view(self): - """ Test the supplier part detail view """ - + """Test the supplier part detail view.""" response = self.client.get(reverse('supplier-part-detail', kwargs={'pk': 10})) self.assertEqual(response.status_code, 200) self.assertContains(response, 'MPN456-APPEL') diff --git a/InvenTree/company/tests.py b/InvenTree/company/tests.py index 008ac066b2..9337f4a0fb 100644 --- a/InvenTree/company/tests.py +++ b/InvenTree/company/tests.py @@ -81,8 +81,7 @@ class CompanySimpleTest(TestCase): self.assertEqual(self.zergm312.price_breaks.count(), 2) def test_quantity_pricing(self): - """ Simple test for quantity pricing """ - + """Simple test for quantity pricing.""" p = self.acme0001.get_price self.assertEqual(p(1), 10) self.assertEqual(p(4), 40) @@ -116,10 +115,7 @@ class CompanySimpleTest(TestCase): self.assertIsNotNone(m3x12.get_price_info(50)) def test_currency_validation(self): - """ - Test validation for currency selection - """ - + """Test validation for currency selection.""" # Create a company with a valid currency code (should pass) company = Company.objects.create( name='Test', diff --git a/InvenTree/company/urls.py b/InvenTree/company/urls.py index a7b9584c54..71adc1be32 100644 --- a/InvenTree/company/urls.py +++ b/InvenTree/company/urls.py @@ -1,6 +1,4 @@ -""" -URL lookup for Company app -""" +"""URL lookup for Company app.""" from django.urls import include, re_path diff --git a/InvenTree/company/views.py b/InvenTree/company/views.py index 6a21d1e57a..178c007582 100644 --- a/InvenTree/company/views.py +++ b/InvenTree/company/views.py @@ -1,6 +1,4 @@ -""" -Django views for interacting with Company app -""" +"""Django views for interacting with Company app.""" import io @@ -20,8 +18,7 @@ from .models import Company, ManufacturerPart, SupplierPart class CompanyIndex(InvenTreeRoleMixin, ListView): - """ View for displaying list of companies - """ + """View for displaying list of companies.""" model = Company template_name = 'company/index.html' @@ -80,7 +77,7 @@ class CompanyIndex(InvenTreeRoleMixin, ListView): return ctx def get_queryset(self): - """ Retrieve the Company queryset based on HTTP request parameters. + """Retrieve the Company queryset based on HTTP request parameters. - supplier: Filter by supplier - customer: Filter by customer @@ -97,7 +94,7 @@ class CompanyIndex(InvenTreeRoleMixin, ListView): class CompanyDetail(InvenTreePluginViewMixin, DetailView): - """ Detail view for Company object """ + """Detail view for Company object.""" context_obect_name = 'company' template_name = 'company/detail.html' queryset = Company.objects.all() @@ -111,9 +108,7 @@ class CompanyDetail(InvenTreePluginViewMixin, DetailView): class CompanyImageDownloadFromURL(AjaxUpdateView): - """ - View for downloading an image from a provided URL - """ + """View for downloading an image from a provided URL.""" model = Company ajax_template_name = 'image_download.html' @@ -121,9 +116,7 @@ class CompanyImageDownloadFromURL(AjaxUpdateView): ajax_form_title = _('Download Image') def validate(self, company, form): - """ - Validate that the image data are correct - """ + """Validate that the image data are correct.""" # First ensure that the normal validation routines pass if not form.is_valid(): return @@ -167,9 +160,7 @@ class CompanyImageDownloadFromURL(AjaxUpdateView): return def save(self, company, form, **kwargs): - """ - Save the downloaded image to the company - """ + """Save the downloaded image to the company.""" fmt = self.image.format if not fmt: @@ -189,7 +180,7 @@ class CompanyImageDownloadFromURL(AjaxUpdateView): class ManufacturerPartDetail(InvenTreePluginViewMixin, DetailView): - """ Detail view for ManufacturerPart """ + """Detail view for ManufacturerPart.""" model = ManufacturerPart template_name = 'company/manufacturer_part_detail.html' context_object_name = 'part' @@ -203,7 +194,7 @@ class ManufacturerPartDetail(InvenTreePluginViewMixin, DetailView): class SupplierPartDetail(InvenTreePluginViewMixin, DetailView): - """ Detail view for SupplierPart """ + """Detail view for SupplierPart.""" model = SupplierPart template_name = 'company/supplier_part_detail.html' context_object_name = 'part' diff --git a/InvenTree/label/api.py b/InvenTree/label/api.py index cb7ea12598..af2d6e31ef 100644 --- a/InvenTree/label/api.py +++ b/InvenTree/label/api.py @@ -24,9 +24,7 @@ from .serializers import (PartLabelSerializer, StockItemLabelSerializer, class LabelListView(generics.ListAPIView): - """ - Generic API class for label templates - """ + """Generic API class for label templates.""" filter_backends = [ DjangoFilterBackend, @@ -44,14 +42,10 @@ class LabelListView(generics.ListAPIView): class LabelPrintMixin: - """ - Mixin for printing labels - """ + """Mixin for printing labels.""" def get_plugin(self, request): - """ - Return the label printing plugin associated with this request. - This is provided in the url, e.g. ?plugin=myprinter + """Return the label printing plugin associated with this request. This is provided in the url, e.g. ?plugin=myprinter. Requires: - settings.PLUGINS_ENABLED is True @@ -59,7 +53,6 @@ class LabelPrintMixin: - matching plugin implements the 'labels' mixin - matching plugin is enabled """ - if not settings.PLUGINS_ENABLED: return None # pragma: no cover @@ -83,10 +76,7 @@ class LabelPrintMixin: raise NotFound(f"Plugin '{plugin_key}' not found") def print(self, request, items_to_print): - """ - Print this label template against a number of pre-validated items - """ - + """Print this label template against a number of pre-validated items.""" # Check the request to determine if the user has selected a label printing plugin plugin = self.get_plugin(request) @@ -123,25 +113,20 @@ class LabelPrintMixin: if plugin is not None: """ - Label printing is to be handled by a plugin, - rather than being exported to PDF. + Label printing is to be handled by a plugin, rather than being exported to PDF. In this case, we do the following: - Individually generate each label, exporting as an image file - Pass all the images through to the label printing plugin - Return a JSON response indicating that the printing has been offloaded - """ # Label instance label_instance = self.get_object() for output in outputs: - """ - For each output, we generate a temporary image file, - which will then get sent to the printer - """ + """For each output, we generate a temporary image file, which will then get sent to the printer.""" # Generate a png image at 300dpi (img_data, w, h) = output.get_document().write_png(resolution=300) @@ -166,20 +151,14 @@ class LabelPrintMixin: }) elif debug_mode: - """ - Contatenate all rendered templates into a single HTML string, - and return the string as a HTML response. - """ + """Contatenate all rendered templates into a single HTML string, and return the string as a HTML response.""" html = "\n".join(outputs) return HttpResponse(html) else: - """ - Concatenate all rendered pages into a single PDF object, - and return the resulting document! - """ + """Concatenate all rendered pages into a single PDF object, and return the resulting document!""" pages = [] @@ -205,15 +184,10 @@ class LabelPrintMixin: class StockItemLabelMixin: - """ - Mixin for extracting stock items from query params - """ + """Mixin for extracting stock items from query params.""" def get_items(self): - """ - Return a list of requested stock items - """ - + """Return a list of requested stock items.""" items = [] params = self.request.query_params @@ -238,25 +212,20 @@ class StockItemLabelMixin: class StockItemLabelList(LabelListView, StockItemLabelMixin): - """ - API endpoint for viewing list of StockItemLabel objects. + """API endpoint for viewing list of StockItemLabel objects. Filterable by: - enabled: Filter by enabled / disabled status - item: Filter by single stock item - items: Filter by list of stock items - """ queryset = StockItemLabel.objects.all() serializer_class = StockItemLabelSerializer def filter_queryset(self, queryset): - """ - Filter the StockItem label queryset. - """ - + """Filter the StockItem label queryset.""" queryset = super().filter_queryset(queryset) # List of StockItem objects to match against @@ -265,9 +234,7 @@ class StockItemLabelList(LabelListView, StockItemLabelMixin): # We wish to filter by stock items if len(items) > 0: """ - At this point, we are basically forced to be inefficient, - as we need to compare the 'filters' string of each label, - and see if it matches against each of the requested items. + At this point, we are basically forced to be inefficient, as we need to compare the 'filters' string of each label, and see if it matches against each of the requested items. TODO: In the future, if this becomes excessively slow, it will need to be readdressed. @@ -311,42 +278,30 @@ class StockItemLabelList(LabelListView, StockItemLabelMixin): class StockItemLabelDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for a single StockItemLabel object - """ + """API endpoint for a single StockItemLabel object.""" queryset = StockItemLabel.objects.all() serializer_class = StockItemLabelSerializer class StockItemLabelPrint(generics.RetrieveAPIView, StockItemLabelMixin, LabelPrintMixin): - """ - API endpoint for printing a StockItemLabel object - """ + """API endpoint for printing a StockItemLabel object.""" queryset = StockItemLabel.objects.all() serializer_class = StockItemLabelSerializer def get(self, request, *args, **kwargs): - """ - Check if valid stock item(s) have been provided. - """ - + """Check if valid stock item(s) have been provided.""" items = self.get_items() return self.print(request, items) class StockLocationLabelMixin: - """ - Mixin for extracting stock locations from query params - """ + """Mixin for extracting stock locations from query params.""" def get_locations(self): - """ - Return a list of requested stock locations - """ - + """Return a list of requested stock locations.""" locations = [] params = self.request.query_params @@ -371,8 +326,7 @@ class StockLocationLabelMixin: class StockLocationLabelList(LabelListView, StockLocationLabelMixin): - """ - API endpoint for viewiing list of StockLocationLabel objects. + """API endpoint for viewiing list of StockLocationLabel objects. Filterable by: @@ -385,10 +339,7 @@ class StockLocationLabelList(LabelListView, StockLocationLabelMixin): serializer_class = StockLocationLabelSerializer def filter_queryset(self, queryset): - """ - Filter the StockLocationLabel queryset - """ - + """Filter the StockLocationLabel queryset.""" queryset = super().filter_queryset(queryset) # List of StockLocation objects to match against @@ -397,9 +348,7 @@ class StockLocationLabelList(LabelListView, StockLocationLabelMixin): # We wish to filter by stock location(s) if len(locations) > 0: """ - At this point, we are basically forced to be inefficient, - as we need to compare the 'filters' string of each label, - and see if it matches against each of the requested items. + At this point, we are basically forced to be inefficient, as we need to compare the 'filters' string of each label, and see if it matches against each of the requested items. TODO: In the future, if this becomes excessively slow, it will need to be readdressed. @@ -443,18 +392,14 @@ class StockLocationLabelList(LabelListView, StockLocationLabelMixin): class StockLocationLabelDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for a single StockLocationLabel object - """ + """API endpoint for a single StockLocationLabel object.""" queryset = StockLocationLabel.objects.all() serializer_class = StockLocationLabelSerializer class StockLocationLabelPrint(generics.RetrieveAPIView, StockLocationLabelMixin, LabelPrintMixin): - """ - API endpoint for printing a StockLocationLabel object - """ + """API endpoint for printing a StockLocationLabel object.""" queryset = StockLocationLabel.objects.all() seiralizer_class = StockLocationLabelSerializer @@ -467,15 +412,10 @@ class StockLocationLabelPrint(generics.RetrieveAPIView, StockLocationLabelMixin, class PartLabelMixin: - """ - Mixin for extracting Part objects from query parameters - """ + """Mixin for extracting Part objects from query parameters.""" def get_parts(self): - """ - Return a list of requested Part objects - """ - + """Return a list of requested Part objects.""" parts = [] params = self.request.query_params @@ -498,9 +438,7 @@ class PartLabelMixin: class PartLabelList(LabelListView, PartLabelMixin): - """ - API endpoint for viewing list of PartLabel objects - """ + """API endpoint for viewing list of PartLabel objects.""" queryset = PartLabel.objects.all() serializer_class = PartLabelSerializer @@ -546,27 +484,20 @@ class PartLabelList(LabelListView, PartLabelMixin): class PartLabelDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for a single PartLabel object - """ + """API endpoint for a single PartLabel object.""" queryset = PartLabel.objects.all() serializer_class = PartLabelSerializer class PartLabelPrint(generics.RetrieveAPIView, PartLabelMixin, LabelPrintMixin): - """ - API endpoint for printing a PartLabel object - """ + """API endpoint for printing a PartLabel object.""" queryset = PartLabel.objects.all() serializer_class = PartLabelSerializer def get(self, request, *args, **kwargs): - """ - Check if valid part(s) have been provided - """ - + """Check if valid part(s) have been provided.""" parts = self.get_parts() return self.print(request, parts) diff --git a/InvenTree/label/apps.py b/InvenTree/label/apps.py index b26b7fb692..4272efa35c 100644 --- a/InvenTree/label/apps.py +++ b/InvenTree/label/apps.py @@ -14,10 +14,7 @@ logger = logging.getLogger("inventree") def hashFile(filename): - """ - Calculate the MD5 hash of a file - """ - + """Calculate the MD5 hash of a file.""" md5 = hashlib.md5() with open(filename, 'rb') as f: @@ -31,17 +28,12 @@ class LabelConfig(AppConfig): name = 'label' def ready(self): - """ - This function is called whenever the label app is loaded - """ - + """This function is called whenever the label app is loaded.""" if canAppAccessDatabase(): self.create_labels() # pragma: no cover def create_labels(self): - """ - Create all default templates - """ + """Create all default templates.""" # Test if models are ready try: from .models import StockLocationLabel @@ -56,11 +48,7 @@ class LabelConfig(AppConfig): self.create_part_labels() def create_stock_item_labels(self): - """ - Create database entries for the default StockItemLabel templates, - if they do not already exist - """ - + """Create database entries for the default StockItemLabel templates, if they do not already exist.""" from .models import StockItemLabel src_dir = os.path.join( @@ -139,11 +127,7 @@ class LabelConfig(AppConfig): ) def create_stock_location_labels(self): - """ - Create database entries for the default StockItemLocation templates, - if they do not already exist - """ - + """Create database entries for the default StockItemLocation templates, if they do not already exist.""" from .models import StockLocationLabel src_dir = os.path.join( @@ -229,11 +213,7 @@ class LabelConfig(AppConfig): ) def create_part_labels(self): - """ - Create database entries for the default PartLabel templates, - if they do not already exist. - """ - + """Create database entries for the default PartLabel templates, if they do not already exist.""" from .models import PartLabel src_dir = os.path.join( diff --git a/InvenTree/label/models.py b/InvenTree/label/models.py index 4da42d73a9..86160dbf89 100644 --- a/InvenTree/label/models.py +++ b/InvenTree/label/models.py @@ -1,6 +1,4 @@ -""" -Label printing models -""" +"""Label printing models.""" import datetime import logging @@ -32,8 +30,7 @@ logger = logging.getLogger("inventree") def rename_label(instance, filename): - """ Place the label file into the correct subdirectory """ - + """Place the label file into the correct subdirectory.""" filename = os.path.basename(filename) return os.path.join('label', 'template', instance.SUBDIR, filename) @@ -61,9 +58,7 @@ def validate_part_filters(filters): class WeasyprintLabelMixin(WeasyTemplateResponseMixin): - """ - Class for rendering a label to a PDF - """ + """Class for rendering a label to a PDF.""" pdf_filename = 'label.pdf' pdf_attachment = True @@ -76,9 +71,7 @@ class WeasyprintLabelMixin(WeasyTemplateResponseMixin): class LabelTemplate(models.Model): - """ - Base class for generic, filterable labels. - """ + """Base class for generic, filterable labels.""" class Meta: abstract = True @@ -150,11 +143,10 @@ class LabelTemplate(models.Model): @property def template_name(self): - """ - Returns the file system path to the template file. + """Returns the file system path to the template file. + Required for passing the file to an external process """ - template = self.label.name template = template.replace('/', os.path.sep) template = template.replace('\\', os.path.sep) @@ -164,19 +156,14 @@ class LabelTemplate(models.Model): return template def get_context_data(self, request): - """ - Supply custom context data to the template for rendering. + """Supply custom context data to the template for rendering. Note: Override this in any subclass """ - return {} # pragma: no cover def generate_filename(self, request, **kwargs): - """ - Generate a filename for this label - """ - + """Generate a filename for this label.""" template_string = Template(self.filename_pattern) ctx = self.context(request) @@ -186,10 +173,7 @@ class LabelTemplate(models.Model): return template_string.render(context) def context(self, request): - """ - Provides context data to the template. - """ - + """Provides context data to the template.""" context = self.get_context_data(request) # Add "basic" context data which gets passed to every label @@ -204,21 +188,17 @@ class LabelTemplate(models.Model): return context def render_as_string(self, request, **kwargs): - """ - Render the label to a HTML string + """Render the label to a HTML string. Useful for debug mode (viewing generated code) """ - return render_to_string(self.template_name, self.context(request), request) def render(self, request, **kwargs): - """ - Render the label template to a PDF file + """Render the label template to a PDF file. Uses django-weasyprint plugin to render HTML template """ - wp = WeasyprintLabelMixin( request, self.template_name, @@ -235,9 +215,7 @@ class LabelTemplate(models.Model): class StockItemLabel(LabelTemplate): - """ - Template for printing StockItem labels - """ + """Template for printing StockItem labels.""" @staticmethod def get_api_url(): @@ -255,10 +233,7 @@ class StockItemLabel(LabelTemplate): ) def get_context_data(self, request): - """ - Generate context data for each provided StockItem - """ - + """Generate context data for each provided StockItem.""" stock_item = self.object_to_print return { @@ -279,9 +254,7 @@ class StockItemLabel(LabelTemplate): class StockLocationLabel(LabelTemplate): - """ - Template for printing StockLocation labels - """ + """Template for printing StockLocation labels.""" @staticmethod def get_api_url(): @@ -298,10 +271,7 @@ class StockLocationLabel(LabelTemplate): ) def get_context_data(self, request): - """ - Generate context data for each provided StockLocation - """ - + """Generate context data for each provided StockLocation.""" location = self.object_to_print return { @@ -311,9 +281,7 @@ class StockLocationLabel(LabelTemplate): class PartLabel(LabelTemplate): - """ - Template for printing Part labels - """ + """Template for printing Part labels.""" @staticmethod def get_api_url(): @@ -331,10 +299,7 @@ class PartLabel(LabelTemplate): ) def get_context_data(self, request): - """ - Generate context data for each provided Part object - """ - + """Generate context data for each provided Part object.""" part = self.object_to_print return { diff --git a/InvenTree/label/serializers.py b/InvenTree/label/serializers.py index 5428424572..995c41fdc5 100644 --- a/InvenTree/label/serializers.py +++ b/InvenTree/label/serializers.py @@ -5,9 +5,7 @@ from .models import PartLabel, StockItemLabel, StockLocationLabel class StockItemLabelSerializer(InvenTreeModelSerializer): - """ - Serializes a StockItemLabel object. - """ + """Serializes a StockItemLabel object.""" label = InvenTreeAttachmentSerializerField(required=True) @@ -24,9 +22,7 @@ class StockItemLabelSerializer(InvenTreeModelSerializer): class StockLocationLabelSerializer(InvenTreeModelSerializer): - """ - Serializes a StockLocationLabel object - """ + """Serializes a StockLocationLabel object.""" label = InvenTreeAttachmentSerializerField(required=True) @@ -43,9 +39,7 @@ class StockLocationLabelSerializer(InvenTreeModelSerializer): class PartLabelSerializer(InvenTreeModelSerializer): - """ - Serializes a PartLabel object - """ + """Serializes a PartLabel object.""" label = InvenTreeAttachmentSerializerField(required=True) diff --git a/InvenTree/label/test_api.py b/InvenTree/label/test_api.py index d9b0bafc9a..39e898cb6f 100644 --- a/InvenTree/label/test_api.py +++ b/InvenTree/label/test_api.py @@ -6,9 +6,7 @@ from InvenTree.api_tester import InvenTreeAPITestCase class TestReportTests(InvenTreeAPITestCase): - """ - Tests for the StockItem TestReport templates - """ + """Tests for the StockItem TestReport templates.""" fixtures = [ 'category', diff --git a/InvenTree/label/tests.py b/InvenTree/label/tests.py index f94efafb84..2124b17202 100644 --- a/InvenTree/label/tests.py +++ b/InvenTree/label/tests.py @@ -1,4 +1,4 @@ -# Tests for labels +"""Tests for labels""" import os @@ -30,10 +30,7 @@ class LabelTest(InvenTreeAPITestCase): apps.get_app_config('label').create_labels() def test_default_labels(self): - """ - Test that the default label templates are copied across - """ - + """Test that the default label templates are copied across.""" labels = StockItemLabel.objects.all() self.assertTrue(labels.count() > 0) @@ -43,10 +40,7 @@ class LabelTest(InvenTreeAPITestCase): self.assertTrue(labels.count() > 0) def test_default_files(self): - """ - Test that label files exist in the MEDIA directory - """ - + """Test that label files exist in the MEDIA directory.""" item_dir = os.path.join( settings.MEDIA_ROOT, 'label', @@ -70,10 +64,7 @@ class LabelTest(InvenTreeAPITestCase): self.assertTrue(len(files) > 0) def test_filters(self): - """ - Test the label filters - """ - + """Test the label filters.""" filter_string = "part__pk=10" filters = validateFilterString(filter_string, model=StockItem) @@ -86,8 +77,7 @@ class LabelTest(InvenTreeAPITestCase): validateFilterString(bad_filter_string, model=StockItem) def test_label_rendering(self): - """Test label rendering""" - + """Test label rendering.""" labels = PartLabel.objects.all() part = Part.objects.first() diff --git a/InvenTree/order/__init__.py b/InvenTree/order/__init__.py index 464c173210..0ef70f99b7 100644 --- a/InvenTree/order/__init__.py +++ b/InvenTree/order/__init__.py @@ -1 +1 @@ -"""The Order module is responsible for managing Orders""" +"""The Order module is responsible for managing Orders.""" diff --git a/InvenTree/order/admin.py b/InvenTree/order/admin.py index a46fe62532..126dcf4c01 100644 --- a/InvenTree/order/admin.py +++ b/InvenTree/order/admin.py @@ -91,9 +91,7 @@ class SalesOrderAdmin(ImportExportModelAdmin): class PurchaseOrderResource(ModelResource): - """ - Class for managing import / export of PurchaseOrder data - """ + """Class for managing import / export of PurchaseOrder data.""" # Add number of line items line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True) @@ -111,7 +109,7 @@ class PurchaseOrderResource(ModelResource): class PurchaseOrderLineItemResource(ModelResource): - """ Class for managing import / export of PurchaseOrderLineItem data """ + """Class for managing import / export of PurchaseOrderLineItem data.""" part_name = Field(attribute='part__part__name', readonly=True) @@ -129,16 +127,14 @@ class PurchaseOrderLineItemResource(ModelResource): class PurchaseOrderExtraLineResource(ModelResource): - """ Class for managing import / export of PurchaseOrderExtraLine data """ + """Class for managing import / export of PurchaseOrderExtraLine data.""" class Meta(GeneralExtraLineMeta): model = PurchaseOrderExtraLine class SalesOrderResource(ModelResource): - """ - Class for managing import / export of SalesOrder data - """ + """Class for managing import / export of SalesOrder data.""" # Add number of line items line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True) @@ -156,9 +152,7 @@ class SalesOrderResource(ModelResource): class SalesOrderLineItemResource(ModelResource): - """ - Class for managing import / export of SalesOrderLineItem data - """ + """Class for managing import / export of SalesOrderLineItem data.""" part_name = Field(attribute='part__name', readonly=True) @@ -169,11 +163,10 @@ class SalesOrderLineItemResource(ModelResource): fulfilled = Field(attribute='fulfilled_quantity', readonly=True) def dehydrate_sale_price(self, item): - """ - Return a string value of the 'sale_price' field, rather than the 'Money' object. + """Return a string value of the 'sale_price' field, rather than the 'Money' object. + Ref: https://github.com/inventree/InvenTree/issues/2207 """ - if item.sale_price: return str(item.sale_price) else: @@ -187,7 +180,7 @@ class SalesOrderLineItemResource(ModelResource): class SalesOrderExtraLineResource(ModelResource): - """ Class for managing import / export of SalesOrderExtraLine data """ + """Class for managing import / export of SalesOrderExtraLine data.""" class Meta(GeneralExtraLineMeta): model = SalesOrderExtraLine diff --git a/InvenTree/order/api.py b/InvenTree/order/api.py index e6e6767edb..ba86bb8e93 100644 --- a/InvenTree/order/api.py +++ b/InvenTree/order/api.py @@ -1,6 +1,4 @@ -""" -JSON API for the Order app -""" +"""JSON API for the Order app.""" from django.db.models import F, Q from django.urls import include, path, re_path @@ -24,9 +22,7 @@ from users.models import Owner class GeneralExtraLineList: - """ - General template for ExtraLine API classes - """ + """General template for ExtraLine API classes.""" def get_serializer(self, *args, **kwargs): try: @@ -76,17 +72,12 @@ class GeneralExtraLineList: class PurchaseOrderFilter(rest_filters.FilterSet): - """ - Custom API filters for the PurchaseOrderList endpoint - """ + """Custom API filters for the PurchaseOrderList endpoint.""" assigned_to_me = rest_filters.BooleanFilter(label='assigned_to_me', method='filter_assigned_to_me') def filter_assigned_to_me(self, queryset, name, value): - """ - Filter by orders which are assigned to the current user - """ - + """Filter by orders which are assigned to the current user.""" value = str2bool(value) # Work out who "me" is! @@ -107,7 +98,7 @@ class PurchaseOrderFilter(rest_filters.FilterSet): class PurchaseOrderList(APIDownloadMixin, generics.ListCreateAPIView): - """ API endpoint for accessing a list of PurchaseOrder objects + """API endpoint for accessing a list of PurchaseOrder objects. - GET: Return list of PurchaseOrder objects (with filters) - POST: Create a new PurchaseOrder object @@ -118,9 +109,7 @@ class PurchaseOrderList(APIDownloadMixin, generics.ListCreateAPIView): filterset_class = PurchaseOrderFilter def create(self, request, *args, **kwargs): - """ - Save user information on create - """ + """Save user information on create.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) @@ -260,7 +249,7 @@ class PurchaseOrderList(APIDownloadMixin, generics.ListCreateAPIView): class PurchaseOrderDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of a PurchaseOrder object """ + """API endpoint for detail view of a PurchaseOrder object.""" queryset = models.PurchaseOrder.objects.all() serializer_class = serializers.PurchaseOrderSerializer @@ -292,11 +281,10 @@ class PurchaseOrderDetail(generics.RetrieveUpdateDestroyAPIView): class PurchaseOrderContextMixin: - """ Mixin to add purchase order object as serializer context variable """ + """Mixin to add purchase order object as serializer context variable.""" def get_serializer_context(self): - """ Add the PurchaseOrder object to the serializer context """ - + """Add the PurchaseOrder object to the serializer context.""" context = super().get_serializer_context() # Pass the purchase order through to the serializer for validation @@ -311,8 +299,7 @@ class PurchaseOrderContextMixin: class PurchaseOrderCancel(PurchaseOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to 'cancel' a purchase order. + """API endpoint to 'cancel' a purchase order. The purchase order must be in a state which can be cancelled """ @@ -323,9 +310,7 @@ class PurchaseOrderCancel(PurchaseOrderContextMixin, generics.CreateAPIView): class PurchaseOrderComplete(PurchaseOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to 'complete' a purchase order - """ + """API endpoint to 'complete' a purchase order.""" queryset = models.PurchaseOrder.objects.all() @@ -333,9 +318,7 @@ class PurchaseOrderComplete(PurchaseOrderContextMixin, generics.CreateAPIView): class PurchaseOrderIssue(PurchaseOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to 'complete' a purchase order - """ + """API endpoint to 'complete' a purchase order.""" queryset = models.PurchaseOrder.objects.all() @@ -343,7 +326,7 @@ class PurchaseOrderIssue(PurchaseOrderContextMixin, generics.CreateAPIView): class PurchaseOrderMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating PurchaseOrder metadata""" + """API endpoint for viewing / updating PurchaseOrder metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(models.PurchaseOrder, *args, **kwargs) @@ -352,8 +335,7 @@ class PurchaseOrderMetadata(generics.RetrieveUpdateAPIView): class PurchaseOrderReceive(PurchaseOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to receive stock items against a purchase order. + """API endpoint to receive stock items against a purchase order. - The purchase order is specified in the URL. - Items to receive are specified as a list called "items" with the following options: @@ -370,9 +352,7 @@ class PurchaseOrderReceive(PurchaseOrderContextMixin, generics.CreateAPIView): class PurchaseOrderLineItemFilter(rest_filters.FilterSet): - """ - Custom filters for the PurchaseOrderLineItemList endpoint - """ + """Custom filters for the PurchaseOrderLineItemList endpoint.""" class Meta: model = models.PurchaseOrderLineItem @@ -384,10 +364,7 @@ class PurchaseOrderLineItemFilter(rest_filters.FilterSet): pending = rest_filters.BooleanFilter(label='pending', method='filter_pending') def filter_pending(self, queryset, name, value): - """ - Filter by "pending" status (order status = pending) - """ - + """Filter by "pending" status (order status = pending)""" value = str2bool(value) if value: @@ -402,12 +379,10 @@ class PurchaseOrderLineItemFilter(rest_filters.FilterSet): received = rest_filters.BooleanFilter(label='received', method='filter_received') def filter_received(self, queryset, name, value): - """ - Filter by lines which are "received" (or "not" received) + """Filter by lines which are "received" (or "not" received) A line is considered "received" when received >= quantity """ - value = str2bool(value) q = Q(received__gte=F('quantity')) @@ -422,7 +397,7 @@ class PurchaseOrderLineItemFilter(rest_filters.FilterSet): class PurchaseOrderLineItemList(APIDownloadMixin, generics.ListCreateAPIView): - """ API endpoint for accessing a list of PurchaseOrderLineItem objects + """API endpoint for accessing a list of PurchaseOrderLineItem objects. - GET: Return a list of PurchaseOrder Line Item objects - POST: Create a new PurchaseOrderLineItem object @@ -453,10 +428,7 @@ class PurchaseOrderLineItemList(APIDownloadMixin, generics.ListCreateAPIView): return self.serializer_class(*args, **kwargs) def filter_queryset(self, queryset): - """ - Additional filtering options - """ - + """Additional filtering options.""" params = self.request.query_params queryset = super().filter_queryset(queryset) @@ -530,9 +502,7 @@ class PurchaseOrderLineItemList(APIDownloadMixin, generics.ListCreateAPIView): class PurchaseOrderLineItemDetail(generics.RetrieveUpdateDestroyAPIView): - """ - Detail API endpoint for PurchaseOrderLineItem object - """ + """Detail API endpoint for PurchaseOrderLineItem object.""" queryset = models.PurchaseOrderLineItem.objects.all() serializer_class = serializers.PurchaseOrderLineItemSerializer @@ -547,25 +517,21 @@ class PurchaseOrderLineItemDetail(generics.RetrieveUpdateDestroyAPIView): class PurchaseOrderExtraLineList(GeneralExtraLineList, generics.ListCreateAPIView): - """ - API endpoint for accessing a list of PurchaseOrderExtraLine objects. - """ + """API endpoint for accessing a list of PurchaseOrderExtraLine objects.""" queryset = models.PurchaseOrderExtraLine.objects.all() serializer_class = serializers.PurchaseOrderExtraLineSerializer class PurchaseOrderExtraLineDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of a PurchaseOrderExtraLine object """ + """API endpoint for detail view of a PurchaseOrderExtraLine object.""" queryset = models.PurchaseOrderExtraLine.objects.all() serializer_class = serializers.PurchaseOrderExtraLineSerializer class SalesOrderAttachmentList(generics.ListCreateAPIView, AttachmentMixin): - """ - API endpoint for listing (and creating) a SalesOrderAttachment (file upload) - """ + """API endpoint for listing (and creating) a SalesOrderAttachment (file upload)""" queryset = models.SalesOrderAttachment.objects.all() serializer_class = serializers.SalesOrderAttachmentSerializer @@ -580,17 +546,14 @@ class SalesOrderAttachmentList(generics.ListCreateAPIView, AttachmentMixin): class SalesOrderAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin): - """ - Detail endpoint for SalesOrderAttachment - """ + """Detail endpoint for SalesOrderAttachment.""" queryset = models.SalesOrderAttachment.objects.all() serializer_class = serializers.SalesOrderAttachmentSerializer class SalesOrderList(APIDownloadMixin, generics.ListCreateAPIView): - """ - API endpoint for accessing a list of SalesOrder objects. + """API endpoint for accessing a list of SalesOrder objects. - GET: Return list of SalesOrder objects (with filters) - POST: Create a new SalesOrder @@ -600,9 +563,7 @@ class SalesOrderList(APIDownloadMixin, generics.ListCreateAPIView): serializer_class = serializers.SalesOrderSerializer def create(self, request, *args, **kwargs): - """ - Save user information on create - """ + """Save user information on create.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) @@ -648,10 +609,7 @@ class SalesOrderList(APIDownloadMixin, generics.ListCreateAPIView): return DownloadFile(filedata, filename) def filter_queryset(self, queryset): - """ - Perform custom filtering operations on the SalesOrder queryset. - """ - + """Perform custom filtering operations on the SalesOrder queryset.""" queryset = super().filter_queryset(queryset) params = self.request.query_params @@ -739,9 +697,7 @@ class SalesOrderList(APIDownloadMixin, generics.ListCreateAPIView): class SalesOrderDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for detail view of a SalesOrder object. - """ + """API endpoint for detail view of a SalesOrder object.""" queryset = models.SalesOrder.objects.all() serializer_class = serializers.SalesOrderSerializer @@ -769,9 +725,7 @@ class SalesOrderDetail(generics.RetrieveUpdateDestroyAPIView): class SalesOrderLineItemFilter(rest_filters.FilterSet): - """ - Custom filters for SalesOrderLineItemList endpoint - """ + """Custom filters for SalesOrderLineItemList endpoint.""" class Meta: model = models.SalesOrderLineItem @@ -783,12 +737,10 @@ class SalesOrderLineItemFilter(rest_filters.FilterSet): completed = rest_filters.BooleanFilter(label='completed', method='filter_completed') def filter_completed(self, queryset, name, value): - """ - Filter by lines which are "completed" + """Filter by lines which are "completed". A line is completed when shipped >= quantity """ - value = str2bool(value) q = Q(shipped__gte=F('quantity')) @@ -802,9 +754,7 @@ class SalesOrderLineItemFilter(rest_filters.FilterSet): class SalesOrderLineItemList(generics.ListCreateAPIView): - """ - API endpoint for accessing a list of SalesOrderLineItem objects. - """ + """API endpoint for accessing a list of SalesOrderLineItem objects.""" queryset = models.SalesOrderLineItem.objects.all() serializer_class = serializers.SalesOrderLineItemSerializer @@ -866,30 +816,28 @@ class SalesOrderLineItemList(generics.ListCreateAPIView): class SalesOrderExtraLineList(GeneralExtraLineList, generics.ListCreateAPIView): - """ - API endpoint for accessing a list of SalesOrderExtraLine objects. - """ + """API endpoint for accessing a list of SalesOrderExtraLine objects.""" queryset = models.SalesOrderExtraLine.objects.all() serializer_class = serializers.SalesOrderExtraLineSerializer class SalesOrderExtraLineDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of a SalesOrderExtraLine object """ + """API endpoint for detail view of a SalesOrderExtraLine object.""" queryset = models.SalesOrderExtraLine.objects.all() serializer_class = serializers.SalesOrderExtraLineSerializer class SalesOrderLineItemDetail(generics.RetrieveUpdateDestroyAPIView): - """ API endpoint for detail view of a SalesOrderLineItem object """ + """API endpoint for detail view of a SalesOrderLineItem object.""" queryset = models.SalesOrderLineItem.objects.all() serializer_class = serializers.SalesOrderLineItemSerializer class SalesOrderContextMixin: - """ Mixin to add sales order object as serializer context variable """ + """Mixin to add sales order object as serializer context variable.""" def get_serializer_context(self): @@ -912,16 +860,14 @@ class SalesOrderCancel(SalesOrderContextMixin, generics.CreateAPIView): class SalesOrderComplete(SalesOrderContextMixin, generics.CreateAPIView): - """ - API endpoint for manually marking a SalesOrder as "complete". - """ + """API endpoint for manually marking a SalesOrder as "complete".""" queryset = models.SalesOrder.objects.all() serializer_class = serializers.SalesOrderCompleteSerializer class SalesOrderMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating SalesOrder metadata""" + """API endpoint for viewing / updating SalesOrder metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(models.SalesOrder, *args, **kwargs) @@ -930,18 +876,14 @@ class SalesOrderMetadata(generics.RetrieveUpdateAPIView): class SalesOrderAllocateSerials(SalesOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to allocation stock items against a SalesOrder, - by specifying serial numbers. - """ + """API endpoint to allocation stock items against a SalesOrder, by specifying serial numbers.""" queryset = models.SalesOrder.objects.none() serializer_class = serializers.SalesOrderSerialAllocationSerializer class SalesOrderAllocate(SalesOrderContextMixin, generics.CreateAPIView): - """ - API endpoint to allocate stock items against a SalesOrder + """API endpoint to allocate stock items against a SalesOrder. - The SalesOrder is specified in the URL - See the SalesOrderShipmentAllocationSerializer class @@ -952,18 +894,14 @@ class SalesOrderAllocate(SalesOrderContextMixin, generics.CreateAPIView): class SalesOrderAllocationDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API endpoint for detali view of a SalesOrderAllocation object - """ + """API endpoint for detali view of a SalesOrderAllocation object.""" queryset = models.SalesOrderAllocation.objects.all() serializer_class = serializers.SalesOrderAllocationSerializer class SalesOrderAllocationList(generics.ListAPIView): - """ - API endpoint for listing SalesOrderAllocation objects - """ + """API endpoint for listing SalesOrderAllocation objects.""" queryset = models.SalesOrderAllocation.objects.all() serializer_class = serializers.SalesOrderAllocationSerializer @@ -1039,9 +977,7 @@ class SalesOrderAllocationList(generics.ListAPIView): class SalesOrderShipmentFilter(rest_filters.FilterSet): - """ - Custom filterset for the SalesOrderShipmentList endpoint - """ + """Custom filterset for the SalesOrderShipmentList endpoint.""" shipped = rest_filters.BooleanFilter(label='shipped', method='filter_shipped') @@ -1064,9 +1000,7 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet): class SalesOrderShipmentList(generics.ListCreateAPIView): - """ - API list endpoint for SalesOrderShipment model - """ + """API list endpoint for SalesOrderShipment model.""" queryset = models.SalesOrderShipment.objects.all() serializer_class = serializers.SalesOrderShipmentSerializer @@ -1078,27 +1012,20 @@ class SalesOrderShipmentList(generics.ListCreateAPIView): class SalesOrderShipmentDetail(generics.RetrieveUpdateDestroyAPIView): - """ - API detail endpooint for SalesOrderShipment model - """ + """API detail endpooint for SalesOrderShipment model.""" queryset = models.SalesOrderShipment.objects.all() serializer_class = serializers.SalesOrderShipmentSerializer class SalesOrderShipmentComplete(generics.CreateAPIView): - """ - API endpoint for completing (shipping) a SalesOrderShipment - """ + """API endpoint for completing (shipping) a SalesOrderShipment.""" queryset = models.SalesOrderShipment.objects.all() serializer_class = serializers.SalesOrderShipmentCompleteSerializer def get_serializer_context(self): - """ - Pass the request object to the serializer - """ - + """Pass the request object to the serializer.""" ctx = super().get_serializer_context() ctx['request'] = self.request @@ -1113,9 +1040,7 @@ class SalesOrderShipmentComplete(generics.CreateAPIView): class PurchaseOrderAttachmentList(generics.ListCreateAPIView, AttachmentMixin): - """ - API endpoint for listing (and creating) a PurchaseOrderAttachment (file upload) - """ + """API endpoint for listing (and creating) a PurchaseOrderAttachment (file upload)""" queryset = models.PurchaseOrderAttachment.objects.all() serializer_class = serializers.PurchaseOrderAttachmentSerializer @@ -1130,9 +1055,7 @@ class PurchaseOrderAttachmentList(generics.ListCreateAPIView, AttachmentMixin): class PurchaseOrderAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin): - """ - Detail endpoint for a PurchaseOrderAttachment - """ + """Detail endpoint for a PurchaseOrderAttachment.""" queryset = models.PurchaseOrderAttachment.objects.all() serializer_class = serializers.PurchaseOrderAttachmentSerializer diff --git a/InvenTree/order/forms.py b/InvenTree/order/forms.py index 2b06a92d00..c38f50ed56 100644 --- a/InvenTree/order/forms.py +++ b/InvenTree/order/forms.py @@ -1,6 +1,4 @@ -""" -Django Forms for interacting with Order objects -""" +"""Django Forms for interacting with Order objects.""" from django import forms from django.utils.translation import gettext_lazy as _ @@ -11,11 +9,10 @@ from InvenTree.helpers import clean_decimal class OrderMatchItemForm(MatchItemForm): - """ Override MatchItemForm fields """ + """Override MatchItemForm fields.""" def get_special_field(self, col_guess, row, file_manager): - """ Set special fields """ - + """Set special fields.""" # set quantity field if 'quantity' in col_guess.lower(): return forms.CharField( diff --git a/InvenTree/order/models.py b/InvenTree/order/models.py index aae8388b70..4fd45aa09f 100644 --- a/InvenTree/order/models.py +++ b/InvenTree/order/models.py @@ -1,4 +1,4 @@ -"""Order model definitions""" +"""Order model definitions.""" import logging import os @@ -43,7 +43,7 @@ logger = logging.getLogger('inventree') def get_next_po_number(): - """Returns the next available PurchaseOrder reference number""" + """Returns the next available PurchaseOrder reference number.""" if PurchaseOrder.objects.count() == 0: return '0001' @@ -69,7 +69,7 @@ def get_next_po_number(): def get_next_so_number(): - """Returns the next available SalesOrder reference number""" + """Returns the next available SalesOrder reference number.""" if SalesOrder.objects.count() == 0: return '0001' @@ -235,7 +235,7 @@ class PurchaseOrder(Order): @staticmethod def filterByDate(queryset, min_date, max_date): - """Filter by 'minimum and maximum date range' + """Filter by 'minimum and maximum date range'. - Specified as min_date, max_date - Both must be specified for filter to be applied @@ -330,8 +330,7 @@ class PurchaseOrder(Order): @transaction.atomic def add_line_item(self, supplier_part, quantity, group=True, reference='', purchase_price=None): - """Add a new line item to this purchase order. - This function will check that: + """Add a new line item to this purchase order. This function will check that: * The supplier part matches the supplier specified for this purchase order * The quantity is greater than zero @@ -381,7 +380,10 @@ class PurchaseOrder(Order): @transaction.atomic def place_order(self): - """Marks the PurchaseOrder as PLACED. Order must be currently PENDING.""" + """Marks the PurchaseOrder as PLACED. + + Order must be currently PENDING. + """ if self.status == PurchaseOrderStatus.PENDING: self.status = PurchaseOrderStatus.PLACED self.issue_date = datetime.now().date() @@ -391,7 +393,10 @@ class PurchaseOrder(Order): @transaction.atomic def complete_order(self): - """Marks the PurchaseOrder as COMPLETE. Order must be currently PLACED.""" + """Marks the PurchaseOrder as COMPLETE. + + Order must be currently PLACED. + """ if self.status == PurchaseOrderStatus.PLACED: self.status = PurchaseOrderStatus.COMPLETE self.complete_date = datetime.now().date() @@ -401,7 +406,7 @@ class PurchaseOrder(Order): @property def is_overdue(self): - """Returns True if this PurchaseOrder is "overdue" + """Returns True if this PurchaseOrder is "overdue". Makes use of the OVERDUE_FILTER to avoid code duplication. """ @@ -434,7 +439,7 @@ class PurchaseOrder(Order): return self.lines.filter(quantity__gt=F('received')) def completed_line_items(self): - """Return a list of completed line items against this order""" + """Return a list of completed line items against this order.""" return self.lines.filter(quantity__lte=F('received')) @property @@ -452,12 +457,12 @@ class PurchaseOrder(Order): @property def is_complete(self): - """Return True if all line items have been received""" + """Return True if all line items have been received.""" return self.lines.count() > 0 and self.pending_line_items().count() == 0 @transaction.atomic def receive_line_item(self, line, location, quantity, user, status=StockStatus.OK, **kwargs): - """Receive a line item (or partial line item) against this PurchaseOrder""" + """Receive a line item (or partial line item) against this PurchaseOrder.""" # Extract optional batch code for the new stock item batch_code = kwargs.get('batch_code', '') @@ -560,7 +565,7 @@ class SalesOrder(Order): @staticmethod def filterByDate(queryset, min_date, max_date): - """Filter by "minimum and maximum date range" + """Filter by "minimum and maximum date range". - Specified as min_date, max_date - Both must be specified for filter to be applied @@ -665,13 +670,13 @@ class SalesOrder(Order): @property def stock_allocations(self): - """Return a queryset containing all allocations for this order""" + """Return a queryset containing all allocations for this order.""" return SalesOrderAllocation.objects.filter( line__in=[line.pk for line in self.lines.all()] ) def is_fully_allocated(self): - """Return True if all line items are fully allocated""" + """Return True if all line items are fully allocated.""" for line in self.lines.all(): if not line.is_fully_allocated(): return False @@ -679,7 +684,7 @@ class SalesOrder(Order): return True def is_over_allocated(self): - """Return true if any lines in the order are over-allocated""" + """Return true if any lines in the order are over-allocated.""" for line in self.lines.all(): if line.is_over_allocated(): return True @@ -721,7 +726,7 @@ class SalesOrder(Order): return True def complete_order(self, user): - """Mark this order as "complete""" + """Mark this order as "complete.""" if not self.can_complete(): return False @@ -736,7 +741,7 @@ class SalesOrder(Order): return True def can_cancel(self): - """Return True if this order can be cancelled""" + """Return True if this order can be cancelled.""" if self.status != SalesOrderStatus.PENDING: return False @@ -768,11 +773,11 @@ class SalesOrder(Order): return self.lines.count() def completed_line_items(self): - """Return a queryset of the completed line items for this order""" + """Return a queryset of the completed line items for this order.""" return self.lines.filter(shipped__gte=F('quantity')) def pending_line_items(self): - """Return a queryset of the pending line items for this order""" + """Return a queryset of the pending line items for this order.""" return self.lines.filter(shipped__lt=F('quantity')) @property @@ -784,11 +789,11 @@ class SalesOrder(Order): return self.pending_line_items().count() def completed_shipments(self): - """Return a queryset of the completed shipments for this order""" + """Return a queryset of the completed shipments for this order.""" return self.shipments.exclude(shipment_date=None) def pending_shipments(self): - """Return a queryset of the pending shipments for this order""" + """Return a queryset of the pending shipments for this order.""" return self.shipments.filter(shipment_date=None) @property @@ -806,7 +811,7 @@ class SalesOrder(Order): @receiver(post_save, sender=SalesOrder, dispatch_uid='build_post_save_log') def after_save_sales_order(sender, instance: SalesOrder, created: bool, **kwargs): - """Callback function to be executed after a SalesOrder instance is saved""" + """Callback function to be executed after a SalesOrder instance is saved.""" if created and getSetting('SALESORDER_DEFAULT_SHIPMENT'): # A new SalesOrder has just been created @@ -818,7 +823,7 @@ def after_save_sales_order(sender, instance: SalesOrder, created: bool, **kwargs class PurchaseOrderAttachment(InvenTreeAttachment): - """Model for storing file attachments against a PurchaseOrder object""" + """Model for storing file attachments against a PurchaseOrder object.""" @staticmethod def get_api_url(): @@ -831,7 +836,7 @@ class PurchaseOrderAttachment(InvenTreeAttachment): class SalesOrderAttachment(InvenTreeAttachment): - """Model for storing file attachments against a SalesOrder object""" + """Model for storing file attachments against a SalesOrder object.""" @staticmethod def get_api_url(): @@ -844,7 +849,7 @@ class SalesOrderAttachment(InvenTreeAttachment): class OrderLineItem(models.Model): - """Abstract model for an order line item + """Abstract model for an order line item. Attributes: quantity: Number of items @@ -884,7 +889,7 @@ class OrderLineItem(models.Model): class OrderExtraLine(OrderLineItem): - """Abstract Model for a single ExtraLine in a Order + """Abstract Model for a single ExtraLine in a Order. Attributes: price: The unit sale price for this OrderLineItem @@ -957,7 +962,7 @@ class PurchaseOrderLineItem(OrderLineItem): ) def get_base_part(self): - """Return the base part.Part object for the line item + """Return the base part.Part object for the line item. Note: Returns None if the SupplierPart is not set! """ @@ -999,7 +1004,7 @@ class PurchaseOrderLineItem(OrderLineItem): ) def get_destination(self): - """Show where the line item is or should be placed + """Show where the line item is or should be placed. NOTE: If a line item gets split when recieved, only an arbitrary stock items location will be reported as the location for the @@ -1014,13 +1019,14 @@ class PurchaseOrderLineItem(OrderLineItem): return self.part.part.default_location def remaining(self): - """Calculate the number of items remaining to be received""" + """Calculate the number of items remaining to be received.""" r = self.quantity - self.received return max(r, 0) class PurchaseOrderExtraLine(OrderExtraLine): - """Model for a single ExtraLine in a PurchaseOrder + """Model for a single ExtraLine in a PurchaseOrder. + Attributes: order: Link to the PurchaseOrder that this line belongs to title: title of line @@ -1034,7 +1040,7 @@ class PurchaseOrderExtraLine(OrderExtraLine): class SalesOrderLineItem(OrderLineItem): - """Model for a single LineItem in a SalesOrder + """Model for a single LineItem in a SalesOrder. Attributes: order: Link to the SalesOrder that this line item belongs to @@ -1093,14 +1099,14 @@ class SalesOrderLineItem(OrderLineItem): return query['allocated'] def is_fully_allocated(self): - """Return True if this line item is fully allocated""" + """Return True if this line item is fully allocated.""" if self.order.status == SalesOrderStatus.SHIPPED: return self.fulfilled_quantity() >= self.quantity return self.allocated_quantity() >= self.quantity def is_over_allocated(self): - """Return True if this line item is over allocated""" + """Return True if this line item is over allocated.""" return self.allocated_quantity() > self.quantity def is_completed(self): @@ -1260,7 +1266,7 @@ class SalesOrderShipment(models.Model): class SalesOrderExtraLine(OrderExtraLine): - """Model for a single ExtraLine in a SalesOrder + """Model for a single ExtraLine in a SalesOrder. Attributes: order: Link to the SalesOrder that this line belongs to @@ -1275,9 +1281,7 @@ class SalesOrderExtraLine(OrderExtraLine): class SalesOrderAllocation(models.Model): - """This model is used to 'allocate' stock items to a SalesOrder. - Items that are "allocated" to a SalesOrder are not yet "attached" to the order, - but they will be once the order is fulfilled. + """This model is used to 'allocate' stock items to a SalesOrder. Items that are "allocated" to a SalesOrder are not yet "attached" to the order, but they will be once the order is fulfilled. Attributes: line: SalesOrderLineItem reference diff --git a/InvenTree/order/serializers.py b/InvenTree/order/serializers.py index 0a6b196002..7a46f60d47 100644 --- a/InvenTree/order/serializers.py +++ b/InvenTree/order/serializers.py @@ -1,4 +1,4 @@ -"""JSON serializers for the Order API""" +"""JSON serializers for the Order API.""" from datetime import datetime from decimal import Decimal @@ -31,7 +31,7 @@ from users.serializers import OwnerSerializer class AbstractOrderSerializer(serializers.Serializer): - """Abstract field definitions for OrderSerializers""" + """Abstract field definitions for OrderSerializers.""" total_price = InvenTreeMoneySerializer( source='get_total_price', @@ -43,7 +43,7 @@ class AbstractOrderSerializer(serializers.Serializer): class AbstractExtraLineSerializer(serializers.Serializer): - """Abstract Serializer for a ExtraLine object""" + """Abstract Serializer for a ExtraLine object.""" def __init__(self, *args, **kwargs): @@ -69,7 +69,7 @@ class AbstractExtraLineSerializer(serializers.Serializer): class AbstractExtraLineMeta: - """Abstract Meta for ExtraLine""" + """Abstract Meta for ExtraLine.""" fields = [ 'pk', @@ -86,7 +86,7 @@ class AbstractExtraLineMeta: class PurchaseOrderSerializer(AbstractOrderSerializer, ReferenceIndexingSerializerMixin, InvenTreeModelSerializer): - """Serializer for a PurchaseOrder object""" + """Serializer for a PurchaseOrder object.""" def __init__(self, *args, **kwargs): @@ -99,7 +99,7 @@ class PurchaseOrderSerializer(AbstractOrderSerializer, ReferenceIndexingSerializ @staticmethod def annotate_queryset(queryset): - """Add extra information to the queryset + """Add extra information to the queryset. - Number of lines in the PurchaseOrder - Overdue status of the PurchaseOrder @@ -166,13 +166,13 @@ class PurchaseOrderSerializer(AbstractOrderSerializer, ReferenceIndexingSerializ class PurchaseOrderCancelSerializer(serializers.Serializer): - """Serializer for cancelling a PurchaseOrder""" + """Serializer for cancelling a PurchaseOrder.""" class Meta: fields = [], def get_context_data(self): - """Return custom context information about the order""" + """Return custom context information about the order.""" self.order = self.context['order'] return { @@ -190,13 +190,13 @@ class PurchaseOrderCancelSerializer(serializers.Serializer): class PurchaseOrderCompleteSerializer(serializers.Serializer): - """Serializer for completing a purchase order""" + """Serializer for completing a purchase order.""" class Meta: fields = [] def get_context_data(self): - """Custom context information for this serializer""" + """Custom context information for this serializer.""" order = self.context['order'] return { @@ -210,7 +210,7 @@ class PurchaseOrderCompleteSerializer(serializers.Serializer): class PurchaseOrderIssueSerializer(serializers.Serializer): - """Serializer for issuing (sending) a purchase order""" + """Serializer for issuing (sending) a purchase order.""" class Meta: fields = [] @@ -356,7 +356,7 @@ class PurchaseOrderLineItemSerializer(InvenTreeModelSerializer): class PurchaseOrderExtraLineSerializer(AbstractExtraLineSerializer, InvenTreeModelSerializer): - """Serializer for a PurchaseOrderExtraLine object""" + """Serializer for a PurchaseOrderExtraLine object.""" order_detail = PurchaseOrderSerializer(source='order', many=False, read_only=True) @@ -365,7 +365,7 @@ class PurchaseOrderExtraLineSerializer(AbstractExtraLineSerializer, InvenTreeMod class PurchaseOrderLineItemReceiveSerializer(serializers.Serializer): - """A serializer for receiving a single purchase order line item against a purchase order""" + """A serializer for receiving a single purchase order line item against a purchase order.""" class Meta: fields = [ @@ -448,7 +448,7 @@ class PurchaseOrderLineItemReceiveSerializer(serializers.Serializer): ) def validate_barcode(self, barcode): - """Cannot check in a LineItem with a barcode that is already assigned""" + """Cannot check in a LineItem with a barcode that is already assigned.""" # Ignore empty barcode values if not barcode or barcode.strip() == '': return None @@ -490,7 +490,7 @@ class PurchaseOrderLineItemReceiveSerializer(serializers.Serializer): class PurchaseOrderReceiveSerializer(serializers.Serializer): - """Serializer for receiving items against a purchase order""" + """Serializer for receiving items against a purchase order.""" items = PurchaseOrderLineItemReceiveSerializer(many=True) @@ -546,8 +546,7 @@ class PurchaseOrderReceiveSerializer(serializers.Serializer): return data def save(self): - """Perform the actual database transaction to receive purchase order items""" - + """Perform the actual database transaction to receive purchase order items.""" data = self.validated_data request = self.context['request'] @@ -586,7 +585,7 @@ class PurchaseOrderReceiveSerializer(serializers.Serializer): class PurchaseOrderAttachmentSerializer(InvenTreeAttachmentSerializer): - """Serializers for the PurchaseOrderAttachment model""" + """Serializers for the PurchaseOrderAttachment model.""" class Meta: model = order.models.PurchaseOrderAttachment @@ -607,7 +606,7 @@ class PurchaseOrderAttachmentSerializer(InvenTreeAttachmentSerializer): class SalesOrderSerializer(AbstractOrderSerializer, ReferenceIndexingSerializerMixin, InvenTreeModelSerializer): - """Serializers for the SalesOrder object""" + """Serializers for the SalesOrder object.""" def __init__(self, *args, **kwargs): @@ -620,7 +619,7 @@ class SalesOrderSerializer(AbstractOrderSerializer, ReferenceIndexingSerializerM @staticmethod def annotate_queryset(queryset): - """Add extra information to the queryset + """Add extra information to the queryset. - Number of line items in the SalesOrder - Overdue status of the SalesOrder @@ -750,7 +749,7 @@ class SalesOrderAllocationSerializer(InvenTreeModelSerializer): class SalesOrderLineItemSerializer(InvenTreeModelSerializer): - """Serializer for a SalesOrderLineItem object""" + """Serializer for a SalesOrderLineItem object.""" @staticmethod def annotate_queryset(queryset): @@ -831,7 +830,7 @@ class SalesOrderLineItemSerializer(InvenTreeModelSerializer): class SalesOrderShipmentSerializer(InvenTreeModelSerializer): - """Serializer for the SalesOrderShipment class""" + """Serializer for the SalesOrderShipment class.""" allocations = SalesOrderAllocationSerializer(many=True, read_only=True, location_detail=True) @@ -856,7 +855,7 @@ class SalesOrderShipmentSerializer(InvenTreeModelSerializer): class SalesOrderShipmentCompleteSerializer(serializers.ModelSerializer): - """Serializer for completing (shipping) a SalesOrderShipment""" + """Serializer for completing (shipping) a SalesOrderShipment.""" class Meta: model = order.models.SalesOrderShipment @@ -906,7 +905,7 @@ class SalesOrderShipmentCompleteSerializer(serializers.ModelSerializer): class SalesOrderShipmentAllocationItemSerializer(serializers.Serializer): - """A serializer for allocating a single stock-item against a SalesOrder shipment""" + """A serializer for allocating a single stock-item against a SalesOrder shipment.""" class Meta: fields = [ @@ -978,7 +977,7 @@ class SalesOrderShipmentAllocationItemSerializer(serializers.Serializer): class SalesOrderCompleteSerializer(serializers.Serializer): - """DRF serializer for manually marking a sales order as complete""" + """DRF serializer for manually marking a sales order as complete.""" def validate(self, data): @@ -1001,7 +1000,7 @@ class SalesOrderCompleteSerializer(serializers.Serializer): class SalesOrderCancelSerializer(serializers.Serializer): - """Serializer for marking a SalesOrder as cancelled""" + """Serializer for marking a SalesOrder as cancelled.""" def get_context_data(self): @@ -1019,7 +1018,7 @@ class SalesOrderCancelSerializer(serializers.Serializer): class SalesOrderSerialAllocationSerializer(serializers.Serializer): - """DRF serializer for allocation of serial numbers against a sales order / shipment""" + """DRF serializer for allocation of serial numbers against a sales order / shipment.""" class Meta: fields = [ @@ -1038,7 +1037,7 @@ class SalesOrderSerialAllocationSerializer(serializers.Serializer): ) def validate_line_item(self, line_item): - """Ensure that the line_item is valid""" + """Ensure that the line_item is valid.""" order = self.context['order'] # Ensure that the line item points to the correct order @@ -1173,7 +1172,7 @@ class SalesOrderSerialAllocationSerializer(serializers.Serializer): class SalesOrderShipmentAllocationSerializer(serializers.Serializer): - """DRF serializer for allocation of stock items against a sales order / shipment""" + """DRF serializer for allocation of stock items against a sales order / shipment.""" class Meta: fields = [ @@ -1192,7 +1191,7 @@ class SalesOrderShipmentAllocationSerializer(serializers.Serializer): ) def validate_shipment(self, shipment): - """Run validation against the provided shipment instance""" + """Run validation against the provided shipment instance.""" order = self.context['order'] if shipment.shipment_date is not None: @@ -1204,7 +1203,7 @@ class SalesOrderShipmentAllocationSerializer(serializers.Serializer): return shipment def validate(self, data): - """Serializer validation""" + """Serializer validation.""" data = super().validate(data) # Extract SalesOrder from serializer context @@ -1218,7 +1217,7 @@ class SalesOrderShipmentAllocationSerializer(serializers.Serializer): return data def save(self): - """Perform the allocation of items against this order""" + """Perform the allocation of items against this order.""" data = self.validated_data items = data['items'] @@ -1240,7 +1239,7 @@ class SalesOrderShipmentAllocationSerializer(serializers.Serializer): class SalesOrderExtraLineSerializer(AbstractExtraLineSerializer, InvenTreeModelSerializer): - """Serializer for a SalesOrderExtraLine object""" + """Serializer for a SalesOrderExtraLine object.""" order_detail = SalesOrderSerializer(source='order', many=False, read_only=True) @@ -1249,7 +1248,7 @@ class SalesOrderExtraLineSerializer(AbstractExtraLineSerializer, InvenTreeModelS class SalesOrderAttachmentSerializer(InvenTreeAttachmentSerializer): - """Serializers for the SalesOrderAttachment model""" + """Serializers for the SalesOrderAttachment model.""" class Meta: model = order.models.SalesOrderAttachment diff --git a/InvenTree/order/test_api.py b/InvenTree/order/test_api.py index a278fabb13..54aab70ac9 100644 --- a/InvenTree/order/test_api.py +++ b/InvenTree/order/test_api.py @@ -1,4 +1,4 @@ -"""Tests for the Order API""" +"""Tests for the Order API.""" import io from datetime import datetime, timedelta @@ -37,7 +37,7 @@ class OrderTest(InvenTreeAPITestCase): super().setUp() def filter(self, filters, count): - """Test API filters""" + """Test API filters.""" response = self.get( self.LIST_URL, filters @@ -50,7 +50,7 @@ class OrderTest(InvenTreeAPITestCase): class PurchaseOrderTest(OrderTest): - """Tests for the PurchaseOrder API""" + """Tests for the PurchaseOrder API.""" LIST_URL = reverse('api-po-list') @@ -72,7 +72,7 @@ class PurchaseOrderTest(OrderTest): self.filter({'status': 40}, 1) def test_overdue(self): - """Test "overdue" status""" + """Test "overdue" status.""" self.filter({'overdue': True}, 0) self.filter({'overdue': False}, 7) @@ -97,7 +97,7 @@ class PurchaseOrderTest(OrderTest): self.assertEqual(data['description'], 'Ordering some screws') def test_po_reference(self): - """test that a reference with a too big / small reference is not possible""" + """Test that a reference with a too big / small reference is not possible.""" # get permissions self.assignRole('purchase_order.add') @@ -123,7 +123,7 @@ class PurchaseOrderTest(OrderTest): self.assertEqual(response.status_code, status.HTTP_200_OK) def test_po_operations(self): - """Test that we can create / edit and delete a PurchaseOrder via the API""" + """Test that we can create / edit and delete a PurchaseOrder via the API.""" n = models.PurchaseOrder.objects.count() url = reverse('api-po-list') @@ -210,7 +210,7 @@ class PurchaseOrderTest(OrderTest): response = self.get(url, expected_code=404) def test_po_create(self): - """Test that we can create a new PurchaseOrder via the API""" + """Test that we can create a new PurchaseOrder via the API.""" self.assignRole('purchase_order.add') self.post( @@ -224,7 +224,7 @@ class PurchaseOrderTest(OrderTest): ) def test_po_cancel(self): - """Test the PurchaseOrderCancel API endpoint""" + """Test the PurchaseOrderCancel API endpoint.""" po = models.PurchaseOrder.objects.get(pk=1) self.assertEqual(po.status, PurchaseOrderStatus.PENDING) @@ -250,7 +250,7 @@ class PurchaseOrderTest(OrderTest): self.post(url, {}, expected_code=400) def test_po_complete(self): - """ Test the PurchaseOrderComplete API endpoint """ + """Test the PurchaseOrderComplete API endpoint.""" po = models.PurchaseOrder.objects.get(pk=3) url = reverse('api-po-complete', kwargs={'pk': po.pk}) @@ -269,7 +269,7 @@ class PurchaseOrderTest(OrderTest): self.assertEqual(po.status, PurchaseOrderStatus.COMPLETE) def test_po_issue(self): - """ Test the PurchaseOrderIssue API endpoint """ + """Test the PurchaseOrderIssue API endpoint.""" po = models.PurchaseOrder.objects.get(pk=2) url = reverse('api-po-issue', kwargs={'pk': po.pk}) @@ -303,7 +303,7 @@ class PurchaseOrderTest(OrderTest): class PurchaseOrderDownloadTest(OrderTest): - """Unit tests for downloading PurchaseOrder data via the API endpoint""" + """Unit tests for downloading PurchaseOrder data via the API endpoint.""" required_cols = [ 'id', @@ -321,8 +321,7 @@ class PurchaseOrderDownloadTest(OrderTest): ] def test_download_wrong_format(self): - """Incorrect format should default raise an error""" - + """Incorrect format should default raise an error.""" url = reverse('api-po-list') with self.assertRaises(ValueError): @@ -334,8 +333,7 @@ class PurchaseOrderDownloadTest(OrderTest): ) def test_download_csv(self): - """Download PurchaseOrder data as .csv""" - + """Download PurchaseOrder data as .csv.""" with self.download_file( reverse('api-po-list'), { @@ -374,7 +372,7 @@ class PurchaseOrderDownloadTest(OrderTest): class PurchaseOrderReceiveTest(OrderTest): - """Unit tests for receiving items against a PurchaseOrder""" + """Unit tests for receiving items against a PurchaseOrder.""" def setUp(self): super().setUp() @@ -392,7 +390,7 @@ class PurchaseOrderReceiveTest(OrderTest): order.save() def test_empty(self): - """Test without any POST data""" + """Test without any POST data.""" data = self.post(self.url, {}, expected_code=400).data self.assertIn('This field is required', str(data['items'])) @@ -402,7 +400,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_no_items(self): - """Test with an empty list of items""" + """Test with an empty list of items.""" data = self.post( self.url, { @@ -418,7 +416,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_invalid_items(self): - """Test than errors are returned as expected for invalid data""" + """Test than errors are returned as expected for invalid data.""" data = self.post( self.url, { @@ -441,7 +439,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_invalid_status(self): - """Test with an invalid StockStatus value""" + """Test with an invalid StockStatus value.""" data = self.post( self.url, { @@ -463,7 +461,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_mismatched_items(self): - """Test for supplier parts which *do* exist but do not match the order supplier""" + """Test for supplier parts which *do* exist but do not match the order supplier.""" data = self.post( self.url, { @@ -485,7 +483,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_null_barcode(self): - """Test than a "null" barcode field can be provided""" + """Test than a "null" barcode field can be provided.""" # Set stock item barcode item = StockItem.objects.get(pk=1) item.save() @@ -560,7 +558,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(self.n, StockItem.objects.count()) def test_valid(self): - """Test receipt of valid data""" + """Test receipt of valid data.""" line_1 = models.PurchaseOrderLineItem.objects.get(pk=1) line_2 = models.PurchaseOrderLineItem.objects.get(pk=2) @@ -637,7 +635,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertTrue(StockItem.objects.filter(uid='MY-UNIQUE-BARCODE-456').exists()) def test_batch_code(self): - """Test that we can supply a 'batch code' when receiving items""" + """Test that we can supply a 'batch code' when receiving items.""" line_1 = models.PurchaseOrderLineItem.objects.get(pk=1) line_2 = models.PurchaseOrderLineItem.objects.get(pk=2) @@ -678,7 +676,7 @@ class PurchaseOrderReceiveTest(OrderTest): self.assertEqual(item_2.batch, 'xyz-789') def test_serial_numbers(self): - """Test that we can supply a 'serial number' when receiving items""" + """Test that we can supply a 'serial number' when receiving items.""" line_1 = models.PurchaseOrderLineItem.objects.get(pk=1) line_2 = models.PurchaseOrderLineItem.objects.get(pk=2) @@ -734,7 +732,7 @@ class PurchaseOrderReceiveTest(OrderTest): class SalesOrderTest(OrderTest): - """Tests for the SalesOrder API""" + """Tests for the SalesOrder API.""" LIST_URL = reverse('api-so-list') @@ -757,10 +755,7 @@ class SalesOrderTest(OrderTest): self.filter({'status': 99}, 0) # Invalid def test_overdue(self): - """ - Test "overdue" status - """ - + """Test "overdue" status.""" self.filter({'overdue': True}, 0) self.filter({'overdue': False}, 5) @@ -789,7 +784,7 @@ class SalesOrderTest(OrderTest): self.get(url) def test_so_operations(self): - """Test that we can create / edit and delete a SalesOrder via the API""" + """Test that we can create / edit and delete a SalesOrder via the API.""" n = models.SalesOrder.objects.count() url = reverse('api-so-list') @@ -869,7 +864,7 @@ class SalesOrderTest(OrderTest): response = self.get(url, expected_code=404) def test_so_create(self): - """Test that we can create a new SalesOrder via the API""" + """Test that we can create a new SalesOrder via the API.""" self.assignRole('sales_order.add') self.post( @@ -883,8 +878,7 @@ class SalesOrderTest(OrderTest): ) def test_so_cancel(self): - """ Test API endpoint for cancelling a SalesOrder """ - + """Test API endpoint for cancelling a SalesOrder.""" so = models.SalesOrder.objects.get(pk=1) self.assertEqual(so.status, SalesOrderStatus.PENDING) @@ -920,7 +914,7 @@ class SalesOrderTest(OrderTest): class SalesOrderLineItemTest(OrderTest): - """Tests for the SalesOrderLineItem API""" + """Tests for the SalesOrderLineItem API.""" def setUp(self): @@ -998,10 +992,10 @@ class SalesOrderLineItemTest(OrderTest): class SalesOrderDownloadTest(OrderTest): - """Unit tests for downloading SalesOrder data via the API endpoint""" + """Unit tests for downloading SalesOrder data via the API endpoint.""" def test_download_fail(self): - """Test that downloading without the 'export' option fails""" + """Test that downloading without the 'export' option fails.""" url = reverse('api-so-list') with self.assertRaises(ValueError): @@ -1088,7 +1082,7 @@ class SalesOrderDownloadTest(OrderTest): class SalesOrderAllocateTest(OrderTest): - """Unit tests for allocating stock items against a SalesOrder""" + """Unit tests for allocating stock items against a SalesOrder.""" def setUp(self): super().setUp() @@ -1123,7 +1117,7 @@ class SalesOrderAllocateTest(OrderTest): ) def test_invalid(self): - """Test POST with invalid data""" + """Test POST with invalid data.""" # No data response = self.post(self.url, {}, expected_code=400) @@ -1206,7 +1200,7 @@ class SalesOrderAllocateTest(OrderTest): self.assertEqual(line.allocations.count(), 1) def test_shipment_complete(self): - """Test that we can complete a shipment via the API""" + """Test that we can complete a shipment via the API.""" url = reverse('api-so-shipment-ship', kwargs={'pk': self.shipment.pk}) self.assertFalse(self.shipment.is_complete()) diff --git a/InvenTree/order/test_migrations.py b/InvenTree/order/test_migrations.py index 80c88a4006..1734501a9c 100644 --- a/InvenTree/order/test_migrations.py +++ b/InvenTree/order/test_migrations.py @@ -1,4 +1,4 @@ -"""Unit tests for the 'order' model data migrations""" +"""Unit tests for the 'order' model data migrations.""" from django_test_migrations.contrib.unittest_case import MigratorTestCase @@ -6,13 +6,13 @@ from InvenTree.status_codes import SalesOrderStatus class TestRefIntMigrations(MigratorTestCase): - """Test entire schema migration""" + """Test entire schema migration.""" migrate_from = ('order', '0040_salesorder_target_date') migrate_to = ('order', '0061_merge_0054_auto_20211201_2139_0060_auto_20211129_1339') def prepare(self): - """Create initial data set""" + """Create initial data set.""" # Create a purchase order from a supplier Company = self.old_state.apps.get_model('company', 'company') @@ -50,7 +50,7 @@ class TestRefIntMigrations(MigratorTestCase): print(sales_order.reference_int) def test_ref_field(self): - """Test that the 'reference_int' field has been created and is filled out correctly""" + """Test that the 'reference_int' field has been created and is filled out correctly.""" PurchaseOrder = self.new_state.apps.get_model('order', 'purchaseorder') SalesOrder = self.new_state.apps.get_model('order', 'salesorder') @@ -65,13 +65,13 @@ class TestRefIntMigrations(MigratorTestCase): class TestShipmentMigration(MigratorTestCase): - """Test data migration for the "SalesOrderShipment" model""" + """Test data migration for the "SalesOrderShipment" model.""" migrate_from = ('order', '0051_auto_20211014_0623') migrate_to = ('order', '0055_auto_20211025_0645') def prepare(self): - """Create an initial SalesOrder""" + """Create an initial SalesOrder.""" Company = self.old_state.apps.get_model('company', 'company') customer = Company.objects.create( @@ -97,7 +97,7 @@ class TestShipmentMigration(MigratorTestCase): self.old_state.apps.get_model('order', 'salesordershipment') def test_shipment_creation(self): - """Check that a SalesOrderShipment has been created""" + """Check that a SalesOrderShipment has been created.""" SalesOrder = self.new_state.apps.get_model('order', 'salesorder') Shipment = self.new_state.apps.get_model('order', 'salesordershipment') @@ -107,13 +107,13 @@ class TestShipmentMigration(MigratorTestCase): class TestAdditionalLineMigration(MigratorTestCase): - """Test entire schema migration""" + """Test entire schema migration.""" migrate_from = ('order', '0063_alter_purchaseorderlineitem_unique_together') migrate_to = ('order', '0064_purchaseorderextraline_salesorderextraline') def prepare(self): - """Create initial data set""" + """Create initial data set.""" # Create a purchase order from a supplier Company = self.old_state.apps.get_model('company', 'company') PurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder') @@ -176,7 +176,7 @@ class TestAdditionalLineMigration(MigratorTestCase): # ) def test_po_migration(self): - """Test that the the PO lines where converted correctly""" + """Test that the the PO lines where converted correctly.""" PurchaseOrder = self.new_state.apps.get_model('order', 'purchaseorder') for ii in range(10): diff --git a/InvenTree/order/test_sales_order.py b/InvenTree/order/test_sales_order.py index 1652f18fe1..29ede9a232 100644 --- a/InvenTree/order/test_sales_order.py +++ b/InvenTree/order/test_sales_order.py @@ -44,8 +44,7 @@ class SalesOrderTest(TestCase): self.line = SalesOrderLineItem.objects.create(quantity=50, order=self.order, part=self.part) def test_overdue(self): - """Tests for overdue functionality""" - + """Tests for overdue functionality.""" today = datetime.now().date() # By default, order is *not* overdue as the target date is not set diff --git a/InvenTree/order/test_views.py b/InvenTree/order/test_views.py index c905af2cae..3096f5ea60 100644 --- a/InvenTree/order/test_views.py +++ b/InvenTree/order/test_views.py @@ -37,17 +37,17 @@ class OrderListTest(OrderViewTestCase): class PurchaseOrderTests(OrderViewTestCase): - """Tests for PurchaseOrder views""" + """Tests for PurchaseOrder views.""" def test_detail_view(self): - """ Retrieve PO detail view """ + """Retrieve PO detail view.""" response = self.client.get(reverse('po-detail', args=(1,))) self.assertEqual(response.status_code, 200) keys = response.context.keys() self.assertIn('PurchaseOrderStatus', keys) def test_po_export(self): - """Export PurchaseOrder""" + """Export PurchaseOrder.""" response = self.client.get(reverse('po-export', args=(1,)), HTTP_X_REQUESTED_WITH='XMLHttpRequest') # Response should be streaming-content (file download) diff --git a/InvenTree/order/tests.py b/InvenTree/order/tests.py index ba95ac8fda..e23dd36a44 100644 --- a/InvenTree/order/tests.py +++ b/InvenTree/order/tests.py @@ -26,7 +26,7 @@ class OrderTest(TestCase): ] def test_basics(self): - """Basic tests e.g. repr functions etc""" + """Basic tests e.g. repr functions etc.""" order = PurchaseOrder.objects.get(pk=1) self.assertEqual(order.get_absolute_url(), '/order/purchase-order/1/') @@ -38,7 +38,7 @@ class OrderTest(TestCase): self.assertEqual(str(line), "100 x ACME0001 from ACME (for PO0001 - ACME)") def test_overdue(self): - """Test overdue status functionality""" + """Test overdue status functionality.""" today = datetime.now().date() order = PurchaseOrder.objects.get(pk=1) @@ -53,7 +53,7 @@ class OrderTest(TestCase): self.assertFalse(order.is_overdue) def test_on_order(self): - """There should be 3 separate items on order for the M2x4 LPHS part""" + """There should be 3 separate items on order for the M2x4 LPHS part.""" part = Part.objects.get(name='M2x4 LPHS') open_orders = [] @@ -67,7 +67,7 @@ class OrderTest(TestCase): self.assertEqual(part.on_order, 1400) def test_add_items(self): - """Test functions for adding line items to an order""" + """Test functions for adding line items to an order.""" order = PurchaseOrder.objects.get(pk=1) self.assertEqual(order.status, PurchaseOrderStatus.PENDING) @@ -103,7 +103,7 @@ class OrderTest(TestCase): order.add_line_item(sku, 99) def test_pricing(self): - """Test functions for adding line items to an order including price-breaks""" + """Test functions for adding line items to an order including price-breaks.""" order = PurchaseOrder.objects.get(pk=7) self.assertEqual(order.status, PurchaseOrderStatus.PENDING) @@ -135,7 +135,7 @@ class OrderTest(TestCase): self.assertEqual(order.lines.first().purchase_price.amount, 1.25) def test_receive(self): - """Test order receiving functions""" + """Test order receiving functions.""" part = Part.objects.get(name='M2x4 LPHS') # Receive some items diff --git a/InvenTree/order/views.py b/InvenTree/order/views.py index caf80c3d0e..68a4f1811b 100644 --- a/InvenTree/order/views.py +++ b/InvenTree/order/views.py @@ -1,4 +1,4 @@ -"""Django views for interacting with Order app""" +"""Django views for interacting with Order app.""" import logging from decimal import Decimal, InvalidOperation @@ -31,16 +31,14 @@ logger = logging.getLogger("inventree") class PurchaseOrderIndex(InvenTreeRoleMixin, ListView): - """List view for all purchase orders""" + """List view for all purchase orders.""" model = PurchaseOrder template_name = 'order/purchase_orders.html' context_object_name = 'orders' def get_queryset(self): - """ Retrieve the list of purchase orders, - ensure that the most recent ones are returned first. """ - + """Retrieve the list of purchase orders, ensure that the most recent ones are returned first.""" queryset = PurchaseOrder.objects.all().order_by('-creation_date') return queryset @@ -59,7 +57,7 @@ class SalesOrderIndex(InvenTreeRoleMixin, ListView): class PurchaseOrderDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detail view for a PurchaseOrder object""" + """Detail view for a PurchaseOrder object.""" context_object_name = 'order' queryset = PurchaseOrder.objects.all().prefetch_related('lines') @@ -72,7 +70,7 @@ class PurchaseOrderDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailVi class SalesOrderDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detail view for a SalesOrder object""" + """Detail view for a SalesOrder object.""" context_object_name = 'order' queryset = SalesOrder.objects.all().prefetch_related('lines__allocations__item__purchase_order') @@ -124,13 +122,11 @@ class PurchaseOrderUpload(FileManagementFormView): file_manager_class = OrderFileManager def get_order(self): - """Get order or return 404""" - + """Get order or return 404.""" return get_object_or_404(PurchaseOrder, pk=self.kwargs['pk']) def get_context_data(self, form, **kwargs): - """Handle context data for order""" - + """Handle context data for order.""" context = super().get_context_data(form=form, **kwargs) order = self.get_order() @@ -229,7 +225,7 @@ class PurchaseOrderUpload(FileManagementFormView): row['notes'] = notes def done(self, form_list, **kwargs): - """Once all the data is in, process it to add PurchaseOrderLineItem instances to the order""" + """Once all the data is in, process it to add PurchaseOrderLineItem instances to the order.""" order = self.get_order() items = self.get_clean_items() @@ -260,7 +256,7 @@ class PurchaseOrderUpload(FileManagementFormView): class SalesOrderExport(AjaxView): - """Export a sales order + """Export a sales order. - File format can optionally be passed as a query parameter e.g. ?format=CSV - Default file format is CSV @@ -286,7 +282,7 @@ class SalesOrderExport(AjaxView): class PurchaseOrderExport(AjaxView): - """File download for a purchase order + """File download for a purchase order. - File format can be optionally passed as a query param e.g. ?format=CSV - Default file format is CSV @@ -317,7 +313,7 @@ class PurchaseOrderExport(AjaxView): class LineItemPricing(PartPricing): - """View for inspecting part pricing information""" + """View for inspecting part pricing information.""" class EnhancedForm(PartPricing.form_class): pk = IntegerField(widget=HiddenInput()) @@ -361,7 +357,7 @@ class LineItemPricing(PartPricing): return None def get_quantity(self): - """Return set quantity in decimal format""" + """Return set quantity in decimal format.""" qty = Decimal(self.request.GET.get('quantity', 1)) if qty == 1: return Decimal(self.request.POST.get('quantity', 1)) diff --git a/InvenTree/part/admin.py b/InvenTree/part/admin.py index 88064ff275..81e408b30d 100644 --- a/InvenTree/part/admin.py +++ b/InvenTree/part/admin.py @@ -11,7 +11,7 @@ from stock.models import StockLocation class PartResource(ModelResource): - """ Class for managing Part data import/export """ + """Class for managing Part data import/export.""" # ForeignKey fields category = Field(attribute='category', widget=widgets.ForeignKeyWidget(models.PartCategory)) @@ -49,8 +49,7 @@ class PartResource(ModelResource): ] def get_queryset(self): - """ Prefetch related data for quicker access """ - + """Prefetch related data for quicker access.""" query = super().get_queryset() query = query.prefetch_related( 'category', @@ -82,7 +81,7 @@ class PartAdmin(ImportExportModelAdmin): class PartCategoryResource(ModelResource): - """ Class for managing PartCategory data import/export """ + """Class for managing PartCategory data import/export.""" parent = Field(attribute='parent', widget=widgets.ForeignKeyWidget(models.PartCategory)) @@ -122,9 +121,7 @@ class PartCategoryAdmin(ImportExportModelAdmin): class PartRelatedAdmin(admin.ModelAdmin): - """ - Class to manage PartRelated objects - """ + """Class to manage PartRelated objects.""" autocomplete_fields = ('part_1', 'part_2') @@ -158,7 +155,7 @@ class PartTestTemplateAdmin(admin.ModelAdmin): class BomItemResource(ModelResource): - """ Class for managing BomItem data import/export """ + """Class for managing BomItem data import/export.""" level = Field(attribute='level', readonly=True) @@ -189,9 +186,7 @@ class BomItemResource(ModelResource): sub_assembly = Field(attribute='sub_part__assembly', readonly=True) def dehydrate_quantity(self, item): - """ - Special consideration for the 'quantity' field on data export. - We do not want a spreadsheet full of "1.0000" (we'd rather "1") + """Special consideration for the 'quantity' field on data export. We do not want a spreadsheet full of "1.0000" (we'd rather "1") Ref: https://django-import-export.readthedocs.io/en/latest/getting_started.html#advanced-data-manipulation-on-export """ @@ -202,12 +197,7 @@ class BomItemResource(ModelResource): self.is_importing = kwargs.get('importing', False) def get_fields(self, **kwargs): - """ - If we are exporting for the purposes of generating - a 'bom-import' template, there are some fields which - we are not interested in. - """ - + """If we are exporting for the purposes of generating a 'bom-import' template, there are some fields which we are not interested in.""" fields = super().get_fields(**kwargs) # If we are not generating an "import" template, @@ -270,7 +260,7 @@ class ParameterTemplateAdmin(ImportExportModelAdmin): class ParameterResource(ModelResource): - """ Class for managing PartParameter data import/export """ + """Class for managing PartParameter data import/export.""" part = Field(attribute='part', widget=widgets.ForeignKeyWidget(models.Part)) diff --git a/InvenTree/part/api.py b/InvenTree/part/api.py index 7ab2f1b26a..569a0491f2 100644 --- a/InvenTree/part/api.py +++ b/InvenTree/part/api.py @@ -1,4 +1,4 @@ -"""Provides a JSON API for the Part app""" +"""Provides a JSON API for the Part app.""" import datetime from decimal import Decimal, InvalidOperation @@ -155,7 +155,7 @@ class CategoryList(generics.ListCreateAPIView): class CategoryDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of a single PartCategory object""" + """API endpoint for detail view of a single PartCategory object.""" serializer_class = part_serializers.CategorySerializer queryset = PartCategory.objects.all() @@ -185,7 +185,7 @@ class CategoryDetail(generics.RetrieveUpdateDestroyAPIView): class CategoryMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating PartCategory metadata""" + """API endpoint for viewing / updating PartCategory metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(PartCategory, *args, **kwargs) @@ -250,14 +250,14 @@ class CategoryTree(generics.ListAPIView): class PartSalePriceDetail(generics.RetrieveUpdateDestroyAPIView): - """Detail endpoint for PartSellPriceBreak model""" + """Detail endpoint for PartSellPriceBreak model.""" queryset = PartSellPriceBreak.objects.all() serializer_class = part_serializers.PartSalePriceSerializer class PartSalePriceList(generics.ListCreateAPIView): - """API endpoint for list view of PartSalePriceBreak model""" + """API endpoint for list view of PartSalePriceBreak model.""" queryset = PartSellPriceBreak.objects.all() serializer_class = part_serializers.PartSalePriceSerializer @@ -272,14 +272,14 @@ class PartSalePriceList(generics.ListCreateAPIView): class PartInternalPriceDetail(generics.RetrieveUpdateDestroyAPIView): - """Detail endpoint for PartInternalPriceBreak model""" + """Detail endpoint for PartInternalPriceBreak model.""" queryset = PartInternalPriceBreak.objects.all() serializer_class = part_serializers.PartInternalPriceSerializer class PartInternalPriceList(generics.ListCreateAPIView): - """API endpoint for list view of PartInternalPriceBreak model""" + """API endpoint for list view of PartInternalPriceBreak model.""" queryset = PartInternalPriceBreak.objects.all() serializer_class = part_serializers.PartInternalPriceSerializer @@ -310,14 +310,14 @@ class PartAttachmentList(generics.ListCreateAPIView, AttachmentMixin): class PartAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin): - """Detail endpoint for PartAttachment model""" + """Detail endpoint for PartAttachment model.""" queryset = PartAttachment.objects.all() serializer_class = part_serializers.PartAttachmentSerializer class PartTestTemplateDetail(generics.RetrieveUpdateDestroyAPIView): - """Detail endpoint for PartTestTemplate model""" + """Detail endpoint for PartTestTemplate model.""" queryset = PartTestTemplate.objects.all() serializer_class = part_serializers.PartTestTemplateSerializer @@ -364,7 +364,7 @@ class PartTestTemplateList(generics.ListCreateAPIView): class PartThumbs(generics.ListAPIView): - """API endpoint for retrieving information on available Part thumbnails""" + """API endpoint for retrieving information on available Part thumbnails.""" queryset = Part.objects.all() serializer_class = part_serializers.PartThumbSerializer @@ -407,7 +407,7 @@ class PartThumbs(generics.ListAPIView): class PartThumbsUpdate(generics.RetrieveUpdateAPIView): - """API endpoint for updating Part thumbnails""" + """API endpoint for updating Part thumbnails.""" queryset = Part.objects.all() serializer_class = part_serializers.PartThumbSerializerUpdate @@ -552,7 +552,7 @@ class PartScheduling(generics.RetrieveAPIView): class PartMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating Part metadata""" + """API endpoint for viewing / updating Part metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(Part, *args, **kwargs) @@ -561,7 +561,7 @@ class PartMetadata(generics.RetrieveUpdateAPIView): class PartSerialNumberDetail(generics.RetrieveAPIView): - """API endpoint for returning extra serial number information about a particular part""" + """API endpoint for returning extra serial number information about a particular part.""" queryset = Part.objects.all() @@ -586,7 +586,7 @@ class PartSerialNumberDetail(generics.RetrieveAPIView): class PartCopyBOM(generics.CreateAPIView): - """API endpoint for duplicating a BOM""" + """API endpoint for duplicating a BOM.""" queryset = Part.objects.all() serializer_class = part_serializers.PartCopyBOMSerializer @@ -604,7 +604,7 @@ class PartCopyBOM(generics.CreateAPIView): class PartValidateBOM(generics.RetrieveUpdateAPIView): - """API endpoint for 'validating' the BOM for a given Part""" + """API endpoint for 'validating' the BOM for a given Part.""" class BOMValidateSerializer(serializers.ModelSerializer): @@ -652,7 +652,7 @@ class PartValidateBOM(generics.RetrieveUpdateAPIView): class PartDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of a single Part object""" + """API endpoint for detail view of a single Part object.""" queryset = Part.objects.all() serializer_class = part_serializers.PartSerializer @@ -750,8 +750,7 @@ class PartFilter(rest_filters.FilterSet): low_stock = rest_filters.BooleanFilter(label='Low stock', method='filter_low_stock') def filter_low_stock(self, queryset, name, value): - """Filter by "low stock" status""" - + """Filter by "low stock" status.""" value = str2bool(value) if value: @@ -811,7 +810,7 @@ class PartFilter(rest_filters.FilterSet): class PartList(APIDownloadMixin, generics.ListCreateAPIView): - """API endpoint for accessing a list of Part objects + """API endpoint for accessing a list of Part objects. - GET: Return list of objects - POST: Create a new Part object @@ -1340,7 +1339,7 @@ class PartList(APIDownloadMixin, generics.ListCreateAPIView): class PartRelatedList(generics.ListCreateAPIView): - """API endpoint for accessing a list of PartRelated objects""" + """API endpoint for accessing a list of PartRelated objects.""" queryset = PartRelated.objects.all() serializer_class = part_serializers.PartRelationSerializer @@ -1367,7 +1366,7 @@ class PartRelatedList(generics.ListCreateAPIView): class PartRelatedDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for accessing detail view of a PartRelated object""" + """API endpoint for accessing detail view of a PartRelated object.""" queryset = PartRelated.objects.all() serializer_class = part_serializers.PartRelationSerializer @@ -1398,7 +1397,7 @@ class PartParameterTemplateList(generics.ListCreateAPIView): ] def filter_queryset(self, queryset): - """Custom filtering for the PartParameterTemplate API""" + """Custom filtering for the PartParameterTemplate API.""" queryset = super().filter_queryset(queryset) params = self.request.query_params @@ -1434,7 +1433,7 @@ class PartParameterTemplateList(generics.ListCreateAPIView): class PartParameterList(generics.ListCreateAPIView): - """API endpoint for accessing a list of PartParameter objects + """API endpoint for accessing a list of PartParameter objects. - GET: Return list of PartParameter objects - POST: Create a new PartParameter object @@ -1454,14 +1453,14 @@ class PartParameterList(generics.ListCreateAPIView): class PartParameterDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of a single PartParameter object""" + """API endpoint for detail view of a single PartParameter object.""" queryset = PartParameter.objects.all() serializer_class = part_serializers.PartParameterSerializer class BomFilter(rest_filters.FilterSet): - """Custom filters for the BOM list""" + """Custom filters for the BOM list.""" # Boolean filters for BOM item optional = rest_filters.BooleanFilter(label='BOM line is optional') @@ -1652,13 +1651,13 @@ class BomList(generics.ListCreateAPIView): return queryset def include_pricing(self): - """Determine if pricing information should be included in the response""" + """Determine if pricing information should be included in the response.""" pricing_default = InvenTreeSetting.get_setting('PART_SHOW_PRICE_IN_BOM') return str2bool(self.request.query_params.get('include_pricing', pricing_default)) def annotate_pricing(self, queryset): - """Add part pricing information to the queryset""" + """Add part pricing information to the queryset.""" # Annotate with purchase prices queryset = queryset.annotate( purchase_price_min=Min('sub_part__stock_items__purchase_price'), @@ -1673,7 +1672,7 @@ class BomList(generics.ListCreateAPIView): ).values('pk', 'sub_part', 'purchase_price', 'purchase_price_currency') def convert_price(price, currency, decimal_places=4): - """Convert price field, returns Money field""" + """Convert price field, returns Money field.""" price_adjusted = None # Get default currency from settings @@ -1735,7 +1734,7 @@ class BomImportUpload(generics.CreateAPIView): serializer_class = part_serializers.BomImportUploadSerializer def create(self, request, *args, **kwargs): - """Custom create function to return the extracted data""" + """Custom create function to return the extracted data.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) @@ -1754,14 +1753,14 @@ class BomImportExtract(generics.CreateAPIView): class BomImportSubmit(generics.CreateAPIView): - """API endpoint for submitting BOM data from a BOM file""" + """API endpoint for submitting BOM data from a BOM file.""" queryset = BomItem.objects.none() serializer_class = part_serializers.BomImportSubmitSerializer class BomDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of a single BomItem object""" + """API endpoint for detail view of a single BomItem object.""" queryset = BomItem.objects.all() serializer_class = part_serializers.BomItemSerializer @@ -1777,7 +1776,7 @@ class BomDetail(generics.RetrieveUpdateDestroyAPIView): class BomItemValidate(generics.UpdateAPIView): - """API endpoint for validating a BomItem""" + """API endpoint for validating a BomItem.""" # Very simple serializers class BomItemValidationSerializer(serializers.Serializer): @@ -1788,8 +1787,7 @@ class BomItemValidate(generics.UpdateAPIView): serializer_class = BomItemValidationSerializer def update(self, request, *args, **kwargs): - """ Perform update request """ - + """Perform update request.""" partial = kwargs.pop('partial', False) valid = request.data.get('valid', False) @@ -1806,7 +1804,7 @@ class BomItemValidate(generics.UpdateAPIView): class BomItemSubstituteList(generics.ListCreateAPIView): - """API endpoint for accessing a list of BomItemSubstitute objects""" + """API endpoint for accessing a list of BomItemSubstitute objects.""" serializer_class = part_serializers.BomItemSubstituteSerializer queryset = BomItemSubstitute.objects.all() @@ -1824,7 +1822,7 @@ class BomItemSubstituteList(generics.ListCreateAPIView): class BomItemSubstituteDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of a single BomItemSubstitute object""" + """API endpoint for detail view of a single BomItemSubstitute object.""" queryset = BomItemSubstitute.objects.all() serializer_class = part_serializers.BomItemSubstituteSerializer diff --git a/InvenTree/part/bom.py b/InvenTree/part/bom.py index 426855af68..69d7baba5d 100644 --- a/InvenTree/part/bom.py +++ b/InvenTree/part/bom.py @@ -1,4 +1,5 @@ """Functionality for Bill of Material (BOM) management. + Primarily BOM upload tools. """ @@ -14,7 +15,7 @@ from .models import BomItem def IsValidBOMFormat(fmt): - """Test if a file format specifier is in the valid list of BOM file formats""" + """Test if a file format specifier is in the valid list of BOM file formats.""" return fmt.strip().lower() in GetExportFormats() @@ -88,9 +89,7 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa pass if parameter_data: - """ - If requested, add extra columns for each PartParameter associated with each line item - """ + """If requested, add extra columns for each PartParameter associated with each line item.""" parameter_cols = {} @@ -113,9 +112,7 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa add_columns_to_dataset(parameter_cols_ordered, len(bom_items)) if stock_data: - """ - If requested, add extra columns for stock data associated with each line item - """ + """If requested, add extra columns for stock data associated with each line item.""" stock_headers = [ _('Default Location'), @@ -168,9 +165,7 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa add_columns_to_dataset(stock_cols, len(bom_items)) if manufacturer_data or supplier_data: - """ - If requested, add extra columns for each SupplierPart and ManufacturerPart associated with each line item - """ + """If requested, add extra columns for each SupplierPart and ManufacturerPart associated with each line item.""" # Keep track of the supplier parts we have already exported supplier_parts_used = set() diff --git a/InvenTree/part/forms.py b/InvenTree/part/forms.py index cf5123f0c0..965f476e21 100644 --- a/InvenTree/part/forms.py +++ b/InvenTree/part/forms.py @@ -1,4 +1,4 @@ -"""Django Forms for interacting with Part objects""" +"""Django Forms for interacting with Part objects.""" from django import forms from django.utils.translation import gettext_lazy as _ @@ -17,7 +17,7 @@ from .models import (Part, PartCategory, PartCategoryParameterTemplate, class PartModelChoiceField(forms.ModelChoiceField): - """Extending string representation of Part instance with available stock""" + """Extending string representation of Part instance with available stock.""" def label_from_instance(self, part): @@ -31,7 +31,7 @@ class PartModelChoiceField(forms.ModelChoiceField): class PartImageDownloadForm(HelperForm): - """Form for downloading an image from a URL""" + """Form for downloading an image from a URL.""" url = forms.URLField( label=_('URL'), @@ -47,11 +47,10 @@ class PartImageDownloadForm(HelperForm): class BomMatchItemForm(MatchItemForm): - """Override MatchItemForm fields""" + """Override MatchItemForm fields.""" def get_special_field(self, col_guess, row, file_manager): - """Set special fields""" - + """Set special fields.""" # set quantity field if 'quantity' in col_guess.lower(): return forms.CharField( @@ -70,13 +69,13 @@ class BomMatchItemForm(MatchItemForm): class SetPartCategoryForm(forms.Form): - """Form for setting the category of multiple Part objects""" + """Form for setting the category of multiple Part objects.""" part_category = TreeNodeChoiceField(queryset=PartCategory.objects.all(), required=True, help_text=_('Select part category')) class EditPartParameterTemplateForm(HelperForm): - """Form for editing a PartParameterTemplate object""" + """Form for editing a PartParameterTemplate object.""" class Meta: model = PartParameterTemplate @@ -87,7 +86,7 @@ class EditPartParameterTemplateForm(HelperForm): class EditCategoryParameterTemplateForm(HelperForm): - """Form for editing a PartCategoryParameterTemplate object""" + """Form for editing a PartCategoryParameterTemplate object.""" add_to_same_level_categories = forms.BooleanField(required=False, initial=False, @@ -109,7 +108,7 @@ class EditCategoryParameterTemplateForm(HelperForm): class PartPriceForm(forms.Form): - """Simple form for viewing part pricing information""" + """Simple form for viewing part pricing information.""" quantity = forms.IntegerField( required=True, @@ -126,7 +125,7 @@ class PartPriceForm(forms.Form): class EditPartSalePriceBreakForm(HelperForm): - """Form for creating / editing a sale price for a part""" + """Form for creating / editing a sale price for a part.""" quantity = RoundingDecimalFormField(max_digits=10, decimal_places=5, label=_('Quantity')) @@ -140,7 +139,7 @@ class EditPartSalePriceBreakForm(HelperForm): class EditPartInternalPriceBreakForm(HelperForm): - """Form for creating / editing a internal price for a part""" + """Form for creating / editing a internal price for a part.""" quantity = RoundingDecimalFormField(max_digits=10, decimal_places=5, label=_('Quantity')) diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py index 9ab99ae7a9..8c8c6eb428 100644 --- a/InvenTree/part/models.py +++ b/InvenTree/part/models.py @@ -1,4 +1,4 @@ -"""Part database model definitions""" +"""Part database model definitions.""" import decimal import hashlib @@ -113,11 +113,11 @@ class PartCategory(MetadataMixin, InvenTreeTree): def get_parts(self, cascade=True): """Return a queryset for all parts under this category. - args: + Args: cascade - If True, also look under subcategories (default = True) """ if cascade: - """ Select any parts which exist in this category or any child categories """ + """Select any parts which exist in this category or any child categories.""" queryset = Part.objects.filter(category__in=self.getUniqueChildren(include_self=True)) else: queryset = Part.objects.filter(category=self.pk) @@ -139,15 +139,15 @@ class PartCategory(MetadataMixin, InvenTreeTree): @property def has_parts(self): - """True if there are any parts in this category""" + """True if there are any parts in this category.""" return self.partcount() > 0 def prefetch_parts_parameters(self, cascade=True): - """Prefectch parts parameters""" + """Prefectch parts parameters.""" return self.get_parts(cascade=cascade).prefetch_related('parameters', 'parameters__template').all() def get_unique_parameters(self, cascade=True, prefetch=None): - """Get all unique parameter names for all parts from this category""" + """Get all unique parameter names for all parts from this category.""" unique_parameters_names = [] if prefetch: @@ -164,7 +164,7 @@ class PartCategory(MetadataMixin, InvenTreeTree): return sorted(unique_parameters_names) def get_parts_parameters(self, cascade=True, prefetch=None): - """Get all parameter names and values for all parts from this category""" + """Get all parameter names and values for all parts from this category.""" category_parameters = [] if prefetch: @@ -193,7 +193,7 @@ class PartCategory(MetadataMixin, InvenTreeTree): @classmethod def get_parent_categories(cls): - """Return tuple list of parent (root) categories""" + """Return tuple list of parent (root) categories.""" # Get root nodes root_categories = cls.objects.filter(level=0) @@ -204,13 +204,13 @@ class PartCategory(MetadataMixin, InvenTreeTree): return parent_categories def get_parameter_templates(self): - """Return parameter templates associated to category""" + """Return parameter templates associated to category.""" prefetch = PartCategoryParameterTemplate.objects.prefetch_related('category', 'parameter_template') return prefetch.filter(category=self.id) def get_subscribers(self, include_parents=True): - """Return a list of users who subscribe to this PartCategory""" + """Return a list of users who subscribe to this PartCategory.""" cats = self.get_ancestors(include_self=True) subscribers = set() @@ -230,11 +230,11 @@ class PartCategory(MetadataMixin, InvenTreeTree): return [s for s in subscribers] def is_starred_by(self, user, **kwargs): - """Returns True if the specified user subscribes to this category""" + """Returns True if the specified user subscribes to this category.""" return user in self.get_subscribers(**kwargs) def set_starred(self, user, status): - """Set the "subscription" status of this PartCategory against the specified user""" + """Set the "subscription" status of this PartCategory against the specified user.""" if not user: return @@ -256,7 +256,7 @@ class PartCategory(MetadataMixin, InvenTreeTree): def rename_part_image(instance, filename): - """Function for renaming a part image file + """Function for renaming a part image file. Args: instance: Instance of a Part object @@ -345,7 +345,7 @@ class Part(MetadataMixin, MPTTModel): return reverse('api-part-list') def api_instance_filters(self): - """Return API query filters for limiting field results against this instance""" + """Return API query filters for limiting field results against this instance.""" return { 'variant_of': { 'exclude_tree': self.pk, @@ -353,7 +353,7 @@ class Part(MetadataMixin, MPTTModel): } def get_context_data(self, request, **kwargs): - """Return some useful context data about this part for template rendering""" + """Return some useful context data about this part for template rendering.""" context = {} context['disabled'] = not self.active @@ -386,10 +386,9 @@ class Part(MetadataMixin, MPTTModel): return context def save(self, *args, **kwargs): - """Overrides the save() function for the Part model. + """Overrides the save function for the Part model. - If the part image has been updated, - then check if the "old" (previous) image is still used by another part. + If the part image has been updated, then check if the "old" (previous) image is still used by another part. If not, it is considered "orphaned" and will be deleted. """ # Get category templates settings @@ -519,8 +518,7 @@ class Part(MetadataMixin, MPTTModel): def checkIfSerialNumberExists(self, sn, exclude_self=False): """Check if a serial number exists for this Part. - Note: Serial numbers must be unique across an entire Part "tree", - so here we filter by the entire tree. + Note: Serial numbers must be unique across an entire Part "tree", so here we filter by the entire tree. """ parts = Part.objects.filter(tree_id=self.tree_id) @@ -626,9 +624,9 @@ class Part(MetadataMixin, MPTTModel): @property def full_name(self): - """Format a 'full name' for this Part based on the format PART_NAME_FORMAT defined in Inventree settings + """Format a 'full name' for this Part based on the format PART_NAME_FORMAT defined in Inventree settings. - As a failsafe option, the following is done + As a failsafe option, the following is done: - IPN (if not null) - Part name @@ -672,18 +670,18 @@ class Part(MetadataMixin, MPTTModel): self.save() def get_absolute_url(self): - """ Return the web URL for viewing this part """ + """Return the web URL for viewing this part.""" return reverse('part-detail', kwargs={'pk': self.id}) def get_image_url(self): - """ Return the URL of the image for this part """ + """Return the URL of the image for this part.""" if self.image: return helpers.getMediaUrl(self.image.url) else: return helpers.getBlankImage() def get_thumbnail_url(self): - """Return the URL of the image thumbnail for this part""" + """Return the URL of the image thumbnail for this part.""" if self.image: return helpers.getMediaUrl(self.image.thumbnail.url) else: @@ -691,11 +689,11 @@ class Part(MetadataMixin, MPTTModel): def validate_unique(self, exclude=None): """Validate that a part is 'unique'. - Uniqueness is checked across the following (case insensitive) fields: - * Name - * IPN - * Revision + Uniqueness is checked across the following (case insensitive) fields: + - Name + - IPN + - Revision e.g. there can exist multiple parts with the same name, but only if they have a different revision or internal part number. @@ -716,7 +714,7 @@ class Part(MetadataMixin, MPTTModel): }) def clean(self): - """Perform cleaning operations for the Part model + """Perform cleaning operations for the Part model. Update trackable status: If this part is trackable, and it is used in the BOM @@ -940,7 +938,7 @@ class Part(MetadataMixin, MPTTModel): responsible = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('Responsible'), related_name='parts_responible') def format_barcode(self, **kwargs): - """Return a JSON string for formatting a barcode for this Part object""" + """Return a JSON string for formatting a barcode for this Part object.""" return helpers.MakeBarcode( "part", self.id, @@ -969,7 +967,7 @@ class Part(MetadataMixin, MPTTModel): return max(total, 0) def requiring_build_orders(self): - """Return list of outstanding build orders which require this part""" + """Return list of outstanding build orders which require this part.""" # List parts that this part is required for parts = self.get_used_in().all() @@ -984,7 +982,7 @@ class Part(MetadataMixin, MPTTModel): return builds def required_build_order_quantity(self): - """Return the quantity of this part required for active build orders""" + """Return the quantity of this part required for active build orders.""" # List active build orders which reference this part builds = self.requiring_build_orders() @@ -1007,7 +1005,7 @@ class Part(MetadataMixin, MPTTModel): return quantity def requiring_sales_orders(self): - """Return a list of sales orders which require this part""" + """Return a list of sales orders which require this part.""" orders = set() # Get a list of line items for open orders which match this part @@ -1022,7 +1020,7 @@ class Part(MetadataMixin, MPTTModel): return orders def required_sales_order_quantity(self): - """Return the quantity of this part required for active sales orders""" + """Return the quantity of this part required for active sales orders.""" # Get a list of line items for open orders which match this part open_lines = OrderModels.SalesOrderLineItem.objects.filter( order__status__in=SalesOrderStatus.OPEN, @@ -1039,7 +1037,7 @@ class Part(MetadataMixin, MPTTModel): return quantity def required_order_quantity(self): - """Return total required to fulfil orders""" + """Return total required to fulfil orders.""" return self.required_build_order_quantity() + self.required_sales_order_quantity() @property @@ -1116,11 +1114,11 @@ class Part(MetadataMixin, MPTTModel): return [s for s in subscribers] def is_starred_by(self, user, **kwargs): - """Return True if the specified user subscribes to this part""" + """Return True if the specified user subscribes to this part.""" return user in self.get_subscribers(**kwargs) def set_starred(self, user, status): - """Set the "subscription" status of this Part against the specified user""" + """Set the "subscription" status of this Part against the specified user.""" if not user: return @@ -1144,7 +1142,7 @@ class Part(MetadataMixin, MPTTModel): @property def can_build(self): - """Return the number of units that can be build with available stock""" + """Return the number of units that can be build with available stock.""" # If this part does NOT have a BOM, result is simply the currently available stock if not self.has_bom: return 0 @@ -1174,7 +1172,7 @@ class Part(MetadataMixin, MPTTModel): @property def active_builds(self): - """ Return a list of outstanding builds. + """Return a list of outstanding builds. Builds marked as 'complete' or 'cancelled' are ignored """ @@ -1182,7 +1180,7 @@ class Part(MetadataMixin, MPTTModel): @property def inactive_builds(self): - """Return a list of inactive builds""" + """Return a list of inactive builds.""" return self.builds.exclude(status__in=BuildStatus.ACTIVE_CODES) @property @@ -1203,7 +1201,7 @@ class Part(MetadataMixin, MPTTModel): return quantity def build_order_allocations(self, **kwargs): - """Return all 'BuildItem' objects which allocate this part to Build objects""" + """Return all 'BuildItem' objects which allocate this part to Build objects.""" include_variants = kwargs.get('include_variants', True) queryset = BuildModels.BuildItem.objects.all() @@ -1219,7 +1217,7 @@ class Part(MetadataMixin, MPTTModel): return queryset def build_order_allocation_count(self, **kwargs): - """Return the total amount of this part allocated to build orders""" + """Return the total amount of this part allocated to build orders.""" query = self.build_order_allocations(**kwargs).aggregate( total=Coalesce( Sum( @@ -1234,7 +1232,7 @@ class Part(MetadataMixin, MPTTModel): return query['total'] def sales_order_allocations(self, **kwargs): - """Return all sales-order-allocation objects which allocate this part to a SalesOrder""" + """Return all sales-order-allocation objects which allocate this part to a SalesOrder.""" include_variants = kwargs.get('include_variants', True) queryset = OrderModels.SalesOrderAllocation.objects.all() @@ -1268,7 +1266,7 @@ class Part(MetadataMixin, MPTTModel): return queryset def sales_order_allocation_count(self, **kwargs): - """Return the total quantity of this part allocated to sales orders""" + """Return the total quantity of this part allocated to sales orders.""" query = self.sales_order_allocations(**kwargs).aggregate( total=Coalesce( Sum( @@ -1283,8 +1281,7 @@ class Part(MetadataMixin, MPTTModel): return query['total'] def allocation_count(self, **kwargs): - """Return the total quantity of stock allocated for this part, against both build orders and sales orders. - """ + """Return the total quantity of stock allocated for this part, against both build orders and sales orders.""" return sum( [ self.build_order_allocation_count(**kwargs), @@ -1313,7 +1310,7 @@ class Part(MetadataMixin, MPTTModel): return query def get_stock_count(self, include_variants=True): - """Return the total "in stock" count for this part""" + """Return the total "in stock" count for this part.""" entries = self.stock_entries(in_stock=True, include_variants=include_variants) query = entries.aggregate(t=Coalesce(Sum('quantity'), Decimal(0))) @@ -1342,7 +1339,6 @@ class Part(MetadataMixin, MPTTModel): Note: This does *not* return a queryset, it returns a Q object, which can be used by some other query operation! Because we want to keep our code DRY! - """ bom_filter = Q(part=self) @@ -1366,7 +1362,7 @@ class Part(MetadataMixin, MPTTModel): return bom_filter def get_bom_items(self, include_inherited=True): - """Return a queryset containing all BOM items for this part + """Return a queryset containing all BOM items for this part. By default, will include inherited BOM items """ @@ -1377,7 +1373,7 @@ class Part(MetadataMixin, MPTTModel): def get_installed_part_options(self, include_inherited=True, include_variants=True): """Return a set of all Parts which can be "installed" into this part, based on the BOM. - arguments: + Arguments: include_inherited - If set, include BomItem entries defined for parent parts include_variants - If set, include variant parts for BomItems which allow variants """ @@ -1443,7 +1439,7 @@ class Part(MetadataMixin, MPTTModel): return self.get_bom_items().count() > 0 def get_trackable_parts(self): - """Return a queryset of all trackable parts in the BOM for this part""" + """Return a queryset of all trackable parts in the BOM for this part.""" queryset = self.get_bom_items() queryset = queryset.filter(sub_part__trackable=True) @@ -1459,21 +1455,19 @@ class Part(MetadataMixin, MPTTModel): @property def bom_count(self): - """Return the number of items contained in the BOM for this part""" + """Return the number of items contained in the BOM for this part.""" return self.get_bom_items().count() @property def used_in_count(self): - """Return the number of part BOMs that this part appears in""" + """Return the number of part BOMs that this part appears in.""" return self.get_used_in().count() def get_bom_hash(self): """Return a checksum hash for the BOM for this part. + Used to determine if the BOM has changed (and needs to be signed off!) - - The hash is calculated by hashing each line item in the BOM. - - returns a string representation of a hash object which can be compared with a stored value + The hash is calculated by hashing each line item in the BOM. Returns a string representation of a hash object which can be compared with a stored value """ result_hash = hashlib.md5(str(self.id).encode()) @@ -1562,12 +1556,12 @@ class Part(MetadataMixin, MPTTModel): @property def supplier_count(self): - """Return the number of supplier parts available for this part""" + """Return the number of supplier parts available for this part.""" return self.supplier_parts.count() @property def has_pricing_info(self, internal=False): - """Return true if there is pricing information for this part""" + """Return true if there is pricing information for this part.""" return self.get_price_range(internal=internal) is not None @property @@ -1581,7 +1575,7 @@ class Part(MetadataMixin, MPTTModel): return True def get_price_info(self, quantity=1, buy=True, bom=True, internal=False): - """Return a simplified pricing string for this part + """Return a simplified pricing string for this part. Args: quantity: Number of units to calculate price for @@ -1632,8 +1626,8 @@ class Part(MetadataMixin, MPTTModel): def get_bom_price_range(self, quantity=1, internal=False, purchase=False): """Return the price range of the BOM for this part. - Adds the minimum price for all components in the BOM. + Adds the minimum price for all components in the BOM. Note: If the BOM contains items without pricing information, these items cannot be included in the BOM! """ @@ -1674,8 +1668,9 @@ class Part(MetadataMixin, MPTTModel): return (min_price, max_price) def get_price_range(self, quantity=1, buy=True, bom=True, internal=False, purchase=False): - """Return the price range for this part. This price can be either: + """Return the price range for this part. + This price can be either: - Supplier price (if purchased from suppliers) - BOM price (if built from other parts) - Internal price (if set for the part) @@ -1722,7 +1717,7 @@ class Part(MetadataMixin, MPTTModel): @property def price_breaks(self): - """Return the associated price breaks in the correct order""" + """Return the associated price breaks in the correct order.""" return self.salepricebreaks.order_by('quantity').all() @property @@ -1730,9 +1725,9 @@ class Part(MetadataMixin, MPTTModel): return self.get_price(1) def add_price_break(self, quantity, price): - """Create a new price break for this part + """Create a new price break for this part. - args: + Args: quantity - Numerical quantity price - Must be a Money object """ @@ -1755,7 +1750,7 @@ class Part(MetadataMixin, MPTTModel): @property def internal_price_breaks(self): - """Return the associated price breaks in the correct order""" + """Return the associated price breaks in the correct order.""" return self.internalpricebreaks.order_by('quantity').all() @property @@ -1778,7 +1773,7 @@ class Part(MetadataMixin, MPTTModel): def copy_bom_from(self, other, clear=True, **kwargs): """Copy the BOM from another part. - args: + Args: other - The part to copy the BOM from clear - Remove existing BOM items first (default=True) """ @@ -1867,8 +1862,8 @@ class Part(MetadataMixin, MPTTModel): @transaction.atomic def deep_copy(self, other, **kwargs): """Duplicates non-field data from another part. - Does not alter the normal fields of this part, - but can be used to copy other data linked by ForeignKey refernce. + + Does not alter the normal fields of this part, but can be used to copy other data linked by ForeignKey refernce. Keyword Args: image: If True, copies Part image (default = True) @@ -1901,9 +1896,10 @@ class Part(MetadataMixin, MPTTModel): def getTestTemplates(self, required=None, include_parent=True): """Return a list of all test templates associated with this Part. + These are used for validation of a StockItem. - args: + Args: required: Set to True or False to filter by "required" status include_parent: Set to True to traverse upwards """ @@ -1943,7 +1939,7 @@ class Part(MetadataMixin, MPTTModel): return attachments def sales_orders(self): - """Return a list of sales orders which reference this part""" + """Return a list of sales orders which reference this part.""" orders = [] for line in self.sales_order_line_items.all().prefetch_related('order'): @@ -1953,7 +1949,7 @@ class Part(MetadataMixin, MPTTModel): return orders def purchase_orders(self): - """Return a list of purchase orders which reference this part""" + """Return a list of purchase orders which reference this part.""" orders = [] for part in self.supplier_parts.all().prefetch_related('purchase_order_line_items'): @@ -1964,11 +1960,11 @@ class Part(MetadataMixin, MPTTModel): return orders def open_purchase_orders(self): - """Return a list of open purchase orders against this part""" + """Return a list of open purchase orders against this part.""" return [order for order in self.purchase_orders() if order.status in PurchaseOrderStatus.OPEN] def closed_purchase_orders(self): - """Return a list of closed purchase orders against this part""" + """Return a list of closed purchase orders against this part.""" return [order for order in self.purchase_orders() if order.status not in PurchaseOrderStatus.OPEN] @property @@ -1991,12 +1987,13 @@ class Part(MetadataMixin, MPTTModel): return quantity - received def get_parameters(self): - """Return all parameters for this part, ordered by name""" + """Return all parameters for this part, ordered by name.""" return self.parameters.order_by('template__name') def parameters_map(self): - """Return a map (dict) of parameter values assocaited with this Part instance, - of the form: + """Return a map (dict) of parameter values assocaited with this Part instance, of the form. + + Example: { "name_1": "value_1", "name_2": "value_2", @@ -2031,7 +2028,7 @@ class Part(MetadataMixin, MPTTModel): return self.get_conversion_options().count() > 0 def get_conversion_options(self): - """Return options for converting this part to a "variant" within the same tree + """Return options for converting this part to a "variant" within the same tree. a) Variants underneath this one b) Immediate parent @@ -2068,8 +2065,9 @@ class Part(MetadataMixin, MPTTModel): def get_related_parts(self): """Return list of tuples for all related parts: - - first value is PartRelated object - - second value is matching Part object + + - first value is PartRelated object + - second value is matching Part object """ related_parts = [] @@ -2092,13 +2090,13 @@ class Part(MetadataMixin, MPTTModel): return len(self.get_related_parts()) def is_part_low_on_stock(self): - """Returns True if the total stock for this part is less than the minimum stock level""" + """Returns True if the total stock for this part is less than the minimum stock level.""" return self.get_stock_count() < self.minimum_stock @receiver(post_save, sender=Part, dispatch_uid='part_post_save_log') def after_save_part(sender, instance: Part, created, **kwargs): - """Function to be executed after a Part is saved""" + """Function to be executed after a Part is saved.""" from part import tasks as part_tasks if not created and not InvenTree.ready.isImportingData(): @@ -2109,7 +2107,7 @@ def after_save_part(sender, instance: Part, created, **kwargs): class PartAttachment(InvenTreeAttachment): - """Model for storing file attachments against a Part object""" + """Model for storing file attachments against a Part object.""" @staticmethod def get_api_url(): @@ -2123,7 +2121,7 @@ class PartAttachment(InvenTreeAttachment): class PartSellPriceBreak(common.models.PriceBreak): - """Represents a price break for selling this part""" + """Represents a price break for selling this part.""" @staticmethod def get_api_url(): @@ -2141,7 +2139,7 @@ class PartSellPriceBreak(common.models.PriceBreak): class PartInternalPriceBreak(common.models.PriceBreak): - """Represents a price break for internally selling this part""" + """Represents a price break for internally selling this part.""" @staticmethod def get_api_url(): @@ -2198,8 +2196,7 @@ class PartCategoryStar(models.Model): class PartTestTemplate(models.Model): - """A PartTestTemplate defines a 'template' for a test which is required to be run - against a StockItem (an instance of the Part). + """A PartTestTemplate defines a 'template' for a test which is required to be run against a StockItem (an instance of the Part). The test template applies "recursively" to part variants, allowing tests to be defined in a heirarchy. @@ -2256,7 +2253,7 @@ class PartTestTemplate(models.Model): @property def key(self): - """ Generate a key for this test """ + """Generate a key for this test.""" return helpers.generateTestKey(self.test_name) part = models.ForeignKey( @@ -2299,17 +2296,16 @@ class PartTestTemplate(models.Model): def validate_template_name(name): - """Prevent illegal characters in "name" field for PartParameterTemplate""" + """Prevent illegal characters in "name" field for PartParameterTemplate.""" for c in "!@#$%^&*()<>{}[].,?/\\|~`_+-=\'\"": if c in str(name): raise ValidationError(_(f"Illegal character in template name ({c})")) class PartParameterTemplate(models.Model): - """A PartParameterTemplate provides a template for key:value pairs for extra - parameters fields/values to be added to a Part. - This allows users to arbitrarily assign data fields to a Part - beyond the built-in attributes. + """A PartParameterTemplate provides a template for key:value pairs for extra parameters fields/values to be added to a Part. + + This allows users to arbitrarily assign data fields to a Part beyond the built-in attributes. Attributes: name: The name (key) of the Parameter [string] @@ -2396,10 +2392,7 @@ class PartParameter(models.Model): class PartCategoryParameterTemplate(models.Model): - """A PartCategoryParameterTemplate creates a unique relationship between a PartCategory - and a PartParameterTemplate. - Multiple PartParameterTemplate instances can be associated to a PartCategory to drive - a default list of parameter templates attached to a Part instance upon creation. + """A PartCategoryParameterTemplate creates a unique relationship between a PartCategory and a PartParameterTemplate. Multiple PartParameterTemplate instances can be associated to a PartCategory to drive a default list of parameter templates attached to a Part instance upon creation. Attributes: category: Reference to a single PartCategory object @@ -2534,11 +2527,11 @@ class BomItem(models.Model, DataImportMixin): return valid_parts def is_stock_item_valid(self, stock_item): - """Check if the provided StockItem object is "valid" for assignment against this BomItem""" + """Check if the provided StockItem object is "valid" for assignment against this BomItem.""" return stock_item.part in self.get_valid_parts_for_allocation() def get_stock_filter(self): - """Return a queryset filter for selecting StockItems which match this BomItem + """Return a queryset filter for selecting StockItems which match this BomItem. - Allow stock from all directly specified substitute parts - If allow_variants is True, allow all part variants @@ -2638,7 +2631,7 @@ class BomItem(models.Model, DataImportMixin): @property def is_line_valid(self): - """Check if this line item has been validated by the user""" + """Check if this line item has been validated by the user.""" # Ensure an empty checksum returns False if len(self.checksum) == 0: return False @@ -2699,7 +2692,7 @@ class BomItem(models.Model, DataImportMixin): n=decimal2string(self.quantity)) def get_overage_quantity(self, quantity): - """Calculate overage quantity""" + """Calculate overage quantity.""" # Most of the time overage string will be empty if len(self.overage) == 0: return 0 @@ -2740,8 +2733,7 @@ class BomItem(models.Model, DataImportMixin): return 0 def get_required_quantity(self, build_quantity): - """Calculate the required part quantity, based on the supplier build_quantity. - Includes overage estimate in the returned value. + """Calculate the required part quantity, based on the supplier build_quantity. Includes overage estimate in the returned value. Args: build_quantity: Number of parts to build @@ -2782,8 +2774,7 @@ class BomItem(models.Model, DataImportMixin): class BomItemSubstitute(models.Model): - """A BomItemSubstitute provides a specification for alternative parts, - which can be used in a bill of materials. + """A BomItemSubstitute provides a specification for alternative parts, which can be used in a bill of materials. Attributes: bom_item: Link to the parent BomItem instance @@ -2852,7 +2843,7 @@ class PartRelated(models.Model): return f'{self.part_1} <--> {self.part_2}' def validate(self, part_1, part_2): - """Validate that the two parts relationship is unique""" + """Validate that the two parts relationship is unique.""" validate = True parts = Part.objects.all() @@ -2872,7 +2863,7 @@ class PartRelated(models.Model): return validate def clean(self): - """Overwrite clean method to check that relation is unique""" + """Overwrite clean method to check that relation is unique.""" validate = self.validate(self.part_1, self.part_2) if not validate: diff --git a/InvenTree/part/serializers.py b/InvenTree/part/serializers.py index 3a9bd4bb7a..9e9f5ac7d1 100644 --- a/InvenTree/part/serializers.py +++ b/InvenTree/part/serializers.py @@ -1,4 +1,4 @@ -"""JSON serializers for Part app""" +"""JSON serializers for Part app.""" import imghdr from decimal import Decimal @@ -35,15 +35,14 @@ from .models import (BomItem, BomItemSubstitute, Part, PartAttachment, class CategorySerializer(InvenTreeModelSerializer): - """Serializer for PartCategory""" + """Serializer for PartCategory.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_starred(self, category): - """Return True if the category is directly "starred" by the current user""" - + """Return True if the category is directly "starred" by the current user.""" return category in self.context.get('starred_categories', []) url = serializers.CharField(source='get_absolute_url', read_only=True) @@ -72,7 +71,7 @@ class CategorySerializer(InvenTreeModelSerializer): class CategoryTree(InvenTreeModelSerializer): - """Serializer for PartCategory tree""" + """Serializer for PartCategory tree.""" class Meta: model = PartCategory @@ -84,7 +83,7 @@ class CategoryTree(InvenTreeModelSerializer): class PartAttachmentSerializer(InvenTreeAttachmentSerializer): - """Serializer for the PartAttachment class""" + """Serializer for the PartAttachment class.""" class Meta: model = PartAttachment @@ -105,7 +104,7 @@ class PartAttachmentSerializer(InvenTreeAttachmentSerializer): class PartTestTemplateSerializer(InvenTreeModelSerializer): - """Serializer for the PartTestTemplate class""" + """Serializer for the PartTestTemplate class.""" key = serializers.CharField(read_only=True) @@ -195,7 +194,7 @@ class PartThumbSerializer(serializers.Serializer): class PartThumbSerializerUpdate(InvenTreeModelSerializer): - """Serializer for updating Part thumbnail""" + """Serializer for updating Part thumbnail.""" def validate_image(self, value): """Check that file is an image.""" @@ -214,7 +213,7 @@ class PartThumbSerializerUpdate(InvenTreeModelSerializer): class PartParameterTemplateSerializer(InvenTreeModelSerializer): - """JSON serializer for the PartParameterTemplate model""" + """JSON serializer for the PartParameterTemplate model.""" class Meta: model = PartParameterTemplate @@ -226,7 +225,7 @@ class PartParameterTemplateSerializer(InvenTreeModelSerializer): class PartParameterSerializer(InvenTreeModelSerializer): - """JSON serializers for the PartParameter model""" + """JSON serializers for the PartParameter model.""" template_detail = PartParameterTemplateSerializer(source='template', many=False, read_only=True) @@ -498,7 +497,7 @@ class PartSerializer(InvenTreeModelSerializer): class PartRelationSerializer(InvenTreeModelSerializer): - """Serializer for a PartRelated model""" + """Serializer for a PartRelated model.""" part_1_detail = PartSerializer(source='part_1', read_only=True, many=False) part_2_detail = PartSerializer(source='part_2', read_only=True, many=False) @@ -515,7 +514,7 @@ class PartRelationSerializer(InvenTreeModelSerializer): class PartStarSerializer(InvenTreeModelSerializer): - """Serializer for a PartStar object""" + """Serializer for a PartStar object.""" partname = serializers.CharField(source='part.full_name', read_only=True) username = serializers.CharField(source='user.username', read_only=True) @@ -532,7 +531,7 @@ class PartStarSerializer(InvenTreeModelSerializer): class BomItemSubstituteSerializer(InvenTreeModelSerializer): - """Serializer for the BomItemSubstitute class""" + """Serializer for the BomItemSubstitute class.""" part_detail = PartBriefSerializer(source='part', read_only=True, many=False) @@ -547,7 +546,7 @@ class BomItemSubstituteSerializer(InvenTreeModelSerializer): class BomItemSerializer(InvenTreeModelSerializer): - """Serializer for BomItem object""" + """Serializer for BomItem object.""" price_range = serializers.CharField(read_only=True) @@ -638,7 +637,6 @@ class BomItemSerializer(InvenTreeModelSerializer): Annotations: available_stock: The amount of stock available for the sub_part Part object """ - """ Construct an "available stock" quantity: available_stock = total_stock - build_order_allocations - sales_order_allocations @@ -767,7 +765,7 @@ class BomItemSerializer(InvenTreeModelSerializer): return queryset def get_purchase_price_range(self, obj): - """Return purchase price range""" + """Return purchase price range.""" try: purchase_price_min = obj.purchase_price_min except AttributeError: @@ -797,7 +795,7 @@ class BomItemSerializer(InvenTreeModelSerializer): return purchase_price_range def get_purchase_price_avg(self, obj): - """Return purchase price average""" + """Return purchase price average.""" try: purchase_price_avg = obj.purchase_price_avg except AttributeError: @@ -843,7 +841,7 @@ class BomItemSerializer(InvenTreeModelSerializer): class CategoryParameterTemplateSerializer(InvenTreeModelSerializer): - """Serializer for PartCategoryParameterTemplate""" + """Serializer for PartCategoryParameterTemplate.""" parameter_template = PartParameterTemplateSerializer(many=False, read_only=True) @@ -862,7 +860,7 @@ class CategoryParameterTemplateSerializer(InvenTreeModelSerializer): class PartCopyBOMSerializer(serializers.Serializer): - """Serializer for copying a BOM from another part""" + """Serializer for copying a BOM from another part.""" class Meta: fields = [ @@ -883,7 +881,7 @@ class PartCopyBOMSerializer(serializers.Serializer): ) def validate_part(self, part): - """Check that a 'valid' part was selected""" + """Check that a 'valid' part was selected.""" return part remove_existing = serializers.BooleanField( @@ -911,7 +909,7 @@ class PartCopyBOMSerializer(serializers.Serializer): ) def save(self): - """Actually duplicate the BOM""" + """Actually duplicate the BOM.""" base_part = self.context['part'] data = self.validated_data @@ -961,8 +959,7 @@ class BomImportUploadSerializer(DataFileUploadSerializer): class BomImportExtractSerializer(DataFileExtractSerializer): - """ - """ + """""" TARGET_MODEL = BomItem diff --git a/InvenTree/part/settings.py b/InvenTree/part/settings.py index af904e56fd..e5706a87ff 100644 --- a/InvenTree/part/settings.py +++ b/InvenTree/part/settings.py @@ -1,38 +1,38 @@ -"""User-configurable settings for the Part app""" +"""User-configurable settings for the Part app.""" from common.models import InvenTreeSetting def part_assembly_default(): - """Returns the default value for the 'assembly' field of a Part object""" + """Returns the default value for the 'assembly' field of a Part object.""" return InvenTreeSetting.get_setting('PART_ASSEMBLY') def part_template_default(): - """Returns the default value for the 'is_template' field of a Part object""" + """Returns the default value for the 'is_template' field of a Part object.""" return InvenTreeSetting.get_setting('PART_TEMPLATE') def part_virtual_default(): - """Returns the default value for the 'is_virtual' field of Part object""" + """Returns the default value for the 'is_virtual' field of Part object.""" return InvenTreeSetting.get_setting('PART_VIRTUAL') def part_component_default(): - """Returns the default value for the 'component' field of a Part object""" + """Returns the default value for the 'component' field of a Part object.""" return InvenTreeSetting.get_setting('PART_COMPONENT') def part_purchaseable_default(): - """Returns the default value for the 'purchasable' field for a Part object""" + """Returns the default value for the 'purchasable' field for a Part object.""" return InvenTreeSetting.get_setting('PART_PURCHASEABLE') def part_salable_default(): - """Returns the default value for the 'salable' field for a Part object""" + """Returns the default value for the 'salable' field for a Part object.""" return InvenTreeSetting.get_setting('PART_SALABLE') def part_trackable_default(): - """Returns the default value for the 'trackable' field for a Part object""" + """Returns the default value for the 'trackable' field for a Part object.""" return InvenTreeSetting.get_setting('PART_TRACKABLE') diff --git a/InvenTree/part/templatetags/inventree_extras.py b/InvenTree/part/templatetags/inventree_extras.py index bebfc36939..2cdb78d326 100644 --- a/InvenTree/part/templatetags/inventree_extras.py +++ b/InvenTree/part/templatetags/inventree_extras.py @@ -28,7 +28,7 @@ logger = logging.getLogger('inventree') @register.simple_tag() def define(value, *args, **kwargs): - """Shortcut function to overcome the shortcomings of the django templating language + """Shortcut function to overcome the shortcomings of the django templating language. Use as follows: {% define "hello_world" as hello %} @@ -39,7 +39,7 @@ def define(value, *args, **kwargs): @register.simple_tag(takes_context=True) def render_date(context, date_object): - """Renders a date according to the preference of the provided user + """Renders a date according to the preference of the provided user. Note that the user preference is stored using the formatting adopted by moment.js, which differs from the python formatting! @@ -96,37 +96,37 @@ def render_date(context, date_object): @register.simple_tag() def decimal(x, *args, **kwargs): - """Simplified rendering of a decimal number""" + """Simplified rendering of a decimal number.""" return InvenTree.helpers.decimal2string(x) @register.simple_tag() def str2bool(x, *args, **kwargs): - """Convert a string to a boolean value""" + """Convert a string to a boolean value.""" return InvenTree.helpers.str2bool(x) @register.simple_tag() def inrange(n, *args, **kwargs): - """Return range(n) for iterating through a numeric quantity""" + """Return range(n) for iterating through a numeric quantity.""" return range(n) @register.simple_tag() def multiply(x, y, *args, **kwargs): - """Multiply two numbers together""" + """Multiply two numbers together.""" return InvenTree.helpers.decimal2string(x * y) @register.simple_tag() def add(x, y, *args, **kwargs): - """Add two numbers together""" + """Add two numbers together.""" return x + y @register.simple_tag() def to_list(*args): - """Return the input arguments as list""" + """Return the input arguments as list.""" return args @@ -138,13 +138,13 @@ def part_allocation_count(build, part, *args, **kwargs): @register.simple_tag() def inventree_in_debug_mode(*args, **kwargs): - """Return True if the server is running in DEBUG mode""" + """Return True if the server is running in DEBUG mode.""" return djangosettings.DEBUG @register.simple_tag() def inventree_show_about(user, *args, **kwargs): - """Return True if the about modal should be shown""" + """Return True if the about modal should be shown.""" if InvenTreeSetting.get_setting('INVENTREE_RESTRICT_ABOUT') and not user.is_superuser: return False return True @@ -152,19 +152,19 @@ def inventree_show_about(user, *args, **kwargs): @register.simple_tag() def inventree_docker_mode(*args, **kwargs): - """Return True if the server is running as a Docker image""" + """Return True if the server is running as a Docker image.""" return djangosettings.DOCKER @register.simple_tag() def plugins_enabled(*args, **kwargs): - """Return True if plugins are enabled for the server instance""" + """Return True if plugins are enabled for the server instance.""" return djangosettings.PLUGINS_ENABLED @register.simple_tag() def inventree_db_engine(*args, **kwargs): - """Return the InvenTree database backend e.g. 'postgresql'""" + """Return the InvenTree database backend e.g. 'postgresql'.""" db = djangosettings.DATABASES['default'] engine = db.get('ENGINE', _('Unknown database')) @@ -176,7 +176,7 @@ def inventree_db_engine(*args, **kwargs): @register.simple_tag() def inventree_instance_name(*args, **kwargs): - """Return the InstanceName associated with the current database""" + """Return the InstanceName associated with the current database.""" return version.inventreeInstanceName() @@ -188,19 +188,19 @@ def inventree_title(*args, **kwargs): @register.simple_tag() def inventree_base_url(*args, **kwargs): - """Return the INVENTREE_BASE_URL setting""" + """Return the INVENTREE_BASE_URL setting.""" return InvenTreeSetting.get_setting('INVENTREE_BASE_URL') @register.simple_tag() def python_version(*args, **kwargs): - """Return the current python version""" + """Return the current python version.""" return sys.version.split(' ')[0] @register.simple_tag() def inventree_version(shortstring=False, *args, **kwargs): - """Return InvenTree version string""" + """Return InvenTree version string.""" if shortstring: return _("{title} v{version}".format( title=version.inventreeInstanceTitle(), @@ -226,37 +226,37 @@ def inventree_docs_version(*args, **kwargs): @register.simple_tag() def inventree_api_version(*args, **kwargs): - """Return InvenTree API version""" + """Return InvenTree API version.""" return version.inventreeApiVersion() @register.simple_tag() def django_version(*args, **kwargs): - """Return Django version string""" + """Return Django version string.""" return version.inventreeDjangoVersion() @register.simple_tag() def inventree_commit_hash(*args, **kwargs): - """Return InvenTree git commit hash string""" + """Return InvenTree git commit hash string.""" return version.inventreeCommitHash() @register.simple_tag() def inventree_commit_date(*args, **kwargs): - """Return InvenTree git commit date string""" + """Return InvenTree git commit date string.""" return version.inventreeCommitDate() @register.simple_tag() def inventree_github_url(*args, **kwargs): - """Return URL for InvenTree github site""" + """Return URL for InvenTree github site.""" return "https://github.com/InvenTree/InvenTree/" @register.simple_tag() def inventree_docs_url(*args, **kwargs): - """Return URL for InvenTree documenation site""" + """Return URL for InvenTree documenation site.""" tag = version.inventreeDocsVersion() return f"https://inventree.readthedocs.io/en/{tag}" @@ -264,19 +264,19 @@ def inventree_docs_url(*args, **kwargs): @register.simple_tag() def inventree_credits_url(*args, **kwargs): - """Return URL for InvenTree credits site""" + """Return URL for InvenTree credits site.""" return "https://inventree.readthedocs.io/en/latest/credits/" @register.simple_tag() def default_currency(*args, **kwargs): - """Returns the default currency code""" + """Returns the default currency code.""" return currency_code_default() @register.simple_tag() def setting_object(key, *args, **kwargs): - """Return a setting object speciifed by the given key + """Return a setting object speciifed by the given key. (Or return None if the setting does not exist) if a user-setting was requested return that @@ -299,7 +299,7 @@ def setting_object(key, *args, **kwargs): @register.simple_tag() def settings_value(key, *args, **kwargs): - """Return a settings value specified by the given key""" + """Return a settings value specified by the given key.""" if 'user' in kwargs: if not kwargs['user'] or (kwargs['user'] and kwargs['user'].is_authenticated is False): return InvenTreeUserSetting.get_setting(key) @@ -310,25 +310,25 @@ def settings_value(key, *args, **kwargs): @register.simple_tag() def user_settings(user, *args, **kwargs): - """Return all USER settings as a key:value dict""" + """Return all USER settings as a key:value dict.""" return InvenTreeUserSetting.allValues(user=user) @register.simple_tag() def global_settings(*args, **kwargs): - """Return all GLOBAL InvenTree settings as a key:value dict""" + """Return all GLOBAL InvenTree settings as a key:value dict.""" return InvenTreeSetting.allValues() @register.simple_tag() def visible_global_settings(*args, **kwargs): - """Return any global settings which are not marked as 'hidden'""" + """Return any global settings which are not marked as 'hidden'.""" return InvenTreeSetting.allValues(exclude_hidden=True) @register.simple_tag() def progress_bar(val, max_val, *args, **kwargs): - """Render a progress bar element""" + """Render a progress bar element.""" item_id = kwargs.get('id', 'progress-bar') val = InvenTree.helpers.normalize(val) @@ -379,7 +379,7 @@ def get_color_theme_css(username): @register.simple_tag() def get_user_color_theme(username): - """Get current user color theme""" + """Get current user color theme.""" try: user_theme = ColorTheme.objects.filter(user=username).get() user_theme_name = user_theme.name @@ -393,7 +393,7 @@ def get_user_color_theme(username): @register.simple_tag() def get_available_themes(*args, **kwargs): - """Return the available theme choices""" + """Return the available theme choices.""" themes = [] for key, name in ColorTheme.get_color_themes_choices(): @@ -425,7 +425,7 @@ def primitive_to_javascript(primitive): @register.filter def keyvalue(dict, key): - """Access to key of supplied dict + """Access to key of supplied dict. Usage: {% mydict|keyvalue:mykey %} @@ -435,7 +435,7 @@ def keyvalue(dict, key): @register.simple_tag() def call_method(obj, method_name, *args): - """Enables calling model methods / functions from templates with arguments + """Enables calling model methods / functions from templates with arguments. Usage: {% call_method model_object 'fnc_name' argument1 %} @@ -446,7 +446,7 @@ def call_method(obj, method_name, *args): @register.simple_tag() def authorized_owners(group): - """Return authorized owners""" + """Return authorized owners.""" owners = [] try: @@ -464,33 +464,33 @@ def authorized_owners(group): @register.simple_tag() def object_link(url_name, pk, ref): - """Return highlighted link to object""" + """Return highlighted link to object.""" ref_url = reverse(url_name, kwargs={'pk': pk}) return mark_safe('{}'.format(ref_url, ref)) @register.simple_tag() def mail_configured(): - """Return if mail is configured""" + """Return if mail is configured.""" return bool(settings.EMAIL_HOST) @register.simple_tag() def inventree_customize(reference, *args, **kwargs): - """Return customization values for the user interface""" + """Return customization values for the user interface.""" return djangosettings.CUSTOMIZE.get(reference, '') @register.simple_tag() def inventree_logo(*args, **kwargs): - """Return the path to the logo-file""" + """Return the path to the logo-file.""" if settings.CUSTOM_LOGO: return default_storage.url(settings.CUSTOM_LOGO) return static('img/inventree.png') class I18nStaticNode(StaticNode): - """Custom StaticNode + """Custom StaticNode. Replaces a variable named *lng* in the path with the current language """ diff --git a/InvenTree/part/templatetags/status_codes.py b/InvenTree/part/templatetags/status_codes.py index 5633599698..57c9fe630f 100644 --- a/InvenTree/part/templatetags/status_codes.py +++ b/InvenTree/part/templatetags/status_codes.py @@ -11,19 +11,19 @@ register = template.Library() @register.simple_tag def purchase_order_status_label(key, *args, **kwargs): - """Render a PurchaseOrder status label""" + """Render a PurchaseOrder status label.""" return mark_safe(PurchaseOrderStatus.render(key, large=kwargs.get('large', False))) @register.simple_tag def sales_order_status_label(key, *args, **kwargs): - """Render a SalesOrder status label""" + """Render a SalesOrder status label.""" return mark_safe(SalesOrderStatus.render(key, large=kwargs.get('large', False))) @register.simple_tag def stock_status_label(key, *args, **kwargs): - """Render a StockItem status label""" + """Render a StockItem status label.""" return mark_safe(StockStatus.render(key, large=kwargs.get('large', False))) @@ -34,5 +34,5 @@ def stock_status_text(key, *args, **kwargs): @register.simple_tag def build_status_label(key, *args, **kwargs): - """Render a Build status label""" + """Render a Build status label.""" return mark_safe(BuildStatus.render(key, large=kwargs.get('large', False))) diff --git a/InvenTree/part/test_api.py b/InvenTree/part/test_api.py index 561c98695d..8d32ba1a09 100644 --- a/InvenTree/part/test_api.py +++ b/InvenTree/part/test_api.py @@ -16,7 +16,7 @@ from stock.models import StockItem, StockLocation class PartCategoryAPITest(InvenTreeAPITestCase): - """Unit tests for the PartCategory API""" + """Unit tests for the PartCategory API.""" fixtures = [ 'category', @@ -73,7 +73,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 5) def test_category_metadata(self): - """Test metadata endpoint for the PartCategory""" + """Test metadata endpoint for the PartCategory.""" cat = PartCategory.objects.get(pk=1) cat.metadata = { @@ -94,7 +94,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase): class PartOptionsAPITest(InvenTreeAPITestCase): - """Tests for the various OPTIONS endpoints in the /part/ API + """Tests for the various OPTIONS endpoints in the /part/ API. Ensure that the required field details are provided! """ @@ -108,7 +108,7 @@ class PartOptionsAPITest(InvenTreeAPITestCase): super().setUp() def test_part(self): - """Test the Part API OPTIONS""" + """Test the Part API OPTIONS.""" actions = self.getActions(reverse('api-part-list'))['POST'] # Check that a bunch o' fields are contained @@ -142,7 +142,7 @@ class PartOptionsAPITest(InvenTreeAPITestCase): self.assertEqual(category['help_text'], 'Part category') def test_category(self): - """Test the PartCategory API OPTIONS endpoint""" + """Test the PartCategory API OPTIONS endpoint.""" actions = self.getActions(reverse('api-part-category-list')) # actions should *not* contain 'POST' as we do not have the correct role @@ -161,7 +161,7 @@ class PartOptionsAPITest(InvenTreeAPITestCase): self.assertEqual(loc['api_url'], reverse('api-location-list')) def test_bom_item(self): - """Test the BomItem API OPTIONS endpoint""" + """Test the BomItem API OPTIONS endpoint.""" actions = self.getActions(reverse('api-bom-list'))['POST'] inherited = actions['inherited'] @@ -184,7 +184,7 @@ class PartOptionsAPITest(InvenTreeAPITestCase): class PartAPITest(InvenTreeAPITestCase): - """Series of tests for the Part DRF API + """Series of tests for the Part DRF API. - Tests for Part API - Tests for PartCategory API @@ -256,7 +256,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 3) def test_add_categories(self): - """Check that we can add categories""" + """Check that we can add categories.""" data = { 'name': 'Animals', 'description': 'All animals go here' @@ -323,7 +323,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(part['category'], 2) def test_include_children(self): - """Test the special 'include_child_categories' flag + """Test the special 'include_child_categories' flag. If provided, parts are provided for ANY child category (recursive) """ @@ -405,7 +405,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_get_thumbs(self): - """Return list of part thumbnails""" + """Return list of part thumbnails.""" url = reverse('api-part-thumbs') response = self.client.get(url) @@ -413,7 +413,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(response.status_code, status.HTTP_200_OK) def test_paginate(self): - """Test pagination of the Part list API""" + """Test pagination of the Part list API.""" for n in [1, 5, 10]: response = self.get(reverse('api-part-list'), {'limit': n}) @@ -476,7 +476,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertFalse(response.data['purchaseable']) def test_initial_stock(self): - """Tests for initial stock quantity creation""" + """Tests for initial stock quantity creation.""" url = reverse('api-part-list') # Track how many parts exist at the start of this test @@ -530,7 +530,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(new_part.total_stock, 12345) def test_initial_supplier_data(self): - """Tests for initial creation of supplier / manufacturer data""" + """Tests for initial creation of supplier / manufacturer data.""" url = reverse('api-part-list') n = Part.objects.count() @@ -592,7 +592,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(new_part.manufacturer_parts.count(), 1) def test_strange_chars(self): - """Test that non-standard ASCII chars are accepted""" + """Test that non-standard ASCII chars are accepted.""" url = reverse('api-part-list') name = "Kaltgerätestecker" @@ -699,10 +699,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 101) def test_variant_stock(self): - """ - Unit tests for the 'variant_stock' annotation, - which provides a stock count for *variant* parts - """ + """Unit tests for the 'variant_stock' annotation, which provides a stock count for *variant* parts.""" # Ensure the MPTT structure is in a known state before running tests Part.objects.rebuild() @@ -786,7 +783,7 @@ class PartAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['variant_stock'], 500) def test_part_download(self): - """Test download of part data via the API""" + """Test download of part data via the API.""" url = reverse('api-part-list') required_cols = [ @@ -838,7 +835,7 @@ class PartAPITest(InvenTreeAPITestCase): class PartDetailTests(InvenTreeAPITestCase): - """Test that we can create / edit / delete Part objects via the API""" + """Test that we can create / edit / delete Part objects via the API.""" fixtures = [ 'category', @@ -933,7 +930,7 @@ class PartDetailTests(InvenTreeAPITestCase): self.assertEqual(Part.objects.count(), n) def test_duplicates(self): - """Check that trying to create 'duplicate' parts results in errors""" + """Check that trying to create 'duplicate' parts results in errors.""" # Create a part response = self.client.post(reverse('api-part-list'), { 'name': 'part', @@ -1009,7 +1006,7 @@ class PartDetailTests(InvenTreeAPITestCase): self.assertEqual(response.status_code, 200) def test_image_upload(self): - """Test that we can upload an image to the part API""" + """Test that we can upload an image to the part API.""" self.assignRole('part.add') # Create a new part @@ -1077,7 +1074,7 @@ class PartDetailTests(InvenTreeAPITestCase): self.assertIsNotNone(p.image) def test_details(self): - """Test that the required details are available""" + """Test that the required details are available.""" p = Part.objects.get(pk=1) url = reverse('api-part-detail', kwargs={'pk': 1}) @@ -1106,7 +1103,7 @@ class PartDetailTests(InvenTreeAPITestCase): self.assertEqual(data['unallocated_stock'], 9000) def test_part_metadata(self): - """Tests for the part metadata endpoint""" + """Tests for the part metadata endpoint.""" url = reverse('api-part-metadata', kwargs={'pk': 1}) part = Part.objects.get(pk=1) @@ -1216,7 +1213,7 @@ class PartAPIAggregationTest(InvenTreeAPITestCase): self.assertTrue(False) # pragma: no cover def test_stock_quantity(self): - """Simple test for the stock quantity""" + """Simple test for the stock quantity.""" data = self.get_part_data() self.assertEqual(data['in_stock'], 600) @@ -1383,7 +1380,7 @@ class PartAPIAggregationTest(InvenTreeAPITestCase): class BomItemTest(InvenTreeAPITestCase): - """Unit tests for the BomItem API""" + """Unit tests for the BomItem API.""" fixtures = [ 'category', @@ -1404,7 +1401,7 @@ class BomItemTest(InvenTreeAPITestCase): super().setUp() def test_bom_list(self): - """Tests for the BomItem list endpoint""" + """Tests for the BomItem list endpoint.""" # How many BOM items currently exist in the database? n = BomItem.objects.count() @@ -1469,7 +1466,7 @@ class BomItemTest(InvenTreeAPITestCase): self.assertTrue(key in el) def test_get_bom_detail(self): - """Get the detail view for a single BomItem object""" + """Get the detail view for a single BomItem object.""" url = reverse('api-bom-item-detail', kwargs={'pk': 3}) response = self.get(url, expected_code=200) @@ -1507,7 +1504,7 @@ class BomItemTest(InvenTreeAPITestCase): self.assertEqual(response.data['note'], 'Added a note') def test_add_bom_item(self): - """Test that we can create a new BomItem via the API""" + """Test that we can create a new BomItem via the API.""" url = reverse('api-bom-list') data = { @@ -1524,7 +1521,7 @@ class BomItemTest(InvenTreeAPITestCase): self.client.post(url, data, expected_code=400) def test_variants(self): - """Tests for BomItem use with variants""" + """Tests for BomItem use with variants.""" stock_url = reverse('api-stock-list') # BOM item we are interested in @@ -1606,7 +1603,7 @@ class BomItemTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 2) def test_substitutes(self): - """Tests for BomItem substitutes""" + """Tests for BomItem substitutes.""" url = reverse('api-bom-substitute-list') stock_url = reverse('api-stock-list') @@ -1688,7 +1685,7 @@ class BomItemTest(InvenTreeAPITestCase): self.assertEqual(data['available_stock'], 9000) def test_bom_item_uses(self): - """Tests for the 'uses' field""" + """Tests for the 'uses' field.""" url = reverse('api-bom-list') # Test that the direct 'sub_part' association works @@ -1738,7 +1735,7 @@ class BomItemTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), i) def test_bom_variant_stock(self): - """Test for 'available_variant_stock' annotation""" + """Test for 'available_variant_stock' annotation.""" Part.objects.rebuild() # BOM item we are interested in @@ -1774,7 +1771,7 @@ class BomItemTest(InvenTreeAPITestCase): class PartParameterTest(InvenTreeAPITestCase): - """Tests for the ParParameter API""" + """Tests for the ParParameter API.""" superuser = True fixtures = [ @@ -1789,7 +1786,7 @@ class PartParameterTest(InvenTreeAPITestCase): super().setUp() def test_list_params(self): - """Test for listing part parameters""" + """Test for listing part parameters.""" url = reverse('api-part-parameter-list') response = self.client.get(url, format='json') @@ -1819,7 +1816,7 @@ class PartParameterTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 3) def test_create_param(self): - """Test that we can create a param via the API""" + """Test that we can create a param via the API.""" url = reverse('api-part-parameter-list') response = self.client.post( @@ -1838,7 +1835,7 @@ class PartParameterTest(InvenTreeAPITestCase): self.assertEqual(len(response.data), 6) def test_param_detail(self): - """Tests for the PartParameter detail endpoint""" + """Tests for the PartParameter detail endpoint.""" url = reverse('api-part-parameter-detail', kwargs={'pk': 5}) response = self.client.get(url) diff --git a/InvenTree/part/test_bom_export.py b/InvenTree/part/test_bom_export.py index 20af439819..67b31a812d 100644 --- a/InvenTree/part/test_bom_export.py +++ b/InvenTree/part/test_bom_export.py @@ -1,4 +1,4 @@ -"""Unit testing for BOM export functionality""" +"""Unit testing for BOM export functionality.""" import csv @@ -24,7 +24,7 @@ class BomExportTest(InvenTreeTestCase): self.url = reverse('bom-download', kwargs={'pk': 100}) def test_bom_template(self): - """Test that the BOM template can be downloaded from the server""" + """Test that the BOM template can be downloaded from the server.""" url = reverse('bom-upload-template') # Download an XLS template @@ -73,7 +73,7 @@ class BomExportTest(InvenTreeTestCase): self.assertTrue(header in headers) def test_export_csv(self): - """Test BOM download in CSV format""" + """Test BOM download in CSV format.""" params = { 'format': 'csv', 'cascade': True, @@ -134,7 +134,7 @@ class BomExportTest(InvenTreeTestCase): self.assertTrue(header in expected) def test_export_xls(self): - """Test BOM download in XLS format""" + """Test BOM download in XLS format.""" params = { 'format': 'xls', 'cascade': True, @@ -152,7 +152,7 @@ class BomExportTest(InvenTreeTestCase): self.assertEqual(content, 'attachment; filename="BOB | Bob | A2_BOM.xls"') def test_export_xlsx(self): - """Test BOM download in XLSX format""" + """Test BOM download in XLSX format.""" params = { 'format': 'xlsx', 'cascade': True, @@ -167,7 +167,7 @@ class BomExportTest(InvenTreeTestCase): self.assertEqual(response.status_code, 200) def test_export_json(self): - """Test BOM download in JSON format""" + """Test BOM download in JSON format.""" params = { 'format': 'json', 'cascade': True, diff --git a/InvenTree/part/test_bom_import.py b/InvenTree/part/test_bom_import.py index 2729d6b1c7..bce7ac4d2f 100644 --- a/InvenTree/part/test_bom_import.py +++ b/InvenTree/part/test_bom_import.py @@ -1,4 +1,4 @@ -"""Unit testing for BOM upload / import functionality""" +"""Unit testing for BOM upload / import functionality.""" from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse @@ -10,7 +10,7 @@ from part.models import Part class BomUploadTest(InvenTreeAPITestCase): - """Test BOM file upload API endpoint""" + """Test BOM file upload API endpoint.""" roles = [ 'part.add', @@ -59,7 +59,7 @@ class BomUploadTest(InvenTreeAPITestCase): return response def test_missing_file(self): - """POST without a file""" + """POST without a file.""" response = self.post( reverse('api-bom-import-upload'), data={}, @@ -69,7 +69,7 @@ class BomUploadTest(InvenTreeAPITestCase): self.assertIn('No file was submitted', str(response.data['data_file'])) def test_unsupported_file(self): - """POST with an unsupported file type""" + """POST with an unsupported file type.""" response = self.post_bom( 'sample.txt', b'hello world', @@ -79,7 +79,7 @@ class BomUploadTest(InvenTreeAPITestCase): self.assertIn('Unsupported file type', str(response.data['data_file'])) def test_broken_file(self): - """Test upload with broken (corrupted) files""" + """Test upload with broken (corrupted) files.""" response = self.post_bom( 'sample.csv', b'', @@ -126,7 +126,7 @@ class BomUploadTest(InvenTreeAPITestCase): self.assertIn('No data rows found in file', str(response.data)) def test_missing_columns(self): - """Upload extracted data, but with missing columns""" + """Upload extracted data, but with missing columns.""" url = reverse('api-bom-import-extract') rows = [ @@ -176,7 +176,7 @@ class BomUploadTest(InvenTreeAPITestCase): ) def test_invalid_data(self): - """Upload data which contains errors""" + """Upload data which contains errors.""" dataset = tablib.Dataset() # Only these headers are strictly necessary @@ -219,7 +219,7 @@ class BomUploadTest(InvenTreeAPITestCase): self.assertEqual(rows[5]['data']['errors']['part'], 'Part is not designated as a component') def test_part_guess(self): - """Test part 'guessing' when PK values are not supplied""" + """Test part 'guessing' when PK values are not supplied.""" dataset = tablib.Dataset() # Should be able to 'guess' the part from the name @@ -279,7 +279,7 @@ class BomUploadTest(InvenTreeAPITestCase): self.assertEqual(rows[idx]['data']['part'], components[idx].pk) def test_levels(self): - """Test that multi-level BOMs are correctly handled during upload""" + """Test that multi-level BOMs are correctly handled during upload.""" url = reverse('api-bom-import-extract') dataset = tablib.Dataset() diff --git a/InvenTree/part/test_bom_item.py b/InvenTree/part/test_bom_item.py index c78cc29a3c..c17f7a845d 100644 --- a/InvenTree/part/test_bom_item.py +++ b/InvenTree/part/test_bom_item.py @@ -48,14 +48,14 @@ class BomItemTest(TestCase): self.assertEqual(self.orphan.used_in_count, 1) def test_self_reference(self): - """Test that we get an appropriate error when we create a BomItem which points to itself""" + """Test that we get an appropriate error when we create a BomItem which points to itself.""" with self.assertRaises(django_exceptions.ValidationError): # A validation error should be raised here item = BomItem.objects.create(part=self.bob, sub_part=self.bob, quantity=7) item.clean() # pragma: no cover def test_integer_quantity(self): - """Test integer validation for BomItem""" + """Test integer validation for BomItem.""" p = Part.objects.create(name="test", description="d", component=True, trackable=True) # Creation of a BOMItem with a non-integer quantity of a trackable Part should fail @@ -66,7 +66,7 @@ class BomItemTest(TestCase): BomItem.objects.create(part=self.bob, sub_part=p, quantity=21) def test_overage(self): - """Test that BOM line overages are calculated correctly""" + """Test that BOM line overages are calculated correctly.""" item = BomItem.objects.get(part=100, sub_part=50) q = 300 @@ -101,7 +101,7 @@ class BomItemTest(TestCase): self.assertEqual(n, 3150) def test_item_hash(self): - """Test BOM item hash encoding""" + """Test BOM item hash encoding.""" item = BomItem.objects.get(part=100, sub_part=50) h1 = item.get_item_hash() @@ -129,7 +129,7 @@ class BomItemTest(TestCase): ) def test_substitutes(self): - """Tests for BOM item substitutes""" + """Tests for BOM item substitutes.""" # We will make some subtitute parts for the "orphan" part bom_item = BomItem.objects.get( part=self.bob, diff --git a/InvenTree/part/test_category.py b/InvenTree/part/test_category.py index 891fb4d566..8270341ce9 100644 --- a/InvenTree/part/test_category.py +++ b/InvenTree/part/test_category.py @@ -28,7 +28,7 @@ class CategoryTest(TestCase): self.transceivers = PartCategory.objects.get(name='Transceivers') def test_parents(self): - """Test that the parent fields are properly set, based on the test fixtures""" + """Test that the parent fields are properly set, based on the test fixtures.""" self.assertEqual(self.resistors.parent, self.electronics) self.assertEqual(self.capacitors.parent, self.electronics) self.assertEqual(self.electronics.parent, None) @@ -36,7 +36,7 @@ class CategoryTest(TestCase): self.assertEqual(self.fasteners.parent, self.mechanical) def test_children_count(self): - """Test that categories have the correct number of children""" + """Test that categories have the correct number of children.""" self.assertTrue(self.electronics.has_children) self.assertTrue(self.mechanical.has_children) @@ -44,7 +44,7 @@ class CategoryTest(TestCase): self.assertEqual(len(self.mechanical.children.all()), 1) def test_unique_childs(self): - """Test the 'unique_children' functionality""" + """Test the 'unique_children' functionality.""" childs = [item.pk for item in self.electronics.getUniqueChildren()] self.assertIn(self.transceivers.id, childs) @@ -53,7 +53,7 @@ class CategoryTest(TestCase): self.assertNotIn(self.fasteners.id, childs) def test_unique_parents(self): - """Test the 'unique_parents' functionality""" + """Test the 'unique_parents' functionality.""" parents = [item.pk for item in self.transceivers.getUniqueParents()] self.assertIn(self.electronics.id, parents) @@ -61,16 +61,16 @@ class CategoryTest(TestCase): self.assertNotIn(self.fasteners.id, parents) def test_path_string(self): - """Test that the category path string works correctly""" + """Test that the category path string works correctly.""" self.assertEqual(str(self.resistors), 'Electronics/Resistors - Resistors') self.assertEqual(str(self.transceivers.pathstring), 'Electronics/IC/Transceivers') def test_url(self): - """Test that the PartCategory URL works""" + """Test that the PartCategory URL works.""" self.assertEqual(self.capacitors.get_absolute_url(), '/part/category/3/') def test_part_count(self): - """Test that the Category part count works""" + """Test that the Category part count works.""" self.assertTrue(self.resistors.has_parts) self.assertTrue(self.fasteners.has_parts) self.assertFalse(self.transceivers.has_parts) @@ -87,7 +87,7 @@ class CategoryTest(TestCase): self.assertEqual(self.electronics.item_count, self.electronics.partcount()) def test_parameters(self): - """Test that the Category parameters are correctly fetched""" + """Test that the Category parameters are correctly fetched.""" # Check number of SQL queries to iterate other parameters with self.assertNumQueries(7): # Prefetch: 3 queries (parts, parameters and parameters_template) @@ -125,7 +125,7 @@ class CategoryTest(TestCase): cat.save() def test_delete(self): - """Test that category deletion moves the children properly""" + """Test that category deletion moves the children properly.""" # Delete the 'IC' category and 'Transceiver' should move to be under 'Electronics' self.assertEqual(self.transceivers.parent, self.ic) self.assertEqual(self.ic.parent, self.electronics) @@ -145,7 +145,7 @@ class CategoryTest(TestCase): self.assertEqual(f.category, self.mechanical) def test_default_locations(self): - """Test traversal for default locations""" + """Test traversal for default locations.""" self.assertEqual(str(self.fasteners.default_location), 'Office/Drawer_1 - In my desk') # Any part under electronics should default to 'Home' diff --git a/InvenTree/part/test_migrations.py b/InvenTree/part/test_migrations.py index e4f8cd90dc..56b6f664ef 100644 --- a/InvenTree/part/test_migrations.py +++ b/InvenTree/part/test_migrations.py @@ -1,4 +1,4 @@ -"""Unit tests for the part model database migrations""" +"""Unit tests for the part model database migrations.""" from django_test_migrations.contrib.unittest_case import MigratorTestCase @@ -6,13 +6,13 @@ from InvenTree import helpers class TestForwardMigrations(MigratorTestCase): - """Test entire schema migration sequence for the part app""" + """Test entire schema migration sequence for the part app.""" migrate_from = ('part', helpers.getOldestMigrationFile('part')) migrate_to = ('part', helpers.getNewestMigrationFile('part')) def prepare(self): - """Create initial data""" + """Create initial data.""" Part = self.old_state.apps.get_model('part', 'part') Part.objects.create(name='A', description='My part A') diff --git a/InvenTree/part/test_part.py b/InvenTree/part/test_part.py index b74a249f00..0069a5e4e2 100644 --- a/InvenTree/part/test_part.py +++ b/InvenTree/part/test_part.py @@ -1,4 +1,4 @@ -"""Tests for the Part model""" +"""Tests for the Part model.""" import os @@ -21,7 +21,7 @@ from .templatetags import inventree_extras class TemplateTagTest(InvenTreeTestCase): - """Tests for the custom template tag code""" + """Tests for the custom template tag code.""" def test_define(self): self.assertEqual(int(inventree_extras.define(3)), 3) @@ -112,7 +112,7 @@ class TemplateTagTest(InvenTreeTestCase): class PartTest(TestCase): - """Tests for the Part model""" + """Tests for the Part model.""" fixtures = [ 'category', @@ -146,7 +146,7 @@ class PartTest(TestCase): self.assertEqual(str(p), "BOB | Bob | A2 - Can we build it?") def test_duplicate(self): - """Test that we cannot create a "duplicate" Part""" + """Test that we cannot create a "duplicate" Part.""" n = Part.objects.count() cat = PartCategory.objects.get(pk=1) @@ -244,7 +244,7 @@ class PartTest(TestCase): self.assertEqual(float(self.r1.get_internal_price(10)), 0.5) def test_metadata(self): - """Unit tests for the Part metadata field""" + """Unit tests for the Part metadata field.""" p = Part.objects.get(pk=1) self.assertIsNone(p.metadata) @@ -326,7 +326,7 @@ class PartSettingsTest(InvenTreeTestCase): """ def make_part(self): - """Helper function to create a simple part""" + """Helper function to create a simple part.""" part = Part.objects.create( name='Test Part', description='I am but a humble test part', @@ -336,7 +336,7 @@ class PartSettingsTest(InvenTreeTestCase): return part def test_defaults(self): - """Test that the default values for the part settings are correct""" + """Test that the default values for the part settings are correct.""" self.assertTrue(part.settings.part_component_default()) self.assertTrue(part.settings.part_purchaseable_default()) self.assertFalse(part.settings.part_salable_default()) @@ -352,7 +352,7 @@ class PartSettingsTest(InvenTreeTestCase): self.assertFalse(part.trackable) def test_custom(self): - """Update some of the part values and re-test""" + """Update some of the part values and re-test.""" for val in [True, False]: InvenTreeSetting.set_setting('PART_COMPONENT', val, self.user) InvenTreeSetting.set_setting('PART_PURCHASEABLE', val, self.user) @@ -378,7 +378,7 @@ class PartSettingsTest(InvenTreeTestCase): Part.objects.filter(pk=part.pk).delete() def test_duplicate_ipn(self): - """Test the setting which controls duplicate IPN values""" + """Test the setting which controls duplicate IPN values.""" # Create a part Part.objects.create(name='Hello', description='A thing', IPN='IPN123', revision='A') @@ -445,7 +445,7 @@ class PartSubscriptionTests(InvenTreeTestCase): ) def test_part_subcription(self): - """Test basic subscription against a part""" + """Test basic subscription against a part.""" # First check that the user is *not* subscribed to the part self.assertFalse(self.part.is_starred_by(self.user)) @@ -462,7 +462,7 @@ class PartSubscriptionTests(InvenTreeTestCase): self.assertFalse(self.part.is_starred_by(self.user)) def test_variant_subscription(self): - """Test subscription against a parent part""" + """Test subscription against a parent part.""" # Construct a sub-part to star against sub_part = Part.objects.create( name='sub_part', @@ -479,7 +479,7 @@ class PartSubscriptionTests(InvenTreeTestCase): self.assertTrue(sub_part.is_starred_by(self.user)) def test_category_subscription(self): - """Test subscription against a PartCategory""" + """Test subscription against a PartCategory.""" self.assertEqual(PartCategoryStar.objects.count(), 0) self.assertFalse(self.part.is_starred_by(self.user)) @@ -504,7 +504,7 @@ class PartSubscriptionTests(InvenTreeTestCase): self.assertFalse(self.part.is_starred_by(self.user)) def test_parent_category_subscription(self): - """Check that a parent category can be subscribed to""" + """Check that a parent category can be subscribed to.""" # Top-level "electronics" category cat = PartCategory.objects.get(pk=1) @@ -521,7 +521,7 @@ class PartSubscriptionTests(InvenTreeTestCase): class BaseNotificationIntegrationTest(InvenTreeTestCase): - """Integration test for notifications""" + """Integration test for notifications.""" fixtures = [ 'location', @@ -565,7 +565,7 @@ class BaseNotificationIntegrationTest(InvenTreeTestCase): class PartNotificationTest(BaseNotificationIntegrationTest): - """Integration test for part notifications""" + """Integration test for part notifications.""" def test_notification(self): self._notification_run(UIMessageNotification) diff --git a/InvenTree/part/test_views.py b/InvenTree/part/test_views.py index b7885f6b5f..3964fb91f5 100644 --- a/InvenTree/part/test_views.py +++ b/InvenTree/part/test_views.py @@ -40,7 +40,7 @@ class PartListTest(PartViewTestCase): class PartDetailTest(PartViewTestCase): def test_part_detail(self): - """Test that we can retrieve a part detail page""" + """Test that we can retrieve a part detail page.""" pk = 1 response = self.client.get(reverse('part-detail', args=(pk,))) @@ -107,14 +107,14 @@ class PartDetailTest(PartViewTestCase): test_ipn_match(index_result=True, detail_result=False) def test_bom_download(self): - """Test downloading a BOM for a valid part""" + """Test downloading a BOM for a valid part.""" response = self.client.get(reverse('bom-download', args=(1,)), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertIn('streaming_content', dir(response)) class PartQRTest(PartViewTestCase): - """Tests for the Part QR Code AJAX view""" + """Tests for the Part QR Code AJAX view.""" def test_html_redirect(self): # A HTML request for a QR code should be redirected (use an AJAX request instead) @@ -137,10 +137,10 @@ class PartQRTest(PartViewTestCase): class CategoryTest(PartViewTestCase): - """Tests for PartCategory related views""" + """Tests for PartCategory related views.""" def test_set_category(self): - """Test that the "SetCategory" view works""" + """Test that the "SetCategory" view works.""" url = reverse('part-set-category') response = self.client.get(url, {'parts[]': 1}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') diff --git a/InvenTree/part/views.py b/InvenTree/part/views.py index 972fb484df..d73cd6c8b0 100644 --- a/InvenTree/part/views.py +++ b/InvenTree/part/views.py @@ -1,4 +1,4 @@ -"""Django views for interacting with Part app""" +"""Django views for interacting with Part app.""" import io import os @@ -41,7 +41,7 @@ from .models import (Part, PartCategory, PartCategoryParameterTemplate, class PartIndex(InvenTreeRoleMixin, ListView): - """View for displaying list of Part objects""" + """View for displaying list of Part objects.""" model = Part template_name = 'part/category.html' @@ -65,7 +65,7 @@ class PartIndex(InvenTreeRoleMixin, ListView): class PartSetCategory(AjaxUpdateView): - """View for settings the part category for multiple parts at once""" + """View for settings the part category for multiple parts at once.""" ajax_template_name = 'part/set_category.html' ajax_form_title = _('Set Part Category') @@ -77,7 +77,7 @@ class PartSetCategory(AjaxUpdateView): parts = [] def get(self, request, *args, **kwargs): - """Respond to a GET request to this view""" + """Respond to a GET request to this view.""" self.request = request if 'parts[]' in request.GET: @@ -88,7 +88,7 @@ class PartSetCategory(AjaxUpdateView): return self.renderJsonResponse(request, form=self.get_form(), context=self.get_context_data()) def post(self, request, *args, **kwargs): - """Respond to a POST request to this view""" + """Respond to a POST request to this view.""" self.parts = [] for item in request.POST: @@ -130,7 +130,7 @@ class PartSetCategory(AjaxUpdateView): part.set_category(self.category) def get_context_data(self): - """Return context data for rendering in the form""" + """Return context data for rendering in the form.""" ctx = {} ctx['parts'] = self.parts @@ -221,7 +221,7 @@ class PartImport(FileManagementFormView): file_manager_class = PartFileManager def get_field_selection(self): - """Fill the form fields for step 3""" + """Fill the form fields for step 3.""" # fetch available elements self.allowed_items = {} self.matches = {} @@ -264,7 +264,7 @@ class PartImport(FileManagementFormView): row[idx.lower()] = data def done(self, form_list, **kwargs): - """Create items""" + """Create items.""" items = self.get_clean_items() import_done = 0 @@ -349,7 +349,7 @@ class PartImportAjax(FileManagementAjaxView, PartImport): class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detail view for Part object""" + """Detail view for Part object.""" context_object_name = 'part' queryset = Part.objects.all().select_related('category') @@ -358,7 +358,7 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): # Add in some extra context information based on query params def get_context_data(self, **kwargs): - """Provide extra context data to template""" + """Provide extra context data to template.""" context = super().get_context_data(**kwargs) part = self.get_object() @@ -381,14 +381,14 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): return context def get_quantity(self): - """Return set quantity in decimal format""" + """Return set quantity in decimal format.""" return Decimal(self.request.POST.get('quantity', 1)) def get_part(self): return self.get_object() def get_pricing(self, quantity=1, currency=None): - """Returns context with pricing information""" + """Returns context with pricing information.""" ctx = PartPricing.get_pricing(self, quantity, currency) part = self.get_part() default_currency = inventree_settings.currency_code_default() @@ -495,7 +495,7 @@ class PartDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): return ctx def get_initials(self): - """Returns initials for form""" + """Returns initials for form.""" return {'quantity': self.get_quantity()} def post(self, request, *args, **kwargs): @@ -510,7 +510,7 @@ class PartDetailFromIPN(PartDetail): slug_url_kwarg = 'slug' def get_object(self): - """Return Part object which IPN field matches the slug value""" + """Return Part object which IPN field matches the slug value.""" queryset = self.get_queryset() # Get slug slug = self.kwargs.get(self.slug_url_kwarg) @@ -533,7 +533,7 @@ class PartDetailFromIPN(PartDetail): return None def get(self, request, *args, **kwargs): - """Attempt to match slug to a Part, else redirect to PartIndex view""" + """Attempt to match slug to a Part, else redirect to PartIndex view.""" self.object = self.get_object() if not self.object: @@ -543,14 +543,14 @@ class PartDetailFromIPN(PartDetail): class PartQRCode(QRCodeView): - """View for displaying a QR code for a Part object""" + """View for displaying a QR code for a Part object.""" ajax_form_title = _("Part QR Code") role_required = 'part.view' def get_qr_data(self): - """Generate QR code data for the Part""" + """Generate QR code data for the Part.""" try: part = Part.objects.get(id=self.pk) return part.format_barcode() @@ -559,7 +559,7 @@ class PartQRCode(QRCodeView): class PartImageDownloadFromURL(AjaxUpdateView): - """View for downloading an image from a provided URL""" + """View for downloading an image from a provided URL.""" model = Part @@ -615,7 +615,7 @@ class PartImageDownloadFromURL(AjaxUpdateView): return def save(self, part, form, **kwargs): - """Save the downloaded image to the part""" + """Save the downloaded image to the part.""" fmt = self.image.format if not fmt: @@ -752,7 +752,7 @@ class BomDownload(AjaxView): class PartDelete(AjaxDeleteView): - """View to delete a Part object""" + """View to delete a Part object.""" model = Part ajax_template_name = 'part/partial_delete.html' @@ -768,7 +768,7 @@ class PartDelete(AjaxDeleteView): class PartPricing(AjaxView): - """View for inspecting part pricing information""" + """View for inspecting part pricing information.""" model = Part ajax_template_name = "part/part_pricing.html" @@ -778,7 +778,7 @@ class PartPricing(AjaxView): role_required = ['sales_order.view', 'part.view'] def get_quantity(self): - """Return set quantity in decimal format""" + """Return set quantity in decimal format.""" return Decimal(self.request.POST.get('quantity', 1)) def get_part(self): @@ -788,7 +788,7 @@ class PartPricing(AjaxView): return None def get_pricing(self, quantity=1, currency=None): - """Returns context with pricing information""" + """Returns context with pricing information.""" if quantity <= 0: quantity = 1 @@ -882,7 +882,7 @@ class PartPricing(AjaxView): return ctx def get_initials(self): - """Returns initials for form""" + """Returns initials for form.""" return {'quantity': self.get_quantity()} def get(self, request, *args, **kwargs): @@ -915,7 +915,7 @@ class PartPricing(AjaxView): class PartParameterTemplateCreate(AjaxCreateView): - """View for creating a new PartParameterTemplate""" + """View for creating a new PartParameterTemplate.""" model = PartParameterTemplate form_class = part_forms.EditPartParameterTemplateForm @@ -923,7 +923,7 @@ class PartParameterTemplateCreate(AjaxCreateView): class PartParameterTemplateEdit(AjaxUpdateView): - """View for editing a PartParameterTemplate""" + """View for editing a PartParameterTemplate.""" model = PartParameterTemplate form_class = part_forms.EditPartParameterTemplateForm @@ -931,14 +931,14 @@ class PartParameterTemplateEdit(AjaxUpdateView): class PartParameterTemplateDelete(AjaxDeleteView): - """View for deleting an existing PartParameterTemplate""" + """View for deleting an existing PartParameterTemplate.""" model = PartParameterTemplate ajax_form_title = _("Delete Part Parameter Template") class CategoryDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detail view for PartCategory""" + """Detail view for PartCategory.""" model = PartCategory context_object_name = 'category' @@ -970,7 +970,7 @@ class CategoryDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): class CategoryDelete(AjaxDeleteView): - """Delete view to delete a PartCategory""" + """Delete view to delete a PartCategory.""" model = PartCategory ajax_template_name = 'part/category_delete.html' @@ -985,14 +985,14 @@ class CategoryDelete(AjaxDeleteView): class CategoryParameterTemplateCreate(AjaxCreateView): - """View for creating a new PartCategoryParameterTemplate""" + """View for creating a new PartCategoryParameterTemplate.""" model = PartCategoryParameterTemplate form_class = part_forms.EditCategoryParameterTemplateForm ajax_form_title = _('Create Category Parameter Template') def get_initial(self): - """Get initial data for Category""" + """Get initial data for Category.""" initials = super().get_initial() category_id = self.kwargs.get('pk', None) @@ -1006,7 +1006,7 @@ class CategoryParameterTemplateCreate(AjaxCreateView): return initials def get_form(self): - """Create a form to upload a new CategoryParameterTemplate + """Create a form to upload a new CategoryParameterTemplate. - Hide the 'category' field (parent part) - Display parameter templates which are not yet related @@ -1040,7 +1040,7 @@ class CategoryParameterTemplateCreate(AjaxCreateView): return form def post(self, request, *args, **kwargs): - """Capture the POST request + """Capture the POST request. - If the add_to_all_categories object is set, link parameter template to all categories @@ -1085,7 +1085,7 @@ class CategoryParameterTemplateCreate(AjaxCreateView): class CategoryParameterTemplateEdit(AjaxUpdateView): - """View for editing a PartCategoryParameterTemplate""" + """View for editing a PartCategoryParameterTemplate.""" model = PartCategoryParameterTemplate form_class = part_forms.EditCategoryParameterTemplateForm @@ -1100,7 +1100,7 @@ class CategoryParameterTemplateEdit(AjaxUpdateView): return self.object def get_form(self): - """Create a form to upload a new CategoryParameterTemplate + """Create a form to upload a new CategoryParameterTemplate. - Hide the 'category' field (parent part) - Display parameter templates which are not yet related @@ -1142,7 +1142,7 @@ class CategoryParameterTemplateEdit(AjaxUpdateView): class CategoryParameterTemplateDelete(AjaxDeleteView): - """View for deleting an existing PartCategoryParameterTemplate""" + """View for deleting an existing PartCategoryParameterTemplate.""" model = PartCategoryParameterTemplate ajax_form_title = _("Delete Category Parameter Template") diff --git a/InvenTree/plugin/__init__.py b/InvenTree/plugin/__init__.py index 7f181863a8..982d634356 100644 --- a/InvenTree/plugin/__init__.py +++ b/InvenTree/plugin/__init__.py @@ -1,4 +1,4 @@ -"""Utility file to enable simper imports""" +"""Utility file to enable simper imports.""" from .helpers import MixinImplementationError, MixinNotImplementedError from .plugin import IntegrationPluginBase, InvenTreePlugin diff --git a/InvenTree/plugin/admin.py b/InvenTree/plugin/admin.py index a9886e763d..dd3a1b5644 100644 --- a/InvenTree/plugin/admin.py +++ b/InvenTree/plugin/admin.py @@ -6,7 +6,7 @@ import plugin.registry as pl_registry def plugin_update(queryset, new_status: bool): - """General function for bulk changing plugins""" + """General function for bulk changing plugins.""" apps_changed = False # Run through all plugins in the queryset as the save method needs to be overridden @@ -23,18 +23,18 @@ def plugin_update(queryset, new_status: bool): @admin.action(description='Activate plugin(s)') def plugin_activate(modeladmin, request, queryset): - """Activate a set of plugins""" + """Activate a set of plugins.""" plugin_update(queryset, True) @admin.action(description='Deactivate plugin(s)') def plugin_deactivate(modeladmin, request, queryset): - """Deactivate a set of plugins""" + """Deactivate a set of plugins.""" plugin_update(queryset, False) class PluginSettingInline(admin.TabularInline): - """Inline admin class for PluginSetting""" + """Inline admin class for PluginSetting.""" model = models.PluginSetting @@ -47,7 +47,7 @@ class PluginSettingInline(admin.TabularInline): class PluginConfigAdmin(admin.ModelAdmin): - """Custom admin with restricted id fields""" + """Custom admin with restricted id fields.""" readonly_fields = ["key", "name", ] list_display = ['name', 'key', '__str__', 'active', ] @@ -57,7 +57,7 @@ class PluginConfigAdmin(admin.ModelAdmin): class NotificationUserSettingAdmin(admin.ModelAdmin): - """Admin class for NotificationUserSetting""" + """Admin class for NotificationUserSetting.""" model = models.NotificationUserSetting diff --git a/InvenTree/plugin/api.py b/InvenTree/plugin/api.py index c9a8f39190..2f4bd2caa7 100644 --- a/InvenTree/plugin/api.py +++ b/InvenTree/plugin/api.py @@ -1,4 +1,4 @@ -"""JSON API for the plugin app""" +"""JSON API for the plugin app.""" from django.conf import settings from django.urls import include, re_path @@ -18,7 +18,7 @@ from plugin.registry import registry class PluginList(generics.ListAPIView): - """API endpoint for list of PluginConfig objects + """API endpoint for list of PluginConfig objects. - GET: Return a list of all PluginConfig objects """ @@ -77,7 +77,7 @@ class PluginList(generics.ListAPIView): class PluginDetail(generics.RetrieveUpdateDestroyAPIView): - """API detail endpoint for PluginConfig object + """API detail endpoint for PluginConfig object. get: Return a single PluginConfig object @@ -94,7 +94,7 @@ class PluginDetail(generics.RetrieveUpdateDestroyAPIView): class PluginInstall(generics.CreateAPIView): - """Endpoint for installing a new plugin""" + """Endpoint for installing a new plugin.""" queryset = PluginConfig.objects.none() serializer_class = PluginSerializers.PluginConfigInstallSerializer diff --git a/InvenTree/plugin/base/action/api.py b/InvenTree/plugin/base/action/api.py index 1f076be6da..4d77121e2d 100644 --- a/InvenTree/plugin/base/action/api.py +++ b/InvenTree/plugin/base/action/api.py @@ -1,4 +1,4 @@ -"""APIs for action plugins""" +"""APIs for action plugins.""" from django.utils.translation import gettext_lazy as _ diff --git a/InvenTree/plugin/base/action/mixins.py b/InvenTree/plugin/base/action/mixins.py index 2d76dd1035..540859f2b4 100644 --- a/InvenTree/plugin/base/action/mixins.py +++ b/InvenTree/plugin/base/action/mixins.py @@ -1,13 +1,13 @@ -"""Plugin mixin classes for action plugin""" +"""Plugin mixin classes for action plugin.""" class ActionMixin: - """Mixin that enables custom actions""" + """Mixin that enables custom actions.""" ACTION_NAME = "" class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Actions' @@ -34,7 +34,10 @@ class ActionMixin: return False def get_info(self, user=None, data=None): - """Extra info? Can be a string / dict / etc""" + """Extra info? + + Can be a string / dict / etc + """ return None def get_response(self, user=None, data=None): diff --git a/InvenTree/plugin/base/action/test_action.py b/InvenTree/plugin/base/action/test_action.py index 13815eaa90..c73ebc64b7 100644 --- a/InvenTree/plugin/base/action/test_action.py +++ b/InvenTree/plugin/base/action/test_action.py @@ -1,4 +1,4 @@ -"""Unit tests for action plugins""" +"""Unit tests for action plugins.""" from django.test import TestCase @@ -8,7 +8,7 @@ from plugin.mixins import ActionMixin class ActionMixinTests(TestCase): - """Tests for ActionMixin""" + """Tests for ActionMixin.""" ACTION_RETURN = 'a action was performed' @@ -18,7 +18,7 @@ class ActionMixinTests(TestCase): self.plugin = SimplePlugin() class TestActionPlugin(ActionMixin, InvenTreePlugin): - """An action plugin""" + """An action plugin.""" ACTION_NAME = 'abc123' def perform_action(self, user=None, data=None): @@ -38,13 +38,13 @@ class ActionMixinTests(TestCase): self.action_name = NameActionPlugin() def test_action_name(self): - """Check the name definition possibilities""" + """Check the name definition possibilities.""" self.assertEqual(self.plugin.action_name(), '') self.assertEqual(self.action_plugin.action_name(), 'abc123') self.assertEqual(self.action_name.action_name(), 'Aplugin') def test_function(self): - """Check functions""" + """Check functions.""" # the class itself self.assertIsNone(self.plugin.perform_action()) self.assertEqual(self.plugin.get_result(), False) @@ -67,10 +67,10 @@ class ActionMixinTests(TestCase): class APITests(InvenTreeTestCase): - """Tests for action api""" + """Tests for action api.""" def test_post_errors(self): - """Check the possible errors with post""" + """Check the possible errors with post.""" # Test empty request response = self.client.post('/api/action/') self.assertEqual(response.status_code, 200) diff --git a/InvenTree/plugin/base/barcodes/api.py b/InvenTree/plugin/base/barcodes/api.py index dfccce2dfd..8b2d49edb1 100644 --- a/InvenTree/plugin/base/barcodes/api.py +++ b/InvenTree/plugin/base/barcodes/api.py @@ -33,7 +33,6 @@ class BarcodeScan(APIView): hashing: Barcode hashes are calculated using MD5 - """ permission_classes = [ @@ -41,7 +40,7 @@ class BarcodeScan(APIView): ] def post(self, request, *args, **kwargs): - """Respond to a barcode POST request""" + """Respond to a barcode POST request.""" data = request.data if 'barcode' not in data: diff --git a/InvenTree/plugin/base/barcodes/mixins.py b/InvenTree/plugin/base/barcodes/mixins.py index d11f0ace59..371157b2eb 100644 --- a/InvenTree/plugin/base/barcodes/mixins.py +++ b/InvenTree/plugin/base/barcodes/mixins.py @@ -1,4 +1,4 @@ -"""Plugin mixin classes for barcode plugin""" +"""Plugin mixin classes for barcode plugin.""" import hashlib import string @@ -27,7 +27,7 @@ def hash_barcode(barcode_data): class BarcodeMixin: - """Mixin that enables barcode handeling + """Mixin that enables barcode handeling. Custom barcode plugins should use and extend this mixin as necessary. """ @@ -35,7 +35,7 @@ class BarcodeMixin: ACTION_NAME = "" class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Barcode' @@ -45,11 +45,11 @@ class BarcodeMixin: @property def has_barcode(self): - """Does this plugin have everything needed to process a barcode""" + """Does this plugin have everything needed to process a barcode.""" return True def init(self, barcode_data): - """Initialize the BarcodePlugin instance + """Initialize the BarcodePlugin instance. Args: barcode_data - The raw barcode data @@ -72,7 +72,7 @@ class BarcodeMixin: return None def renderStockItem(self, item): - """Render a stock item to JSON response""" + """Render a stock item to JSON response.""" serializer = StockItemSerializer(item, part_detail=True, location_detail=True, supplier_part_detail=True) return serializer.data @@ -84,7 +84,7 @@ class BarcodeMixin: return None # pragma: no cover def renderStockLocation(self, loc): - """Render a stock location to a JSON response""" + """Render a stock location to a JSON response.""" serializer = LocationSerializer(loc) return serializer.data @@ -96,7 +96,7 @@ class BarcodeMixin: return None # pragma: no cover def renderPart(self, part): - """Render a part to JSON response""" + """Render a part to JSON response.""" serializer = PartSerializer(part) return serializer.data @@ -115,5 +115,5 @@ class BarcodeMixin: return hash_barcode(self.data) def validate(self): - """Default implementation returns False""" + """Default implementation returns False.""" return False # pragma: no cover diff --git a/InvenTree/plugin/base/barcodes/test_barcode.py b/InvenTree/plugin/base/barcodes/test_barcode.py index 178223816e..3c4f1f7ae1 100644 --- a/InvenTree/plugin/base/barcodes/test_barcode.py +++ b/InvenTree/plugin/base/barcodes/test_barcode.py @@ -1,4 +1,4 @@ -"""Unit tests for Barcode endpoints""" +"""Unit tests for Barcode endpoints.""" from django.urls import reverse @@ -58,7 +58,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertIsNone(data['plugin']) def test_find_part(self): - """Test that we can lookup a part based on ID""" + """Test that we can lookup a part based on ID.""" response = self.client.post( self.scan_url, { @@ -75,7 +75,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['part']['pk'], 1) def test_invalid_part(self): - """Test response for invalid part""" + """Test response for invalid part.""" response = self.client.post( self.scan_url, { @@ -91,7 +91,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['part'], 'Part does not exist') def test_find_stock_item(self): - """Test that we can lookup a stock item based on ID""" + """Test that we can lookup a stock item based on ID.""" response = self.client.post( self.scan_url, { @@ -108,7 +108,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['stockitem']['pk'], 1) def test_invalid_item(self): - """Test response for invalid stock item""" + """Test response for invalid stock item.""" response = self.client.post( self.scan_url, { @@ -124,7 +124,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['stockitem'], 'Stock item does not exist') def test_find_location(self): - """Test that we can lookup a stock location based on ID""" + """Test that we can lookup a stock location based on ID.""" response = self.client.post( self.scan_url, { @@ -141,7 +141,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(response.data['stocklocation']['pk'], 1) def test_invalid_location(self): - """Test response for an invalid location""" + """Test response for an invalid location.""" response = self.client.post( self.scan_url, { @@ -200,7 +200,7 @@ class BarcodeAPITest(InvenTreeAPITestCase): self.assertEqual(pk, item.pk) def test_association(self): - """Test that a barcode can be associated with a StockItem""" + """Test that a barcode can be associated with a StockItem.""" item = StockItem.objects.get(pk=522) self.assertEqual(len(item.uid), 0) diff --git a/InvenTree/plugin/base/event/events.py b/InvenTree/plugin/base/event/events.py index d510755465..380fc5587a 100644 --- a/InvenTree/plugin/base/event/events.py +++ b/InvenTree/plugin/base/event/events.py @@ -1,4 +1,4 @@ -"""Functions for triggering and responding to server side events""" +"""Functions for triggering and responding to server side events.""" import logging @@ -134,7 +134,7 @@ def allow_table_event(table_name): @receiver(post_save) def after_save(sender, instance, created, **kwargs): - """Trigger an event whenever a database entry is saved""" + """Trigger an event whenever a database entry is saved.""" table = sender.objects.model._meta.db_table instance_id = getattr(instance, 'id', None) @@ -161,7 +161,7 @@ def after_save(sender, instance, created, **kwargs): @receiver(post_delete) def after_delete(sender, instance, **kwargs): - """Trigger an event whenever a database entry is deleted""" + """Trigger an event whenever a database entry is deleted.""" table = sender.objects.model._meta.db_table if not allow_table_event(table): diff --git a/InvenTree/plugin/base/event/mixins.py b/InvenTree/plugin/base/event/mixins.py index d18c800bfe..945f73a5a1 100644 --- a/InvenTree/plugin/base/event/mixins.py +++ b/InvenTree/plugin/base/event/mixins.py @@ -1,4 +1,4 @@ -"""Plugin mixin class for events""" +"""Plugin mixin class for events.""" from plugin.helpers import MixinNotImplementedError @@ -10,7 +10,7 @@ class EventMixin: """ def process_event(self, event, *args, **kwargs): - """Function to handle events + """Function to handle events. Must be overridden by plugin """ @@ -18,7 +18,7 @@ class EventMixin: raise MixinNotImplementedError class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Events' diff --git a/InvenTree/plugin/base/integration/mixins.py b/InvenTree/plugin/base/integration/mixins.py index 88a450da69..57d7b27df5 100644 --- a/InvenTree/plugin/base/integration/mixins.py +++ b/InvenTree/plugin/base/integration/mixins.py @@ -1,4 +1,4 @@ -"""Plugin mixin classes""" +"""Plugin mixin classes.""" import json import logging @@ -19,7 +19,7 @@ logger = logging.getLogger('inventree') class SettingsMixin: - """Mixin that enables global settings for the plugin""" + """Mixin that enables global settings for the plugin.""" class MixinMeta: MIXIN_NAME = 'Settings' @@ -31,15 +31,15 @@ class SettingsMixin: @property def has_settings(self): - """Does this plugin use custom global settings""" + """Does this plugin use custom global settings.""" return bool(self.settings) def get_setting(self, key): - """Return the 'value' of the setting associated with this plugin""" + """Return the 'value' of the setting associated with this plugin.""" return PluginSetting.get_setting(key, plugin=self) def set_setting(self, key, value, user=None): - """Set plugin setting value by key""" + """Set plugin setting value by key.""" try: plugin, _ = PluginConfig.objects.get_or_create(key=self.plugin_slug(), name=self.plugin_name()) except (OperationalError, ProgrammingError): # pragma: no cover @@ -86,7 +86,7 @@ class ScheduleMixin: SCHEDULED_TASKS = {} class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Schedule' @@ -102,11 +102,11 @@ class ScheduleMixin: @property def has_scheduled_tasks(self): - """Are tasks defined for this plugin""" + """Are tasks defined for this plugin.""" return bool(self.scheduled_tasks) def validate_scheduled_tasks(self): - """Check that the provided scheduled tasks are valid""" + """Check that the provided scheduled tasks are valid.""" if not self.has_scheduled_tasks: raise MixinImplementationError("SCHEDULED_TASKS not defined") @@ -128,18 +128,18 @@ class ScheduleMixin: raise MixinImplementationError(f"Task '{key}' is missing 'minutes' parameter") def get_task_name(self, key): - """Task name for key""" + """Task name for key.""" # Generate a 'unique' task name slug = self.plugin_slug() return f"plugin.{slug}.{key}" def get_task_names(self): - """All defined task names""" + """All defined task names.""" # Returns a list of all task names associated with this plugin instance return [self.get_task_name(key) for key in self.scheduled_tasks.keys()] def register_tasks(self): - """Register the tasks with the database""" + """Register the tasks with the database.""" try: from django_q.models import Schedule @@ -167,7 +167,8 @@ class ScheduleMixin: ) else: - """Non-dotted notation indicates that we wish to call a 'member function' of the calling plugin. + """ + Non-dotted notation indicates that we wish to call a 'member function' of the calling plugin. This is managed by the plugin registry itself. """ @@ -188,7 +189,7 @@ class ScheduleMixin: logger.warning("register_tasks failed, database not ready") def unregister_tasks(self): - """Deregister the tasks with the database""" + """Deregister the tasks with the database.""" try: from django_q.models import Schedule @@ -207,10 +208,10 @@ class ScheduleMixin: class UrlsMixin: - """Mixin that enables custom URLs for the plugin""" + """Mixin that enables custom URLs for the plugin.""" class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'URLs' @@ -220,40 +221,40 @@ class UrlsMixin: self.urls = self.setup_urls() def setup_urls(self): - """Setup url endpoints for this plugin""" + """Setup url endpoints for this plugin.""" return getattr(self, 'URLS', None) @property def base_url(self): - """Base url for this plugin""" + """Base url for this plugin.""" return f'{PLUGIN_BASE}/{self.slug}/' @property def internal_name(self): - """Internal url pattern name""" + """Internal url pattern name.""" return f'plugin:{self.slug}:' @property def urlpatterns(self): - """Urlpatterns for this plugin""" + """Urlpatterns for this plugin.""" if self.has_urls: return re_path(f'^{self.slug}/', include((self.urls, self.slug)), name=self.slug) return None @property def has_urls(self): - """Does this plugin use custom urls""" + """Does this plugin use custom urls.""" return bool(self.urls) class NavigationMixin: - """Mixin that enables custom navigation links with the plugin""" + """Mixin that enables custom navigation links with the plugin.""" NAVIGATION_TAB_NAME = None NAVIGATION_TAB_ICON = "fas fa-question" class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Navigation Links' @@ -263,7 +264,7 @@ class NavigationMixin: self.navigation = self.setup_navigation() def setup_navigation(self): - """Setup navigation links for this plugin""" + """Setup navigation links for this plugin.""" nav_links = getattr(self, 'NAVIGATION', None) if nav_links: # check if needed values are configured @@ -274,12 +275,12 @@ class NavigationMixin: @property def has_naviation(self): - """Does this plugin define navigation elements""" + """Does this plugin define navigation elements.""" return bool(self.navigation) @property def navigation_name(self): - """Name for navigation tab""" + """Name for navigation tab.""" name = getattr(self, 'NAVIGATION_TAB_NAME', None) if not name: name = self.human_name @@ -287,15 +288,15 @@ class NavigationMixin: @property def navigation_icon(self): - """Icon-name for navigation tab""" + """Icon-name for navigation tab.""" return getattr(self, 'NAVIGATION_TAB_ICON', "fas fa-question") class AppMixin: - """Mixin that enables full django app functions for a plugin""" + """Mixin that enables full django app functions for a plugin.""" class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'App registration' @@ -305,12 +306,12 @@ class AppMixin: @property def has_app(self): - """This plugin is always an app with this plugin""" + """This plugin is always an app with this plugin.""" return True class APICallMixin: - """Mixin that enables easier API calls for a plugin + """Mixin that enables easier API calls for a plugin. Steps to set up: 1. Add this mixin before (left of) SettingsMixin and PluginBase @@ -361,7 +362,7 @@ class APICallMixin: API_TOKEN = 'Bearer' class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'API calls' def __init__(self): @@ -465,7 +466,6 @@ class PanelMixin: 'javascript': 'alert("You just loaded this panel!")', 'content': 'Hello world', } - """ class MixinMeta: @@ -476,7 +476,7 @@ class PanelMixin: self.add_mixin('panel', True, __class__) def get_custom_panels(self, view, request): - """This method *must* be implemented by the plugin class""" + """This method *must* be implemented by the plugin class.""" raise MixinNotImplementedError(f"{__class__} is missing the 'get_custom_panels' method") def get_panel_context(self, view, request, context): diff --git a/InvenTree/plugin/base/integration/test_mixins.py b/InvenTree/plugin/base/integration/test_mixins.py index 722a71ad8f..7362485f91 100644 --- a/InvenTree/plugin/base/integration/test_mixins.py +++ b/InvenTree/plugin/base/integration/test_mixins.py @@ -1,4 +1,4 @@ -"""Unit tests for base mixins for plugins""" +"""Unit tests for base mixins for plugins.""" from django.conf import settings from django.test import TestCase @@ -170,7 +170,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): API_TOKEN_SETTING = 'API_TOKEN' def get_external_url(self, simple: bool = True): - """Returns data from the sample endpoint""" + """Returns data from the sample endpoint.""" return self.api_call('api/users/2', simple_response=simple) self.mixin = MixinCls() @@ -183,7 +183,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): self.mixin_wrong2 = WrongCLS2() def test_base_setup(self): - """Test that the base settings work""" + """Test that the base settings work.""" # check init self.assertTrue(self.mixin.has_api_call) # api_url @@ -194,7 +194,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): self.assertEqual(headers, {'Bearer': '', 'Content-Type': 'application/json'}) def test_args(self): - """Test that building up args work""" + """Test that building up args work.""" # api_build_url_args # 1 arg result = self.mixin.api_build_url_args({'a': 'b'}) @@ -207,7 +207,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): self.assertEqual(result, '?a=b&c=d,e,f') def test_api_call(self): - """Test that api calls work""" + """Test that api calls work.""" # api_call result = self.mixin.get_external_url() self.assertTrue(result) @@ -237,7 +237,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): self.assertEqual(result['page'], 2) def test_function_errors(self): - """Test function errors""" + """Test function errors.""" # wrongly defined plugins should not load with self.assertRaises(MixinNotImplementedError): self.mixin_wrong.has_api_call() @@ -248,7 +248,7 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): class PanelMixinTests(InvenTreeTestCase): - """Test that the PanelMixin plugin operates correctly""" + """Test that the PanelMixin plugin operates correctly.""" fixtures = [ 'category', @@ -260,7 +260,7 @@ class PanelMixinTests(InvenTreeTestCase): roles = 'all' def test_installed(self): - """Test that the sample panel plugin is installed""" + """Test that the sample panel plugin is installed.""" plugins = registry.with_mixin('panel') self.assertTrue(len(plugins) > 0) @@ -272,7 +272,7 @@ class PanelMixinTests(InvenTreeTestCase): self.assertEqual(len(plugins), 0) def test_disabled(self): - """Test that the panels *do not load* if the plugin is not enabled""" + """Test that the panels *do not load* if the plugin is not enabled.""" plugin = registry.get_plugin('samplepanel') plugin.set_setting('ENABLE_HELLO_WORLD', True) @@ -301,7 +301,7 @@ class PanelMixinTests(InvenTreeTestCase): self.assertNotIn('Custom Part Panel', str(response.content)) def test_enabled(self): - """Test that the panels *do* load if the plugin is enabled""" + """Test that the panels *do* load if the plugin is enabled.""" plugin = registry.get_plugin('samplepanel') self.assertEqual(len(registry.with_mixin('panel', active=True)), 0) @@ -375,7 +375,7 @@ class PanelMixinTests(InvenTreeTestCase): self.assertEqual(Error.objects.count(), n_errors + len(urls)) def test_mixin(self): - """Test that ImplementationError is raised""" + """Test that ImplementationError is raised.""" with self.assertRaises(MixinNotImplementedError): class Wrong(PanelMixin, InvenTreePlugin): pass diff --git a/InvenTree/plugin/base/label/label.py b/InvenTree/plugin/base/label/label.py index f02420bf61..6a13e616cd 100644 --- a/InvenTree/plugin/base/label/label.py +++ b/InvenTree/plugin/base/label/label.py @@ -1,4 +1,4 @@ -"""Functions to print a label to a mixin printer""" +"""Functions to print a label to a mixin printer.""" import logging diff --git a/InvenTree/plugin/base/label/mixins.py b/InvenTree/plugin/base/label/mixins.py index ddab7cd0c7..7fac8a4971 100644 --- a/InvenTree/plugin/base/label/mixins.py +++ b/InvenTree/plugin/base/label/mixins.py @@ -1,4 +1,4 @@ -"""Plugin mixin classes for label plugins""" +"""Plugin mixin classes for label plugins.""" from plugin.helpers import MixinNotImplementedError @@ -12,7 +12,7 @@ class LabelPrintingMixin: """ class MixinMeta: - """Meta options for this mixin""" + """Meta options for this mixin.""" MIXIN_NAME = 'Label printing' @@ -21,7 +21,7 @@ class LabelPrintingMixin: self.add_mixin('labels', True, __class__) def print_label(self, label, **kwargs): - """Callback to print a single label + """Callback to print a single label. Arguments: label: A black-and-white pillow Image object diff --git a/InvenTree/plugin/base/label/test_label_mixin.py b/InvenTree/plugin/base/label/test_label_mixin.py index 32c9f9f450..0f362287dd 100644 --- a/InvenTree/plugin/base/label/test_label_mixin.py +++ b/InvenTree/plugin/base/label/test_label_mixin.py @@ -1,4 +1,4 @@ -"""Unit tests for the label printing mixin""" +"""Unit tests for the label printing mixin.""" from django.apps import apps from django.urls import reverse @@ -15,7 +15,7 @@ from stock.models import StockItem, StockLocation class LabelMixinTests(InvenTreeAPITestCase): - """Test that the Label mixin operates correctly""" + """Test that the Label mixin operates correctly.""" fixtures = [ 'category', @@ -27,13 +27,13 @@ class LabelMixinTests(InvenTreeAPITestCase): roles = 'all' def do_activate_plugin(self): - """Activate the 'samplelabel' plugin""" + """Activate the 'samplelabel' plugin.""" config = registry.get_plugin('samplelabel').plugin_config() config.active = True config.save() def do_url(self, parts, plugin_ref, label, url_name: str = 'api-part-label-print', url_single: str = 'part', invalid: bool = False): - """Generate an URL to print a label""" + """Generate an URL to print a label.""" # Construct URL kwargs = {} if label: @@ -60,7 +60,7 @@ class LabelMixinTests(InvenTreeAPITestCase): return url def test_wrong_implementation(self): - """Test that a wrong implementation raises an error""" + """Test that a wrong implementation raises an error.""" class WrongPlugin(LabelPrintingMixin, InvenTreePlugin): pass @@ -69,7 +69,7 @@ class LabelMixinTests(InvenTreeAPITestCase): plugin.print_label('test') def test_installed(self): - """Test that the sample printing plugin is installed""" + """Test that the sample printing plugin is installed.""" # Get all label plugins plugins = registry.with_mixin('labels') self.assertEqual(len(plugins), 1) @@ -79,7 +79,7 @@ class LabelMixinTests(InvenTreeAPITestCase): self.assertEqual(len(plugins), 0) def test_api(self): - """Test that we can filter the API endpoint by mixin""" + """Test that we can filter the API endpoint by mixin.""" url = reverse('api-plugin-list') # Try POST (disallowed) @@ -123,7 +123,7 @@ class LabelMixinTests(InvenTreeAPITestCase): self.assertEqual(data['key'], 'samplelabel') def test_printing_process(self): - """Test that a label can be printed""" + """Test that a label can be printed.""" # Ensure the labels were created apps.get_app_config('label').create_labels() @@ -171,7 +171,7 @@ class LabelMixinTests(InvenTreeAPITestCase): self.do_activate_plugin() def run_print_test(label, qs, url_name, url_single): - """Run tests on single and multiple page printing + """Run tests on single and multiple page printing. Args: label (_type_): class of the label diff --git a/InvenTree/plugin/base/locate/api.py b/InvenTree/plugin/base/locate/api.py index 3b00490112..ee3b613267 100644 --- a/InvenTree/plugin/base/locate/api.py +++ b/InvenTree/plugin/base/locate/api.py @@ -1,4 +1,4 @@ -"""API for location plugins""" +"""API for location plugins.""" from rest_framework import permissions from rest_framework.exceptions import NotFound, ParseError @@ -11,7 +11,7 @@ from stock.models import StockItem, StockLocation class LocatePluginView(APIView): - """Endpoint for using a custom plugin to identify or 'locate' a stock item or location""" + """Endpoint for using a custom plugin to identify or 'locate' a stock item or location.""" permission_classes = [ permissions.IsAuthenticated, diff --git a/InvenTree/plugin/base/locate/mixins.py b/InvenTree/plugin/base/locate/mixins.py index 7ffec7c82c..7cf3d80e4d 100644 --- a/InvenTree/plugin/base/locate/mixins.py +++ b/InvenTree/plugin/base/locate/mixins.py @@ -1,4 +1,4 @@ -"""Plugin mixin for locating stock items and locations""" +"""Plugin mixin for locating stock items and locations.""" import logging @@ -31,7 +31,7 @@ class LocateMixin: self.add_mixin('locate', True, __class__) def locate_stock_item(self, item_pk): - """Attempt to locate a particular StockItem + """Attempt to locate a particular StockItem. Arguments: item_pk: The PK (primary key) of the StockItem to be located @@ -58,7 +58,7 @@ class LocateMixin: pass def locate_stock_location(self, location_pk): - """Attempt to location a particular StockLocation + """Attempt to location a particular StockLocation. Arguments: location_pk: The PK (primary key) of the StockLocation to be located diff --git a/InvenTree/plugin/base/locate/test_locate.py b/InvenTree/plugin/base/locate/test_locate.py index 4105167741..8e20554e1b 100644 --- a/InvenTree/plugin/base/locate/test_locate.py +++ b/InvenTree/plugin/base/locate/test_locate.py @@ -1,4 +1,4 @@ -"""Unit tests for the 'locate' plugin mixin class""" +"""Unit tests for the 'locate' plugin mixin class.""" from django.urls import reverse @@ -18,7 +18,7 @@ class LocatePluginTests(InvenTreeAPITestCase): ] def test_installed(self): - """Test that a locate plugin is actually installed""" + """Test that a locate plugin is actually installed.""" plugins = registry.with_mixin('locate') self.assertTrue(len(plugins) > 0) @@ -26,7 +26,7 @@ class LocatePluginTests(InvenTreeAPITestCase): self.assertTrue('samplelocate' in [p.slug for p in plugins]) def test_locate_fail(self): - """Test various API failure modes""" + """Test various API failure modes.""" url = reverse('api-locate-plugin') # Post without a plugin @@ -86,7 +86,7 @@ class LocatePluginTests(InvenTreeAPITestCase): self.assertIn(f"StockLocation matching PK '{pk}' not found", str(response.data)) def test_locate_item(self): - """Test that the plugin correctly 'locates' a StockItem + """Test that the plugin correctly 'locates' a StockItem. As the background worker is not running during unit testing, the sample 'locate' function will be called 'inline' @@ -115,7 +115,7 @@ class LocatePluginTests(InvenTreeAPITestCase): self.assertTrue(item.metadata['located']) def test_locate_location(self): - """Test that the plugin correctly 'locates' a StockLocation""" + """Test that the plugin correctly 'locates' a StockLocation.""" url = reverse('api-locate-plugin') for location in StockLocation.objects.all(): @@ -139,7 +139,7 @@ class LocatePluginTests(InvenTreeAPITestCase): self.assertTrue(location.metadata['located']) def test_mixin_locate(self): - """Test the sample mixin redirection""" + """Test the sample mixin redirection.""" class SamplePlugin(LocateMixin, InvenTreePlugin): pass diff --git a/InvenTree/plugin/builtin/action/simpleactionplugin.py b/InvenTree/plugin/builtin/action/simpleactionplugin.py index 483122a33d..e9a77a86b9 100644 --- a/InvenTree/plugin/builtin/action/simpleactionplugin.py +++ b/InvenTree/plugin/builtin/action/simpleactionplugin.py @@ -1,11 +1,11 @@ -"""Sample implementation for ActionMixin""" +"""Sample implementation for ActionMixin.""" from plugin import InvenTreePlugin from plugin.mixins import ActionMixin class SimpleActionPlugin(ActionMixin, InvenTreePlugin): - """An EXTREMELY simple action plugin which demonstrates the capability of the ActionMixin class""" + """An EXTREMELY simple action plugin which demonstrates the capability of the ActionMixin class.""" NAME = "SimpleActionPlugin" ACTION_NAME = "simple" diff --git a/InvenTree/plugin/builtin/action/test_simpleactionplugin.py b/InvenTree/plugin/builtin/action/test_simpleactionplugin.py index 67ee637a77..32da3d8540 100644 --- a/InvenTree/plugin/builtin/action/test_simpleactionplugin.py +++ b/InvenTree/plugin/builtin/action/test_simpleactionplugin.py @@ -1,11 +1,11 @@ -"""Unit tests for action plugins""" +"""Unit tests for action plugins.""" from InvenTree.helpers import InvenTreeTestCase from plugin.builtin.action.simpleactionplugin import SimpleActionPlugin class SimpleActionPluginTests(InvenTreeTestCase): - """Tests for SampleIntegrationPlugin""" + """Tests for SampleIntegrationPlugin.""" def setUp(self): super().setUp() @@ -13,12 +13,12 @@ class SimpleActionPluginTests(InvenTreeTestCase): self.plugin = SimpleActionPlugin() def test_name(self): - """Check plugn names""" + """Check plugn names.""" self.assertEqual(self.plugin.plugin_name(), "SimpleActionPlugin") self.assertEqual(self.plugin.action_name(), "simple") def test_function(self): - """Check if functions work""" + """Check if functions work.""" # test functions response = self.client.post('/api/action/', data={'action': "simple", 'data': {'foo': "bar", }}) self.assertEqual(response.status_code, 200) diff --git a/InvenTree/plugin/builtin/barcodes/inventree_barcode.py b/InvenTree/plugin/builtin/barcodes/inventree_barcode.py index a5c8cdb607..e21684e1ee 100644 --- a/InvenTree/plugin/builtin/barcodes/inventree_barcode.py +++ b/InvenTree/plugin/builtin/barcodes/inventree_barcode.py @@ -1,5 +1,4 @@ -"""The InvenTreeBarcodePlugin validates barcodes generated by InvenTree itself. -It can be used as a template for developing third-party barcode plugins. +"""The InvenTreeBarcodePlugin validates barcodes generated by InvenTree itself. It can be used as a template for developing third-party barcode plugins. The data format is very simple, and maps directly to database objects, via the "id" parameter. diff --git a/InvenTree/plugin/builtin/barcodes/test_inventree_barcode.py b/InvenTree/plugin/builtin/barcodes/test_inventree_barcode.py index cd95f0f35b..c4618483cf 100644 --- a/InvenTree/plugin/builtin/barcodes/test_inventree_barcode.py +++ b/InvenTree/plugin/builtin/barcodes/test_inventree_barcode.py @@ -1,4 +1,4 @@ -"""Unit tests for InvenTreeBarcodePlugin""" +"""Unit tests for InvenTreeBarcodePlugin.""" from django.urls import reverse @@ -17,7 +17,7 @@ class TestInvenTreeBarcode(InvenTreeAPITestCase): ] def test_errors(self): - """Test all possible error cases for assigment action""" + """Test all possible error cases for assigment action.""" def test_assert_error(barcode_data): response = self.client.post( @@ -43,7 +43,7 @@ class TestInvenTreeBarcode(InvenTreeAPITestCase): test_assert_error('{"blbla": 10004}') def test_scan(self): - """Test that a barcode can be scanned""" + """Test that a barcode can be scanned.""" response = self.client.post(reverse('api-barcode-scan'), format='json', data={'barcode': 'blbla=10004'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn('success', response.data) diff --git a/InvenTree/plugin/builtin/integration/core_notifications.py b/InvenTree/plugin/builtin/integration/core_notifications.py index a63dff43bc..9358eb3a61 100644 --- a/InvenTree/plugin/builtin/integration/core_notifications.py +++ b/InvenTree/plugin/builtin/integration/core_notifications.py @@ -1,4 +1,4 @@ -"""Core set of Notifications as a Plugin""" +"""Core set of Notifications as a Plugin.""" from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ @@ -16,7 +16,7 @@ class PlgMixin: class CoreNotificationsPlugin(SettingsMixin, InvenTreePlugin): - """Core notification methods for InvenTree""" + """Core notification methods for InvenTree.""" NAME = "CoreNotificationsPlugin" AUTHOR = _('InvenTree contributors') @@ -48,7 +48,7 @@ class CoreNotificationsPlugin(SettingsMixin, InvenTreePlugin): } def get_targets(self): - """Return a list of target email addresses, only for users which allow email notifications""" + """Return a list of target email addresses, only for users which allow email notifications.""" allowed_users = [] for user in self.targets: diff --git a/InvenTree/plugin/builtin/integration/test_core_notifications.py b/InvenTree/plugin/builtin/integration/test_core_notifications.py index cbfa2910c2..07c7c5cb41 100644 --- a/InvenTree/plugin/builtin/integration/test_core_notifications.py +++ b/InvenTree/plugin/builtin/integration/test_core_notifications.py @@ -8,7 +8,7 @@ from plugin.models import NotificationUserSetting class CoreNotificationTestTests(BaseNotificationIntegrationTest): def test_email(self): - """Ensure that the email notifications run""" + """Ensure that the email notifications run.""" # enable plugin and set mail setting to true plugin = registry.plugins.get('corenotificationsplugin') plugin.set_setting('ENABLE_NOTIFICATION_EMAILS', True) diff --git a/InvenTree/plugin/events.py b/InvenTree/plugin/events.py index eb8c9f8050..800233bd9a 100644 --- a/InvenTree/plugin/events.py +++ b/InvenTree/plugin/events.py @@ -1,4 +1,4 @@ -"""Import helper for events""" +"""Import helper for events.""" from plugin.base.event.events import (process_event, register_event, trigger_event) diff --git a/InvenTree/plugin/helpers.py b/InvenTree/plugin/helpers.py index 79eba76067..10f2706749 100644 --- a/InvenTree/plugin/helpers.py +++ b/InvenTree/plugin/helpers.py @@ -1,4 +1,4 @@ -"""Helpers for plugin app""" +"""Helpers for plugin app.""" import inspect import logging @@ -19,7 +19,7 @@ logger = logging.getLogger('inventree') # region logging / errors class IntegrationPluginError(Exception): - """Error that encapsulates another error and adds the path / reference of the raising plugin""" + """Error that encapsulates another error and adds the path / reference of the raising plugin.""" def __init__(self, path, message): self.path = path @@ -30,7 +30,7 @@ class IntegrationPluginError(Exception): class MixinImplementationError(ValueError): - """Error if mixin was implemented wrong in plugin + """Error if mixin was implemented wrong in plugin. Mostly raised if constant is missing """ @@ -38,12 +38,12 @@ class MixinImplementationError(ValueError): class MixinNotImplementedError(NotImplementedError): - """Error if necessary mixin function was not overwritten""" + """Error if necessary mixin function was not overwritten.""" pass def log_error(error, reference: str = 'general'): - """Log an plugin error""" + """Log an plugin error.""" from plugin import registry # make sure the registry is set up @@ -55,7 +55,7 @@ def log_error(error, reference: str = 'general'): def handle_error(error, do_raise: bool = True, do_log: bool = True, log_name: str = ''): - """Handles an error and casts it as an IntegrationPluginError""" + """Handles an error and casts it as an IntegrationPluginError.""" package_path = traceback.extract_tb(error.__traceback__)[-1].filename install_path = sysconfig.get_paths()["purelib"] try: @@ -91,7 +91,7 @@ def handle_error(error, do_raise: bool = True, do_log: bool = True, log_name: st # region git-helpers def get_git_log(path): - """Get dict with info of the last commit to file named in path""" + """Get dict with info of the last commit to file named in path.""" from plugin import registry output = None @@ -112,7 +112,7 @@ def get_git_log(path): def check_git_version(): - """Returns if the current git version supports modern features""" + """Returns if the current git version supports modern features.""" # get version string try: output = str(subprocess.check_output(['git', '--version'], cwd=os.path.dirname(settings.BASE_DIR)), 'utf-8') @@ -132,10 +132,10 @@ def check_git_version(): class GitStatus: - """Class for resolving git gpg singing state""" + """Class for resolving git gpg singing state.""" class Definition: - """Definition of a git gpg sing state""" + """Definition of a git gpg sing state.""" key: str = 'N' status: int = 2 @@ -159,7 +159,7 @@ class GitStatus: # region plugin finders def get_modules(pkg): - """Get all modules in a package""" + """Get all modules in a package.""" context = {} for loader, name, ispkg in pkgutil.walk_packages(pkg.__path__): try: @@ -181,7 +181,7 @@ def get_modules(pkg): def get_classes(module): - """Get all classes in a given module""" + """Get all classes in a given module.""" return inspect.getmembers(module, inspect.isclass) @@ -228,7 +228,7 @@ def render_template(plugin, template_file, context=None): def render_text(text, context=None): - """Locate a raw string with provided context""" + """Locate a raw string with provided context.""" ctx = template.Context(context) return template.Template(text).render(ctx) diff --git a/InvenTree/plugin/mixins/__init__.py b/InvenTree/plugin/mixins/__init__.py index 5c139d76cb..207a65ab42 100644 --- a/InvenTree/plugin/mixins/__init__.py +++ b/InvenTree/plugin/mixins/__init__.py @@ -1,4 +1,4 @@ -"""Utility class to enable simpler imports""" +"""Utility class to enable simpler imports.""" from common.notifications import (BulkNotificationMethod, SingleNotificationMethod) diff --git a/InvenTree/plugin/models.py b/InvenTree/plugin/models.py index 46aed598c6..bd8bd5306e 100644 --- a/InvenTree/plugin/models.py +++ b/InvenTree/plugin/models.py @@ -1,4 +1,4 @@ -"""Plugin model definitions""" +"""Plugin model definitions.""" import warnings @@ -33,7 +33,7 @@ class MetadataMixin(models.Model): ) def get_metadata(self, key: str, backup_value=None): - """Finds metadata for this model instance, using the provided key for lookup + """Finds metadata for this model instance, using the provided key for lookup. Args: key: String key for requesting metadata. e.g. if a plugin is accessing the metadata, the plugin slug should be used @@ -115,7 +115,7 @@ class PluginConfig(models.Model): # functions def __init__(self, *args, **kwargs): - """Override to set original state of the plugin-config instance""" + """Override to set original state of the plugin-config instance.""" super().__init__(*args, **kwargs) self.__org_active = self.active @@ -134,7 +134,7 @@ class PluginConfig(models.Model): } def save(self, force_insert=False, force_update=False, *args, **kwargs): - """Extend save method to reload plugins if the 'active' status changes""" + """Extend save method to reload plugins if the 'active' status changes.""" reload = kwargs.pop('no_reload', False) # check if no_reload flag is set ret = super().save(force_insert, force_update, *args, **kwargs) @@ -150,7 +150,7 @@ class PluginConfig(models.Model): class PluginSetting(common.models.BaseInvenTreeSetting): - """This model represents settings for individual plugins""" + """This model represents settings for individual plugins.""" class Meta: unique_together = [ @@ -191,14 +191,14 @@ class PluginSetting(common.models.BaseInvenTreeSetting): return super().get_setting_definition(key, **kwargs) def get_kwargs(self): - """Explicit kwargs required to uniquely identify a particular setting object, in addition to the 'key' parameter""" + """Explicit kwargs required to uniquely identify a particular setting object, in addition to the 'key' parameter.""" return { 'plugin': self.plugin, } class NotificationUserSetting(common.models.BaseInvenTreeSetting): - """This model represents notification settings for a user""" + """This model represents notification settings for a user.""" class Meta: unique_together = [ @@ -214,7 +214,7 @@ class NotificationUserSetting(common.models.BaseInvenTreeSetting): return super().get_setting_definition(key, **kwargs) def get_kwargs(self): - """Explicit kwargs required to uniquely identify a particular setting object, in addition to the 'key' parameter""" + """Explicit kwargs required to uniquely identify a particular setting object, in addition to the 'key' parameter.""" return { 'method': self.method, 'user': self.user, diff --git a/InvenTree/plugin/plugin.py b/InvenTree/plugin/plugin.py index 38bb397c82..944f06ab6e 100644 --- a/InvenTree/plugin/plugin.py +++ b/InvenTree/plugin/plugin.py @@ -1,4 +1,4 @@ -"""Base Class for InvenTree plugins""" +"""Base Class for InvenTree plugins.""" import inspect import logging @@ -19,7 +19,7 @@ logger = logging.getLogger("inventree") class MetaBase: - """Base class for a plugins metadata""" + """Base class for a plugins metadata.""" # Override the plugin name for each concrete plugin instance NAME = '' @@ -27,7 +27,7 @@ class MetaBase: TITLE = None def get_meta_value(self, key: str, old_key: str = None, __default=None): - """Reference a meta item with a key + """Reference a meta item with a key. Args: key (str): key for the value @@ -53,16 +53,16 @@ class MetaBase: return value def plugin_name(self): - """Name of plugin""" + """Name of plugin.""" return self.get_meta_value('NAME', 'PLUGIN_NAME') @property def name(self): - """Name of plugin""" + """Name of plugin.""" return self.plugin_name() def plugin_slug(self): - """Slug of plugin + """Slug of plugin. If not set plugin name slugified """ @@ -74,11 +74,11 @@ class MetaBase: @property def slug(self): - """Slug of plugin""" + """Slug of plugin.""" return self.plugin_slug() def plugin_title(self): - """Title of plugin""" + """Title of plugin.""" title = self.get_meta_value('TITLE', 'PLUGIN_TITLE', None) if title: return title @@ -86,11 +86,11 @@ class MetaBase: @property def human_name(self): - """Human readable name of plugin""" + """Human readable name of plugin.""" return self.plugin_title() def plugin_config(self): - """Return the PluginConfig object associated with this plugin""" + """Return the PluginConfig object associated with this plugin.""" try: import plugin.models @@ -104,7 +104,7 @@ class MetaBase: return cfg def is_active(self): - """Return True if this plugin is currently active""" + """Return True if this plugin is currently active.""" cfg = self.plugin_config() if cfg: @@ -114,7 +114,7 @@ class MetaBase: class MixinBase: - """Base set of mixin functions and mechanisms""" + """Base set of mixin functions and mechanisms.""" def __init__(self, *args, **kwargs) -> None: self._mixinreg = {} @@ -122,11 +122,11 @@ class MixinBase: super().__init__(*args, **kwargs) def mixin(self, key): - """Check if mixin is registered""" + """Check if mixin is registered.""" return key in self._mixins def mixin_enabled(self, key): - """Check if mixin is registered, enabled and ready""" + """Check if mixin is registered, enabled and ready.""" if self.mixin(key): fnc_name = self._mixins.get(key) @@ -138,12 +138,12 @@ class MixinBase: return False def add_mixin(self, key: str, fnc_enabled=True, cls=None): - """Add a mixin to the plugins registry""" + """Add a mixin to the plugins registry.""" self._mixins[key] = fnc_enabled self.setup_mixin(key, cls=cls) def setup_mixin(self, key, cls=None): - """Define mixin details for the current mixin -> provides meta details for all active mixins""" + """Define mixin details for the current mixin -> provides meta details for all active mixins.""" # get human name human_name = getattr(cls.MixinMeta, 'MIXIN_NAME', key) if cls and hasattr(cls, 'MixinMeta') else key @@ -155,7 +155,7 @@ class MixinBase: @property def registered_mixins(self, with_base: bool = False): - """Get all registered mixins for the plugin""" + """Get all registered mixins for the plugin.""" mixins = getattr(self, '_mixinreg', None) if mixins: # filter out base @@ -167,7 +167,7 @@ class MixinBase: class InvenTreePlugin(MixinBase, MetaBase): - """The InvenTreePlugin class is used to integrate with 3rd party software + """The InvenTreePlugin class is used to integrate with 3rd party software. DO NOT USE THIS DIRECTLY, USE plugin.InvenTreePlugin """ @@ -190,7 +190,7 @@ class InvenTreePlugin(MixinBase, MetaBase): # region properties @property def description(self): - """Description of plugin""" + """Description of plugin.""" description = getattr(self, 'DESCRIPTION', None) if not description: description = self.plugin_name() @@ -220,7 +220,7 @@ class InvenTreePlugin(MixinBase, MetaBase): @property def version(self): - """Version of plugin""" + """Version of plugin.""" version = getattr(self, 'VERSION', None) return version @@ -232,14 +232,14 @@ class InvenTreePlugin(MixinBase, MetaBase): @property def license(self): - """License of plugin""" + """License of plugin.""" lic = getattr(self, 'LICENSE', None) return lic # endregion @property def _is_package(self): - """Is the plugin delivered as a package""" + """Is the plugin delivered as a package.""" return getattr(self, 'is_package', False) @property @@ -250,27 +250,27 @@ class InvenTreePlugin(MixinBase, MetaBase): @property def package_path(self): - """Path to the plugin""" + """Path to the plugin.""" if self._is_package: return self.__module__ # pragma: no cover return pathlib.Path(self.def_path).relative_to(settings.BASE_DIR) @property def settings_url(self): - """URL to the settings panel for this plugin""" + """URL to the settings panel for this plugin.""" return f'{reverse("settings")}#select-plugin-{self.slug}' # region package info def _get_package_commit(self): - """Get last git commit for the plugin""" + """Get last git commit for the plugin.""" return get_git_log(self.def_path) def _get_package_metadata(self): - """Get package metadata for plugin""" + """Get package metadata for plugin.""" return {} # pragma: no cover # TODO add usage for package metadata def define_package(self): - """Add package info of the plugin into plugins context""" + """Add package info of the plugin into plugins context.""" package = self._get_package_metadata() if self._is_package else self._get_package_commit() # process date @@ -294,7 +294,7 @@ class InvenTreePlugin(MixinBase, MetaBase): class IntegrationPluginBase(InvenTreePlugin): def __init__(self, *args, **kwargs): - """Send warning about using this reference""" + """Send warning about using this reference.""" # TODO remove in 0.8.0 warnings.warn("This import is deprecated - use InvenTreePlugin", DeprecationWarning) super().__init__(*args, **kwargs) diff --git a/InvenTree/plugin/registry.py b/InvenTree/plugin/registry.py index 2dcb796d59..b00d15b9d8 100644 --- a/InvenTree/plugin/registry.py +++ b/InvenTree/plugin/registry.py @@ -1,4 +1,4 @@ -"""Registry for loading and managing multiple plugins at run-time +"""Registry for loading and managing multiple plugins at run-time. - Holds the class and the object that contains all code to maintain plugin states - Manages setup and teardown of plugin class instances @@ -30,7 +30,7 @@ logger = logging.getLogger('inventree') class PluginsRegistry: - """The PluginsRegistry class""" + """The PluginsRegistry class.""" def __init__(self) -> None: # plugin registry @@ -79,7 +79,7 @@ class PluginsRegistry: # region public functions # region loading / unloading def load_plugins(self): - """Load and activate all IntegrationPlugins""" + """Load and activate all IntegrationPlugins.""" if not settings.PLUGINS_ENABLED: # Plugins not enabled, do nothing return # pragma: no cover @@ -134,7 +134,7 @@ class PluginsRegistry: logger.info('Finished loading plugins') def unload_plugins(self): - """Unload and deactivate all IntegrationPlugins""" + """Unload and deactivate all IntegrationPlugins.""" if not settings.PLUGINS_ENABLED: # Plugins not enabled, do nothing return # pragma: no cover @@ -158,7 +158,7 @@ class PluginsRegistry: logger.info('Finished unloading plugins') def reload_plugins(self): - """Safely reload IntegrationPlugins""" + """Safely reload IntegrationPlugins.""" # Do not reload whe currently loading if self.is_loading: return # pragma: no cover @@ -172,7 +172,7 @@ class PluginsRegistry: logger.info('Finished reloading plugins') def collect_plugins(self): - """Collect plugins from all possible ways of loading""" + """Collect plugins from all possible ways of loading.""" if not settings.PLUGINS_ENABLED: # Plugins not enabled, do nothing return # pragma: no cover @@ -201,7 +201,7 @@ class PluginsRegistry: logger.info(", ".join([a.__module__ for a in self.plugin_modules])) def install_plugin_file(self): - """Make sure all plugins are installed in the current enviroment""" + """Make sure all plugins are installed in the current enviroment.""" if settings.PLUGIN_FILE_CHECKED: logger.info('Plugin file was already checked') return True @@ -222,7 +222,7 @@ class PluginsRegistry: # region registry functions def with_mixin(self, mixin: str, active=None): - """Returns reference to all plugins that have a specified mixin enabled""" + """Returns reference to all plugins that have a specified mixin enabled.""" result = [] for plugin in self.plugins.values(): @@ -243,7 +243,7 @@ class PluginsRegistry: # region general internal loading /activating / deactivating / deloading def _init_plugins(self, disabled=None): - """Initialise all found plugins + """Initialise all found plugins. :param disabled: loading path of disabled app, defaults to None :type disabled: str, optional @@ -312,7 +312,7 @@ class PluginsRegistry: self.plugins_inactive[plug_key] = plugin_db_setting # pragma: no cover def _activate_plugins(self, force_reload=False): - """Run activation functions for all plugins + """Run activation functions for all plugins. :param force_reload: force reload base apps, defaults to False :type force_reload: bool, optional @@ -326,7 +326,7 @@ class PluginsRegistry: self.activate_plugin_app(plugins, force_reload=force_reload) def _deactivate_plugins(self): - """Run deactivation functions for all plugins""" + """Run deactivation functions for all plugins.""" self.deactivate_plugin_app() self.deactivate_plugin_schedule() self.deactivate_plugin_settings() @@ -400,7 +400,7 @@ class PluginsRegistry: logger.warning("activate_integration_schedule failed, database not ready") def deactivate_plugin_schedule(self): - """Deactivate ScheduleMixin + """Deactivate ScheduleMixin. currently nothing is done """ @@ -478,7 +478,7 @@ class PluginsRegistry: reload(app_config.module.admin) def _get_plugin_path(self, plugin): - """Parse plugin path + """Parse plugin path. The input can be eiter: - a local file / dir @@ -576,7 +576,7 @@ class PluginsRegistry: self.is_loading = False def _try_reload(self, cmd, *args, **kwargs): - """Wrapper to try reloading the apps + """Wrapper to try reloading the apps. Throws an custom error that gets handled by the loading function """ @@ -592,5 +592,5 @@ registry = PluginsRegistry() def call_function(plugin_name, function_name, *args, **kwargs): - """Global helper function to call a specific member function of a plugin""" + """Global helper function to call a specific member function of a plugin.""" return registry.call_plugin_function(plugin_name, function_name, *args, **kwargs) diff --git a/InvenTree/plugin/samples/event/event_sample.py b/InvenTree/plugin/samples/event/event_sample.py index f62552803e..9912d5f80c 100644 --- a/InvenTree/plugin/samples/event/event_sample.py +++ b/InvenTree/plugin/samples/event/event_sample.py @@ -1,4 +1,4 @@ -"""Sample plugin which responds to events""" +"""Sample plugin which responds to events.""" import warnings @@ -9,14 +9,14 @@ from plugin.mixins import EventMixin class EventPluginSample(EventMixin, InvenTreePlugin): - """A sample plugin which provides supports for triggered events""" + """A sample plugin which provides supports for triggered events.""" NAME = "EventPlugin" SLUG = "sampleevent" TITLE = "Triggered Events" def process_event(self, event, *args, **kwargs): - """Custom event processing""" + """Custom event processing.""" print(f"Processing triggered event: '{event}'") print("args:", str(args)) print("kwargs:", str(kwargs)) diff --git a/InvenTree/plugin/samples/event/test_event_sample.py b/InvenTree/plugin/samples/event/test_event_sample.py index 964d107673..4f28e6595f 100644 --- a/InvenTree/plugin/samples/event/test_event_sample.py +++ b/InvenTree/plugin/samples/event/test_event_sample.py @@ -1,4 +1,4 @@ -"""Unit tests for event_sample sample plugins""" +"""Unit tests for event_sample sample plugins.""" from django.conf import settings from django.test import TestCase @@ -10,10 +10,10 @@ from plugin.mixins import EventMixin class EventPluginSampleTests(TestCase): - """Tests for EventPluginSample""" + """Tests for EventPluginSample.""" def test_run_event(self): - """Check if the event is issued""" + """Check if the event is issued.""" # Activate plugin config = registry.get_plugin('sampleevent').plugin_config() config.active = True @@ -30,7 +30,7 @@ class EventPluginSampleTests(TestCase): settings.PLUGIN_TESTING_EVENTS = False def test_mixin(self): - """Test that MixinNotImplementedError is raised""" + """Test that MixinNotImplementedError is raised.""" with self.assertRaises(MixinNotImplementedError): class Wrong(EventMixin, InvenTreePlugin): pass diff --git a/InvenTree/plugin/samples/integration/another_sample.py b/InvenTree/plugin/samples/integration/another_sample.py index e509c33299..580e69d9cf 100644 --- a/InvenTree/plugin/samples/integration/another_sample.py +++ b/InvenTree/plugin/samples/integration/another_sample.py @@ -1,15 +1,15 @@ -"""Sample implementation for IntegrationPlugin""" +"""Sample implementation for IntegrationPlugin.""" from plugin import InvenTreePlugin from plugin.mixins import UrlsMixin class NoIntegrationPlugin(InvenTreePlugin): - """A basic plugin""" + """A basic plugin.""" NAME = "NoIntegrationPlugin" class WrongIntegrationPlugin(UrlsMixin, InvenTreePlugin): - """A basic wron plugin with urls""" + """A basic wron plugin with urls.""" NAME = "WrongIntegrationPlugin" diff --git a/InvenTree/plugin/samples/integration/api_caller.py b/InvenTree/plugin/samples/integration/api_caller.py index 81647609f7..0968780e8b 100644 --- a/InvenTree/plugin/samples/integration/api_caller.py +++ b/InvenTree/plugin/samples/integration/api_caller.py @@ -1,10 +1,10 @@ -"""Sample plugin for calling an external API""" +"""Sample plugin for calling an external API.""" from plugin import InvenTreePlugin from plugin.mixins import APICallMixin, SettingsMixin class SampleApiCallerPlugin(APICallMixin, SettingsMixin, InvenTreePlugin): - """A small api call sample""" + """A small api call sample.""" NAME = "Sample API Caller" @@ -23,5 +23,5 @@ class SampleApiCallerPlugin(APICallMixin, SettingsMixin, InvenTreePlugin): API_TOKEN_SETTING = 'API_TOKEN' def get_external_url(self): - """Returns data from the sample endpoint""" + """Returns data from the sample endpoint.""" return self.api_call('api/users/2') diff --git a/InvenTree/plugin/samples/integration/broken_file.py b/InvenTree/plugin/samples/integration/broken_file.py index 25e51cac6d..f56932e876 100644 --- a/InvenTree/plugin/samples/integration/broken_file.py +++ b/InvenTree/plugin/samples/integration/broken_file.py @@ -1,10 +1,10 @@ -"""Sample of a broken python file that will be ignored on import""" +"""Sample of a broken python file that will be ignored on import.""" from plugin import InvenTreePlugin class BrokenFileIntegrationPlugin(InvenTreePlugin): - """An very broken plugin""" + """An very broken plugin.""" aaa = bb # noqa: F821 diff --git a/InvenTree/plugin/samples/integration/broken_sample.py b/InvenTree/plugin/samples/integration/broken_sample.py index 65a5a427d5..a5a2c494de 100644 --- a/InvenTree/plugin/samples/integration/broken_sample.py +++ b/InvenTree/plugin/samples/integration/broken_sample.py @@ -1,9 +1,9 @@ -"""Sample of a broken plugin""" +"""Sample of a broken plugin.""" from plugin import InvenTreePlugin class BrokenIntegrationPlugin(InvenTreePlugin): - """A very broken plugin""" + """A very broken plugin.""" NAME = 'Test' TITLE = 'Broken Plugin' diff --git a/InvenTree/plugin/samples/integration/custom_panel_sample.py b/InvenTree/plugin/samples/integration/custom_panel_sample.py index 7f4be55298..ce31f65c98 100644 --- a/InvenTree/plugin/samples/integration/custom_panel_sample.py +++ b/InvenTree/plugin/samples/integration/custom_panel_sample.py @@ -1,4 +1,4 @@ -"""Sample plugin which renders custom panels on certain pages""" +"""Sample plugin which renders custom panels on certain pages.""" from part.views import PartDetail from plugin import InvenTreePlugin diff --git a/InvenTree/plugin/samples/integration/label_sample.py b/InvenTree/plugin/samples/integration/label_sample.py index 783f67711b..e367722610 100644 --- a/InvenTree/plugin/samples/integration/label_sample.py +++ b/InvenTree/plugin/samples/integration/label_sample.py @@ -4,7 +4,7 @@ from plugin.mixins import LabelPrintingMixin class SampleLabelPrinter(LabelPrintingMixin, InvenTreePlugin): - """Sample plugin which provides a 'fake' label printer endpoint""" + """Sample plugin which provides a 'fake' label printer endpoint.""" NAME = "Label Printer" SLUG = "samplelabel" diff --git a/InvenTree/plugin/samples/integration/sample.py b/InvenTree/plugin/samples/integration/sample.py index 3d6f20319e..48bab78f91 100644 --- a/InvenTree/plugin/samples/integration/sample.py +++ b/InvenTree/plugin/samples/integration/sample.py @@ -1,4 +1,4 @@ -"""Sample implementations for IntegrationPlugin""" +"""Sample implementations for IntegrationPlugin.""" from django.http import HttpResponse from django.urls import include, re_path @@ -9,7 +9,7 @@ from plugin.mixins import AppMixin, NavigationMixin, SettingsMixin, UrlsMixin class SampleIntegrationPlugin(AppMixin, SettingsMixin, UrlsMixin, NavigationMixin, InvenTreePlugin): - """A full plugin example""" + """A full plugin example.""" NAME = "SampleIntegrationPlugin" SLUG = "sample" @@ -19,7 +19,7 @@ class SampleIntegrationPlugin(AppMixin, SettingsMixin, UrlsMixin, NavigationMixi NAVIGATION_TAB_ICON = 'fas fa-plus' def view_test(self, request): - """Very basic view""" + """Very basic view.""" return HttpResponse(f'Hi there {request.user.username} this works') def setup_urls(self): diff --git a/InvenTree/plugin/samples/integration/scheduled_task.py b/InvenTree/plugin/samples/integration/scheduled_task.py index 72473e8a1e..71ec8007ee 100644 --- a/InvenTree/plugin/samples/integration/scheduled_task.py +++ b/InvenTree/plugin/samples/integration/scheduled_task.py @@ -1,4 +1,4 @@ -"""Sample plugin which supports task scheduling""" +"""Sample plugin which supports task scheduling.""" from plugin import InvenTreePlugin from plugin.mixins import ScheduleMixin, SettingsMixin @@ -14,7 +14,7 @@ def print_world(): class ScheduledTaskPlugin(ScheduleMixin, SettingsMixin, InvenTreePlugin): - """A sample plugin which provides support for scheduled tasks""" + """A sample plugin which provides support for scheduled tasks.""" NAME = "ScheduledTasksPlugin" SLUG = "schedule" @@ -47,7 +47,7 @@ class ScheduledTaskPlugin(ScheduleMixin, SettingsMixin, InvenTreePlugin): } def member_func(self, *args, **kwargs): - """A simple member function to demonstrate functionality""" + """A simple member function to demonstrate functionality.""" t_or_f = self.get_setting('T_OR_F') print(f"Called member_func - value is {t_or_f}") diff --git a/InvenTree/plugin/samples/integration/test_api_caller.py b/InvenTree/plugin/samples/integration/test_api_caller.py index e0d07931e8..28b51835c8 100644 --- a/InvenTree/plugin/samples/integration/test_api_caller.py +++ b/InvenTree/plugin/samples/integration/test_api_caller.py @@ -1,4 +1,4 @@ -"""Unit tests for action caller sample""" +"""Unit tests for action caller sample.""" from django.test import TestCase @@ -6,10 +6,10 @@ from plugin import registry class SampleApiCallerPluginTests(TestCase): - """Tests for SampleApiCallerPluginTests""" + """Tests for SampleApiCallerPluginTests.""" def test_return(self): - """Check if the external api call works""" + """Check if the external api call works.""" # The plugin should be defined self.assertIn('sample-api-caller', registry.plugins) plg = registry.plugins['sample-api-caller'] diff --git a/InvenTree/plugin/samples/integration/test_sample.py b/InvenTree/plugin/samples/integration/test_sample.py index 38b9a22417..bd04377f97 100644 --- a/InvenTree/plugin/samples/integration/test_sample.py +++ b/InvenTree/plugin/samples/integration/test_sample.py @@ -1,13 +1,13 @@ -"""Unit tests for action plugins""" +"""Unit tests for action plugins.""" from InvenTree.helpers import InvenTreeTestCase class SampleIntegrationPluginTests(InvenTreeTestCase): - """Tests for SampleIntegrationPlugin""" + """Tests for SampleIntegrationPlugin.""" def test_view(self): - """Check the function of the custom sample plugin""" + """Check the function of the custom sample plugin.""" response = self.client.get('/plugin/sample/ho/he/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'Hi there testuser this works') diff --git a/InvenTree/plugin/samples/integration/test_scheduled_task.py b/InvenTree/plugin/samples/integration/test_scheduled_task.py index 3fa01096d7..32627c0aa9 100644 --- a/InvenTree/plugin/samples/integration/test_scheduled_task.py +++ b/InvenTree/plugin/samples/integration/test_scheduled_task.py @@ -1,4 +1,4 @@ -"""Unit tests for scheduled tasks""" +"""Unit tests for scheduled tasks.""" from django.test import TestCase @@ -9,10 +9,10 @@ from plugin.registry import call_function class ExampleScheduledTaskPluginTests(TestCase): - """Tests for provided ScheduledTaskPlugin""" + """Tests for provided ScheduledTaskPlugin.""" def test_function(self): - """Check if the scheduling works""" + """Check if the scheduling works.""" # The plugin should be defined self.assertIn('schedule', registry.plugins) plg = registry.plugins['schedule'] @@ -44,7 +44,7 @@ class ExampleScheduledTaskPluginTests(TestCase): self.assertEqual(len(scheduled_plugin_tasks), 0) def test_calling(self): - """Check if a function can be called without errors""" + """Check if a function can be called without errors.""" # Check with right parameters self.assertEqual(call_function('schedule', 'member_func'), False) @@ -53,22 +53,22 @@ class ExampleScheduledTaskPluginTests(TestCase): class ScheduledTaskPluginTests(TestCase): - """Tests for ScheduledTaskPluginTests mixin base""" + """Tests for ScheduledTaskPluginTests mixin base.""" def test_init(self): - """Check that all MixinImplementationErrors raise""" + """Check that all MixinImplementationErrors raise.""" class Base(ScheduleMixin, InvenTreePlugin): NAME = 'APlugin' class NoSchedules(Base): - """Plugin without schedules""" + """Plugin without schedules.""" pass with self.assertRaises(MixinImplementationError): NoSchedules() class WrongFuncSchedules(Base): - """Plugin with broken functions + """Plugin with broken functions. This plugin is missing a func """ @@ -87,7 +87,7 @@ class ScheduledTaskPluginTests(TestCase): WrongFuncSchedules() class WrongFuncSchedules1(WrongFuncSchedules): - """Plugin with broken functions + """Plugin with broken functions. This plugin is missing a schedule """ @@ -103,7 +103,7 @@ class ScheduledTaskPluginTests(TestCase): WrongFuncSchedules1() class WrongFuncSchedules2(WrongFuncSchedules): - """Plugin with broken functions + """Plugin with broken functions. This plugin is missing a schedule """ @@ -119,7 +119,7 @@ class ScheduledTaskPluginTests(TestCase): WrongFuncSchedules2() class WrongFuncSchedules3(WrongFuncSchedules): - """Plugin with broken functions + """Plugin with broken functions. This plugin has a broken schedule """ @@ -136,7 +136,7 @@ class ScheduledTaskPluginTests(TestCase): WrongFuncSchedules3() class WrongFuncSchedules4(WrongFuncSchedules): - """Plugin with broken functions + """Plugin with broken functions. This plugin is missing a minute marker for its schedule """ diff --git a/InvenTree/plugin/samples/locate/locate_sample.py b/InvenTree/plugin/samples/locate/locate_sample.py index d1a3a4c7c6..99307f04e6 100644 --- a/InvenTree/plugin/samples/locate/locate_sample.py +++ b/InvenTree/plugin/samples/locate/locate_sample.py @@ -1,5 +1,4 @@ -""" -Sample plugin for locating stock items / locations. +"""Sample plugin for locating stock items / locations. Note: This plugin does not *actually* locate anything! """ diff --git a/InvenTree/plugin/samples/locate/test_locate_sample.py b/InvenTree/plugin/samples/locate/test_locate_sample.py index 45b0fd292c..1e85ceb566 100644 --- a/InvenTree/plugin/samples/locate/test_locate_sample.py +++ b/InvenTree/plugin/samples/locate/test_locate_sample.py @@ -1,4 +1,4 @@ -"""Unit tests for locate_sample sample plugins""" +"""Unit tests for locate_sample sample plugins.""" from django.urls import reverse @@ -9,7 +9,7 @@ from plugin.mixins import LocateMixin class SampleLocatePlugintests(InvenTreeAPITestCase): - """Tests for SampleLocatePlugin""" + """Tests for SampleLocatePlugin.""" fixtures = [ 'location', @@ -19,7 +19,7 @@ class SampleLocatePlugintests(InvenTreeAPITestCase): ] def test_run_locator(self): - """Check if the event is issued""" + """Check if the event is issued.""" # Activate plugin config = registry.get_plugin('samplelocate').plugin_config() config.active = True @@ -50,7 +50,7 @@ class SampleLocatePlugintests(InvenTreeAPITestCase): self.post(url, {'plugin': 'samplelocate', 'location': 1}, expected_code=200) def test_mixin(self): - """Test that MixinNotImplementedError is raised""" + """Test that MixinNotImplementedError is raised.""" with self.assertRaises(MixinNotImplementedError): class Wrong(LocateMixin, InvenTreePlugin): pass diff --git a/InvenTree/plugin/serializers.py b/InvenTree/plugin/serializers.py index 7c8a1644bf..857d5504dc 100644 --- a/InvenTree/plugin/serializers.py +++ b/InvenTree/plugin/serializers.py @@ -1,4 +1,4 @@ -"""JSON serializers for plugin app""" +"""JSON serializers for plugin app.""" import os import subprocess @@ -58,7 +58,7 @@ class PluginConfigSerializer(serializers.ModelSerializer): class PluginConfigInstallSerializer(serializers.Serializer): - """Serializer for installing a new plugin""" + """Serializer for installing a new plugin.""" url = serializers.CharField( required=False, @@ -148,7 +148,7 @@ class PluginConfigInstallSerializer(serializers.Serializer): class PluginSettingSerializer(GenericReferencedSettingSerializer): - """Serializer for the PluginSetting model""" + """Serializer for the PluginSetting model.""" MODEL = PluginSetting EXTRA_FIELDS = [ @@ -159,7 +159,7 @@ class PluginSettingSerializer(GenericReferencedSettingSerializer): class NotificationUserSettingSerializer(GenericReferencedSettingSerializer): - """Serializer for the PluginSetting model""" + """Serializer for the PluginSetting model.""" MODEL = NotificationUserSetting EXTRA_FIELDS = ['method', ] diff --git a/InvenTree/plugin/template.py b/InvenTree/plugin/template.py index 47fda8d68b..e396b1dd6b 100644 --- a/InvenTree/plugin/template.py +++ b/InvenTree/plugin/template.py @@ -1,4 +1,4 @@ -"""Load templates for loaded plugins""" +"""Load templates for loaded plugins.""" from pathlib import Path diff --git a/InvenTree/plugin/templatetags/plugin_extras.py b/InvenTree/plugin/templatetags/plugin_extras.py index b0e60a6285..35d4db5e17 100644 --- a/InvenTree/plugin/templatetags/plugin_extras.py +++ b/InvenTree/plugin/templatetags/plugin_extras.py @@ -1,4 +1,4 @@ -"""This module provides template tags for handeling plugins""" +"""This module provides template tags for handeling plugins.""" from django import template from django.conf import settings as djangosettings @@ -13,19 +13,19 @@ register = template.Library() @register.simple_tag() def plugin_list(*args, **kwargs): - """List of all installed plugins""" + """List of all installed plugins.""" return registry.plugins @register.simple_tag() def inactive_plugin_list(*args, **kwargs): - """List of all inactive plugins""" + """List of all inactive plugins.""" return registry.plugins_inactive @register.simple_tag() def plugin_settings(plugin, *args, **kwargs): - """List of all settings for the plugin""" + """List of all settings for the plugin.""" return registry.mixins_settings.get(plugin) @@ -37,7 +37,7 @@ def mixin_enabled(plugin, key, *args, **kwargs): @register.simple_tag() def mixin_available(mixin, *args, **kwargs): - """Returns True if there is at least one active plugin which supports the provided mixin""" + """Returns True if there is at least one active plugin which supports the provided mixin.""" return len(registry.with_mixin(mixin)) > 0 @@ -51,7 +51,7 @@ def navigation_enabled(*args, **kwargs): @register.simple_tag() def safe_url(view_name, *args, **kwargs): - """Safe lookup fnc for URLs + """Safe lookup fnc for URLs. Returns None if not found """ @@ -63,11 +63,11 @@ def safe_url(view_name, *args, **kwargs): @register.simple_tag() def plugin_errors(*args, **kwargs): - """All plugin errors in the current session""" + """All plugin errors in the current session.""" return registry.errors @register.simple_tag(takes_context=True) def notification_settings_list(context, *args, **kwargs): - """List of all user notification settings""" + """List of all user notification settings.""" return storage.get_usersettings(user=context.get('user', None)) diff --git a/InvenTree/plugin/test_api.py b/InvenTree/plugin/test_api.py index 2f9b2937d1..0af5826970 100644 --- a/InvenTree/plugin/test_api.py +++ b/InvenTree/plugin/test_api.py @@ -5,7 +5,7 @@ from InvenTree.api_tester import InvenTreeAPITestCase class PluginDetailAPITest(InvenTreeAPITestCase): - """Tests the plugin API endpoints""" + """Tests the plugin API endpoints.""" roles = [ 'admin.add', @@ -22,7 +22,7 @@ class PluginDetailAPITest(InvenTreeAPITestCase): super().setUp() def test_plugin_install(self): - """Test the plugin install command""" + """Test the plugin install command.""" url = reverse('api-plugin-install') # valid - Pypi @@ -69,7 +69,7 @@ class PluginDetailAPITest(InvenTreeAPITestCase): self.assertEqual(data['confirm'][0].title().upper(), 'Installation not confirmed'.upper()) def test_admin_action(self): - """Test the PluginConfig action commands""" + """Test the PluginConfig action commands.""" from plugin import registry from plugin.models import PluginConfig @@ -126,7 +126,7 @@ class PluginDetailAPITest(InvenTreeAPITestCase): self.assertEqual(response.status_code, 200) def test_model(self): - """Test the PluginConfig model""" + """Test the PluginConfig model.""" from plugin import registry from plugin.models import PluginConfig diff --git a/InvenTree/plugin/test_helpers.py b/InvenTree/plugin/test_helpers.py index 1b9cd104cc..53b2622592 100644 --- a/InvenTree/plugin/test_helpers.py +++ b/InvenTree/plugin/test_helpers.py @@ -1,4 +1,4 @@ -"""Unit tests for helpers.py""" +"""Unit tests for helpers.py.""" from django.test import TestCase @@ -6,10 +6,10 @@ from .helpers import render_template class HelperTests(TestCase): - """Tests for helpers""" + """Tests for helpers.""" def test_render_template(self): - """Check if render_template helper works""" + """Check if render_template helper works.""" class ErrorSource: slug = 'sampleplg' diff --git a/InvenTree/plugin/test_plugin.py b/InvenTree/plugin/test_plugin.py index 85163184be..f80f72d832 100644 --- a/InvenTree/plugin/test_plugin.py +++ b/InvenTree/plugin/test_plugin.py @@ -1,4 +1,4 @@ -"""Unit tests for plugins""" +"""Unit tests for plugins.""" from datetime import datetime @@ -12,7 +12,7 @@ from plugin.samples.integration.sample import SampleIntegrationPlugin class PluginTagTests(TestCase): - """Tests for the plugin extras""" + """Tests for the plugin extras.""" def setUp(self): self.sample = SampleIntegrationPlugin() @@ -20,22 +20,22 @@ class PluginTagTests(TestCase): self.plugin_wrong = WrongIntegrationPlugin() def test_tag_plugin_list(self): - """Test that all plugins are listed""" + """Test that all plugins are listed.""" self.assertEqual(plugin_tags.plugin_list(), registry.plugins) def test_tag_incative_plugin_list(self): - """Test that all inactive plugins are listed""" + """Test that all inactive plugins are listed.""" self.assertEqual(plugin_tags.inactive_plugin_list(), registry.plugins_inactive) def test_tag_plugin_settings(self): - """Check all plugins are listed""" + """Check all plugins are listed.""" self.assertEqual( plugin_tags.plugin_settings(self.sample), registry.mixins_settings.get(self.sample) ) def test_tag_mixin_enabled(self): - """Check that mixin enabled functions work""" + """Check that mixin enabled functions work.""" key = 'urls' # mixin enabled self.assertEqual(plugin_tags.mixin_enabled(self.sample, key), True) @@ -45,25 +45,25 @@ class PluginTagTests(TestCase): self.assertEqual(plugin_tags.mixin_enabled(self.plugin_no, key), False) def test_tag_safe_url(self): - """Test that the safe url tag works expected""" + """Test that the safe url tag works expected.""" # right url self.assertEqual(plugin_tags.safe_url('api-plugin-install'), '/api/plugin/install/') # wrong url self.assertEqual(plugin_tags.safe_url('indexas'), None) def test_tag_plugin_errors(self): - """Test that all errors are listed""" + """Test that all errors are listed.""" self.assertEqual(plugin_tags.plugin_errors(), registry.errors) class InvenTreePluginTests(TestCase): - """Tests for InvenTreePlugin""" + """Tests for InvenTreePlugin.""" def setUp(self): self.plugin = InvenTreePlugin() class NamedPlugin(InvenTreePlugin): - """a named plugin""" + """a named plugin.""" NAME = 'abc123' self.named_plugin = NamedPlugin() @@ -93,21 +93,21 @@ class InvenTreePluginTests(TestCase): self.plugin_sample = SampleIntegrationPlugin() def test_basic_plugin_init(self): - """Check if a basic plugin intis""" + """Check if a basic plugin intis.""" self.assertEqual(self.plugin.NAME, '') self.assertEqual(self.plugin.plugin_name(), '') def test_basic_plugin_name(self): - """Check if the name of a basic plugin can be set""" + """Check if the name of a basic plugin can be set.""" self.assertEqual(self.named_plugin.NAME, 'abc123') self.assertEqual(self.named_plugin.plugin_name(), 'abc123') def test_basic_is_active(self): - """Check if a basic plugin is active""" + """Check if a basic plugin is active.""" self.assertEqual(self.plugin.is_active(), False) def test_action_name(self): - """Check the name definition possibilities""" + """Check the name definition possibilities.""" # plugin_name self.assertEqual(self.plugin.plugin_name(), '') self.assertEqual(self.plugin_simple.plugin_name(), 'SimplePlugin') @@ -154,7 +154,7 @@ class InvenTreePluginTests(TestCase): self.assertEqual(self.plugin_name.license, 'MIT') def test_depreciation(self): - """Check if depreciations raise as expected""" + """Check if depreciations raise as expected.""" # check deprecation warning is firing with self.assertWarns(DeprecationWarning): self.assertEqual(self.plugin_old.slug, 'old') diff --git a/InvenTree/plugin/urls.py b/InvenTree/plugin/urls.py index 71481014fb..6da54a83ee 100644 --- a/InvenTree/plugin/urls.py +++ b/InvenTree/plugin/urls.py @@ -1,4 +1,4 @@ -"""URL lookup for plugin app""" +"""URL lookup for plugin app.""" from django.urls import include, re_path @@ -8,7 +8,7 @@ PLUGIN_BASE = 'plugin' # Constant for links def get_plugin_urls(): - """Returns a urlpattern that can be integrated into the global urls""" + """Returns a urlpattern that can be integrated into the global urls.""" urls = [] for plugin in registry.plugins.values(): diff --git a/InvenTree/plugin/views.py b/InvenTree/plugin/views.py index 50e06fc4f6..1be07a6acf 100644 --- a/InvenTree/plugin/views.py +++ b/InvenTree/plugin/views.py @@ -19,7 +19,7 @@ class InvenTreePluginViewMixin: """ def get_plugin_panels(self, ctx): - """Return a list of extra 'plugin panels' associated with this view""" + """Return a list of extra 'plugin panels' associated with this view.""" panels = [] for plug in registry.with_mixin('panel', active=True): @@ -44,7 +44,7 @@ class InvenTreePluginViewMixin: return panels def get_context_data(self, **kwargs): - """Add plugin context data to the view""" + """Add plugin context data to the view.""" ctx = super().get_context_data(**kwargs) if settings.PLUGINS_ENABLED: diff --git a/InvenTree/plugins/__init__.py b/InvenTree/plugins/__init__.py index 926e30e23c..a77bf4fe18 100644 --- a/InvenTree/plugins/__init__.py +++ b/InvenTree/plugins/__init__.py @@ -1,5 +1,5 @@ """ -Directory for custom plugin development +Directory for custom plugin development. Please read the docs for more information https://inventree.readthedocs.io/en/latest/extend/plugins/#local-directory """ diff --git a/InvenTree/report/api.py b/InvenTree/report/api.py index 9e3a5118b7..cba5330f8b 100644 --- a/InvenTree/report/api.py +++ b/InvenTree/report/api.py @@ -24,7 +24,7 @@ from .serializers import (BOMReportSerializer, BuildReportSerializer, class ReportListView(generics.ListAPIView): - """Generic API class for report templates""" + """Generic API class for report templates.""" filter_backends = [ DjangoFilterBackend, @@ -42,10 +42,10 @@ class ReportListView(generics.ListAPIView): class StockItemReportMixin: - """Mixin for extracting stock items from query params""" + """Mixin for extracting stock items from query params.""" def get_items(self): - """Return a list of requested stock items""" + """Return a list of requested stock items.""" items = [] params = self.request.query_params @@ -70,10 +70,10 @@ class StockItemReportMixin: class BuildReportMixin: - """Mixin for extracting Build items from query params""" + """Mixin for extracting Build items from query params.""" def get_builds(self): - """Return a list of requested Build objects""" + """Return a list of requested Build objects.""" builds = [] params = self.request.query_params @@ -97,13 +97,13 @@ class BuildReportMixin: class OrderReportMixin: - """Mixin for extracting order items from query params + """Mixin for extracting order items from query params. requires the OrderModel class attribute to be set! """ def get_orders(self): - """Return a list of order objects""" + """Return a list of order objects.""" orders = [] params = self.request.query_params @@ -127,10 +127,10 @@ class OrderReportMixin: class PartReportMixin: - """Mixin for extracting part items from query params""" + """Mixin for extracting part items from query params.""" def get_parts(self): - """Return a list of requested part objects""" + """Return a list of requested part objects.""" parts = [] params = self.request.query_params @@ -155,7 +155,7 @@ class PartReportMixin: class ReportPrintMixin: - """Mixin for printing reports""" + """Mixin for printing reports.""" def print(self, request, items_to_print): """Print this report template against a number of pre-validated items.""" @@ -203,19 +203,13 @@ class ReportPrintMixin: report_name += '.pdf' if debug_mode: - """ - Contatenate all rendered templates into a single HTML string, - and return the string as a HTML response. - """ + """Contatenate all rendered templates into a single HTML string, and return the string as a HTML response.""" html = "\n".join(outputs) return HttpResponse(html) else: - """ - Concatenate all rendered pages into a single PDF object, - and return the resulting document! - """ + """Concatenate all rendered pages into a single PDF object, and return the resulting document!""" pages = [] @@ -263,7 +257,6 @@ class StockItemTestReportList(ReportListView, StockItemReportMixin): - enabled: Filter by enabled / disabled status - item: Filter by stock item(s) - """ queryset = TestReport.objects.all() @@ -320,14 +313,14 @@ class StockItemTestReportList(ReportListView, StockItemReportMixin): class StockItemTestReportDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for a single TestReport object""" + """API endpoint for a single TestReport object.""" queryset = TestReport.objects.all() serializer_class = TestReportSerializer class StockItemTestReportPrint(generics.RetrieveAPIView, StockItemReportMixin, ReportPrintMixin): - """API endpoint for printing a TestReport object""" + """API endpoint for printing a TestReport object.""" queryset = TestReport.objects.all() serializer_class = TestReportSerializer @@ -401,20 +394,20 @@ class BOMReportList(ReportListView, PartReportMixin): class BOMReportDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for a single BillOfMaterialReport object""" + """API endpoint for a single BillOfMaterialReport object.""" queryset = BillOfMaterialsReport.objects.all() serializer_class = BOMReportSerializer class BOMReportPrint(generics.RetrieveAPIView, PartReportMixin, ReportPrintMixin): - """API endpoint for printing a BillOfMaterialReport object""" + """API endpoint for printing a BillOfMaterialReport object.""" queryset = BillOfMaterialsReport.objects.all() serializer_class = BOMReportSerializer def get(self, request, *args, **kwargs): - """Check if valid part item(s) have been provided""" + """Check if valid part item(s) have been provided.""" parts = self.get_parts() return self.print(request, parts) @@ -483,14 +476,14 @@ class BuildReportList(ReportListView, BuildReportMixin): class BuildReportDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for a single BuildReport object""" + """API endpoint for a single BuildReport object.""" queryset = BuildReport.objects.all() serializer_class = BuildReportSerializer class BuildReportPrint(generics.RetrieveAPIView, BuildReportMixin, ReportPrintMixin): - """API endpoint for printing a BuildReport""" + """API endpoint for printing a BuildReport.""" queryset = BuildReport.objects.all() serializer_class = BuildReportSerializer @@ -517,7 +510,7 @@ class PurchaseOrderReportList(ReportListView, OrderReportMixin): if len(orders) > 0: """ - We wish to filter by purchase orders + We wish to filter by purchase orders. We need to compare the 'filters' string of each report, and see if it matches against each of the specified orders. @@ -560,14 +553,14 @@ class PurchaseOrderReportList(ReportListView, OrderReportMixin): class PurchaseOrderReportDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for a single PurchaseOrderReport object""" + """API endpoint for a single PurchaseOrderReport object.""" queryset = PurchaseOrderReport.objects.all() serializer_class = PurchaseOrderReportSerializer class PurchaseOrderReportPrint(generics.RetrieveAPIView, OrderReportMixin, ReportPrintMixin): - """API endpoint for printing a PurchaseOrderReport object""" + """API endpoint for printing a PurchaseOrderReport object.""" OrderModel = order.models.PurchaseOrder @@ -596,7 +589,7 @@ class SalesOrderReportList(ReportListView, OrderReportMixin): if len(orders) > 0: """ - We wish to filter by purchase orders + We wish to filter by purchase orders. We need to compare the 'filters' string of each report, and see if it matches against each of the specified orders. @@ -639,14 +632,14 @@ class SalesOrderReportList(ReportListView, OrderReportMixin): class SalesOrderReportDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for a single SalesOrderReport object""" + """API endpoint for a single SalesOrderReport object.""" queryset = SalesOrderReport.objects.all() serializer_class = SalesOrderReportSerializer class SalesOrderReportPrint(generics.RetrieveAPIView, OrderReportMixin, ReportPrintMixin): - """API endpoint for printing a PurchaseOrderReport object""" + """API endpoint for printing a PurchaseOrderReport object.""" OrderModel = order.models.SalesOrder diff --git a/InvenTree/report/apps.py b/InvenTree/report/apps.py index 2c93ba5496..548bbd35bc 100644 --- a/InvenTree/report/apps.py +++ b/InvenTree/report/apps.py @@ -14,7 +14,7 @@ class ReportConfig(AppConfig): name = 'report' def ready(self): - """This function is called whenever the report app is loaded""" + """This function is called whenever the report app is loaded.""" if canAppAccessDatabase(allow_test=True): self.create_default_test_reports() self.create_default_build_reports() @@ -76,7 +76,7 @@ class ReportConfig(AppConfig): pass def create_default_test_reports(self): - """Create database entries for the default TestReport templates, if they do not already exist""" + """Create database entries for the default TestReport templates, if they do not already exist.""" try: from .models import TestReport except: # pragma: no cover diff --git a/InvenTree/report/models.py b/InvenTree/report/models.py index 86c172727d..eaa8c762d2 100644 --- a/InvenTree/report/models.py +++ b/InvenTree/report/models.py @@ -1,4 +1,4 @@ -"""Report template model definitions""" +"""Report template model definitions.""" import datetime import logging @@ -43,27 +43,27 @@ def rename_template(instance, filename): def validate_stock_item_report_filters(filters): - """Validate filter string against StockItem model""" + """Validate filter string against StockItem model.""" return validateFilterString(filters, model=stock.models.StockItem) def validate_part_report_filters(filters): - """Validate filter string against Part model""" + """Validate filter string against Part model.""" return validateFilterString(filters, model=part.models.Part) def validate_build_report_filters(filters): - """Validate filter string against Build model""" + """Validate filter string against Build model.""" return validateFilterString(filters, model=build.models.Build) def validate_purchase_order_filters(filters): - """Validate filter string against PurchaseOrder model""" + """Validate filter string against PurchaseOrder model.""" return validateFilterString(filters, model=order.models.PurchaseOrder) def validate_sales_order_filters(filters): - """Validate filter string against SalesOrder model""" + """Validate filter string against SalesOrder model.""" return validateFilterString(filters, model=order.models.SalesOrder) @@ -81,7 +81,7 @@ class WeasyprintReportMixin(WeasyTemplateResponseMixin): class ReportBase(models.Model): - """Base class for uploading html templates""" + """Base class for uploading html templates.""" class Meta: abstract = True @@ -178,7 +178,7 @@ class ReportTemplateBase(ReportBase): object_to_print = None def get_context_data(self, request): - """Supply context data to the template for rendering""" + """Supply context data to the template for rendering.""" return {} def context(self, request): @@ -199,7 +199,7 @@ class ReportTemplateBase(ReportBase): return context def generate_filename(self, request, **kwargs): - """Generate a filename for this report""" + """Generate a filename for this report.""" template_string = Template(self.filename_pattern) ctx = self.context(request) @@ -281,7 +281,7 @@ class TestReport(ReportTemplateBase): ) def matches_stock_item(self, item): - """Test if this report template matches a given StockItem objects""" + """Test if this report template matches a given StockItem objects.""" try: filters = validateFilterString(self.filters) items = stock.models.StockItem.objects.filter(**filters) @@ -309,7 +309,7 @@ class TestReport(ReportTemplateBase): class BuildReport(ReportTemplateBase): - """Build order / work order report""" + """Build order / work order report.""" @staticmethod def get_api_url(): @@ -330,7 +330,7 @@ class BuildReport(ReportTemplateBase): ) def get_context_data(self, request): - """Custom context data for the build report""" + """Custom context data for the build report.""" my_build = self.object_to_print if type(my_build) != build.models.Build: @@ -347,7 +347,7 @@ class BuildReport(ReportTemplateBase): class BillOfMaterialsReport(ReportTemplateBase): - """Render a Bill of Materials against a Part object""" + """Render a Bill of Materials against a Part object.""" @staticmethod def get_api_url(): @@ -379,7 +379,7 @@ class BillOfMaterialsReport(ReportTemplateBase): class PurchaseOrderReport(ReportTemplateBase): - """Render a report against a PurchaseOrder object""" + """Render a report against a PurchaseOrder object.""" @staticmethod def get_api_url(): @@ -416,7 +416,7 @@ class PurchaseOrderReport(ReportTemplateBase): class SalesOrderReport(ReportTemplateBase): - """Render a report against a SalesOrder object""" + """Render a report against a SalesOrder object.""" @staticmethod def get_api_url(): diff --git a/InvenTree/report/templatetags/barcode.py b/InvenTree/report/templatetags/barcode.py index 1abf0b1eea..0f1d885201 100644 --- a/InvenTree/report/templatetags/barcode.py +++ b/InvenTree/report/templatetags/barcode.py @@ -1,4 +1,4 @@ -"""Template tags for rendering various barcodes""" +"""Template tags for rendering various barcodes.""" import base64 from io import BytesIO @@ -12,7 +12,7 @@ register = template.Library() def image_data(img, fmt='PNG'): - """Convert an image into HTML renderable data + """Convert an image into HTML renderable data. Returns a string ``data:image/FMT;base64,xxxxxxxxx`` which can be rendered to an tag """ @@ -26,7 +26,7 @@ def image_data(img, fmt='PNG'): @register.simple_tag() def qrcode(data, **kwargs): - """Return a byte-encoded QR code image + """Return a byte-encoded QR code image. Optional kwargs --------------- @@ -57,7 +57,7 @@ def qrcode(data, **kwargs): @register.simple_tag() def barcode(data, barcode_class='code128', **kwargs): - """Render a barcode""" + """Render a barcode.""" constructor = python_barcode.get_barcode_class(barcode_class) data = str(data).zfill(constructor.digits) diff --git a/InvenTree/report/templatetags/report.py b/InvenTree/report/templatetags/report.py index 7d6be7d836..9e82202196 100644 --- a/InvenTree/report/templatetags/report.py +++ b/InvenTree/report/templatetags/report.py @@ -1,4 +1,4 @@ -"""Custom template tags for report generation""" +"""Custom template tags for report generation.""" import os @@ -33,7 +33,7 @@ def asset(filename): @register.simple_tag() def part_image(part): - """Return a fully-qualified path for a part image""" + """Return a fully-qualified path for a part image.""" # If in debug mode, return URL to the image, not a local file debug_mode = InvenTreeSetting.get_setting('REPORT_DEBUG_MODE') @@ -67,7 +67,7 @@ def part_image(part): @register.simple_tag() def company_image(company): - """Return a fully-qualified path for a company image""" + """Return a fully-qualified path for a company image.""" # If in debug mode, return the URL to the image, not a local file debug_mode = InvenTreeSetting.get_setting('REPORT_DEBUG_MODE') diff --git a/InvenTree/report/tests.py b/InvenTree/report/tests.py index 9d5508b249..5126c44d9e 100644 --- a/InvenTree/report/tests.py +++ b/InvenTree/report/tests.py @@ -36,7 +36,7 @@ class ReportTest(InvenTreeAPITestCase): super().setUp() def copyReportTemplate(self, filename, description): - """Copy the provided report template into the required media directory""" + """Copy the provided report template into the required media directory.""" src_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'templates', @@ -78,7 +78,7 @@ class ReportTest(InvenTreeAPITestCase): ) def test_list_endpoint(self): - """Test that the LIST endpoint works for each report""" + """Test that the LIST endpoint works for each report.""" if not self.list_url: return @@ -129,7 +129,7 @@ class TestReportTest(ReportTest): return super().setUp() def test_print(self): - """Printing tests for the TestReport""" + """Printing tests for the TestReport.""" report = self.model.objects.first() url = reverse(self.print_url, kwargs={'pk': report.pk}) @@ -168,7 +168,7 @@ class BuildReportTest(ReportTest): return super().setUp() def test_print(self): - """Printing tests for the BuildReport""" + """Printing tests for the BuildReport.""" report = self.model.objects.first() url = reverse(self.print_url, kwargs={'pk': report.pk}) diff --git a/InvenTree/script/translation_stats.py b/InvenTree/script/translation_stats.py index 85740053f8..e46d682fae 100644 --- a/InvenTree/script/translation_stats.py +++ b/InvenTree/script/translation_stats.py @@ -1,4 +1,4 @@ -"""This script calculates translation coverage for various languages""" +"""This script calculates translation coverage for various languages.""" import json import os @@ -6,7 +6,7 @@ import sys def calculate_coverage(filename): - """Calculate translation coverage for a .po file""" + """Calculate translation coverage for a .po file.""" with open(filename, 'r') as f: lines = f.readlines() diff --git a/InvenTree/stock/admin.py b/InvenTree/stock/admin.py index 85561c9786..b6825ce71d 100644 --- a/InvenTree/stock/admin.py +++ b/InvenTree/stock/admin.py @@ -15,7 +15,7 @@ from .models import (StockItem, StockItemAttachment, StockItemTestResult, class LocationResource(ModelResource): - """Class for managing StockLocation data import/export""" + """Class for managing StockLocation data import/export.""" parent = Field(attribute='parent', widget=widgets.ForeignKeyWidget(StockLocation)) @@ -42,7 +42,7 @@ class LocationResource(ModelResource): class LocationInline(admin.TabularInline): - """Inline for sub-locations""" + """Inline for sub-locations.""" model = StockLocation @@ -64,7 +64,7 @@ class LocationAdmin(ImportExportModelAdmin): class StockItemResource(ModelResource): - """Class for managing StockItem data import/export""" + """Class for managing StockItem data import/export.""" # Custom managers for ForeignKey fields part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part)) diff --git a/InvenTree/stock/api.py b/InvenTree/stock/api.py index a03de387ce..1b2bc70fe2 100644 --- a/InvenTree/stock/api.py +++ b/InvenTree/stock/api.py @@ -1,4 +1,4 @@ -"""JSON API for the Stock app""" +"""JSON API for the Stock app.""" from collections import OrderedDict from datetime import datetime, timedelta @@ -37,7 +37,7 @@ from stock.models import (StockItem, StockItemAttachment, StockItemTestResult, class StockDetail(generics.RetrieveUpdateDestroyAPIView): - """API detail endpoint for Stock object + """API detail endpoint for Stock object. get: Return a single StockItem object @@ -78,7 +78,7 @@ class StockDetail(generics.RetrieveUpdateDestroyAPIView): class StockMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating StockItem metadata""" + """API endpoint for viewing / updating StockItem metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(StockItem, *args, **kwargs) @@ -87,7 +87,7 @@ class StockMetadata(generics.RetrieveUpdateAPIView): class StockItemContextMixin: - """Mixin class for adding StockItem object to serializer context""" + """Mixin class for adding StockItem object to serializer context.""" def get_serializer_context(self): @@ -103,7 +103,7 @@ class StockItemContextMixin: class StockItemSerialize(StockItemContextMixin, generics.CreateAPIView): - """API endpoint for serializing a stock item""" + """API endpoint for serializing a stock item.""" queryset = StockItem.objects.none() serializer_class = StockSerializers.SerializeStockItemSerializer @@ -122,7 +122,7 @@ class StockItemInstall(StockItemContextMixin, generics.CreateAPIView): class StockItemUninstall(StockItemContextMixin, generics.CreateAPIView): - """API endpoint for removing (uninstalling) items from this item""" + """API endpoint for removing (uninstalling) items from this item.""" queryset = StockItem.objects.none() serializer_class = StockSerializers.UninstallStockItemSerializer @@ -157,7 +157,7 @@ class StockCount(StockAdjustView): class StockAdd(StockAdjustView): - """Endpoint for adding a quantity of stock to an existing StockItem""" + """Endpoint for adding a quantity of stock to an existing StockItem.""" serializer_class = StockSerializers.StockAddSerializer @@ -169,13 +169,13 @@ class StockRemove(StockAdjustView): class StockTransfer(StockAdjustView): - """API endpoint for performing stock movements""" + """API endpoint for performing stock movements.""" serializer_class = StockSerializers.StockTransferSerializer class StockAssign(generics.CreateAPIView): - """API endpoint for assigning stock to a particular customer""" + """API endpoint for assigning stock to a particular customer.""" queryset = StockItem.objects.all() serializer_class = StockSerializers.StockAssignmentSerializer @@ -190,7 +190,7 @@ class StockAssign(generics.CreateAPIView): class StockMerge(generics.CreateAPIView): - """API endpoint for merging multiple stock items""" + """API endpoint for merging multiple stock items.""" queryset = StockItem.objects.none() serializer_class = StockSerializers.StockMergeSerializer @@ -294,7 +294,7 @@ class StockLocationList(generics.ListCreateAPIView): class StockLocationTree(generics.ListAPIView): - """API endpoint for accessing a list of StockLocation objects, ready for rendering as a tree""" + """API endpoint for accessing a list of StockLocation objects, ready for rendering as a tree.""" queryset = StockLocation.objects.all() serializer_class = StockSerializers.LocationTreeSerializer @@ -309,7 +309,7 @@ class StockLocationTree(generics.ListAPIView): class StockFilter(rest_filters.FilterSet): - """FilterSet for StockItem LIST API""" + """FilterSet for StockItem LIST API.""" # Part name filters name = rest_filters.CharFilter(label='Part name (case insensitive)', field_name='part__name', lookup_expr='iexact') @@ -414,7 +414,7 @@ class StockFilter(rest_filters.FilterSet): installed = rest_filters.BooleanFilter(label='Installed in other stock item', method='filter_installed') def filter_installed(self, queryset, name, value): - """Filter stock items by "belongs_to" field being empty""" + """Filter stock items by "belongs_to" field being empty.""" if str2bool(value): queryset = queryset.exclude(belongs_to=None) else: @@ -461,7 +461,7 @@ class StockFilter(rest_filters.FilterSet): class StockList(APIDownloadMixin, generics.ListCreateAPIView): - """API endpoint for list view of Stock objects + """API endpoint for list view of Stock objects. - GET: Return a list of all StockItem objects (with optional query filters) - POST: Create a new StockItem @@ -559,9 +559,7 @@ class StockList(APIDownloadMixin, generics.ListCreateAPIView): }) if serials is not None: - """ - If the stock item is going to be serialized, set the quantity to 1 - """ + """If the stock item is going to be serialized, set the quantity to 1.""" data['quantity'] = 1 # De-serialize the provided data @@ -729,7 +727,7 @@ class StockList(APIDownloadMixin, generics.ListCreateAPIView): return queryset def filter_queryset(self, queryset): - """Custom filtering for the StockItem queryset""" + """Custom filtering for the StockItem queryset.""" params = self.request.query_params queryset = super().filter_queryset(queryset) @@ -1058,14 +1056,14 @@ class StockAttachmentList(generics.ListCreateAPIView, AttachmentMixin): class StockAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin): - """Detail endpoint for StockItemAttachment""" + """Detail endpoint for StockItemAttachment.""" queryset = StockItemAttachment.objects.all() serializer_class = StockSerializers.StockItemAttachmentSerializer class StockItemTestResultDetail(generics.RetrieveUpdateDestroyAPIView): - """Detail endpoint for StockItemTestResult""" + """Detail endpoint for StockItemTestResult.""" queryset = StockItemTestResult.objects.all() serializer_class = StockSerializers.StockItemTestResultSerializer @@ -1160,7 +1158,7 @@ class StockItemTestResultList(generics.ListCreateAPIView): class StockTrackingDetail(generics.RetrieveAPIView): - """Detail API endpoint for StockItemTracking model""" + """Detail API endpoint for StockItemTracking model.""" queryset = StockItemTracking.objects.all() serializer_class = StockSerializers.StockTrackingSerializer @@ -1259,7 +1257,7 @@ class StockTrackingList(generics.ListAPIView): return Response(data) def create(self, request, *args, **kwargs): - """Create a new StockItemTracking object + """Create a new StockItemTracking object. Here we override the default 'create' implementation, to save the user information associated with the request object. @@ -1303,7 +1301,7 @@ class StockTrackingList(generics.ListAPIView): class LocationMetadata(generics.RetrieveUpdateAPIView): - """API endpoint for viewing / updating StockLocation metadata""" + """API endpoint for viewing / updating StockLocation metadata.""" def get_serializer(self, *args, **kwargs): return MetadataSerializer(StockLocation, *args, **kwargs) @@ -1312,7 +1310,7 @@ class LocationMetadata(generics.RetrieveUpdateAPIView): class LocationDetail(generics.RetrieveUpdateDestroyAPIView): - """API endpoint for detail view of StockLocation object + """API endpoint for detail view of StockLocation object. - GET: Return a single StockLocation object - PATCH: Update a StockLocation object diff --git a/InvenTree/stock/forms.py b/InvenTree/stock/forms.py index 847cd875a5..6232930f3b 100644 --- a/InvenTree/stock/forms.py +++ b/InvenTree/stock/forms.py @@ -1,4 +1,4 @@ -"""Django Forms for interacting with Stock app""" +"""Django Forms for interacting with Stock app.""" from InvenTree.forms import HelperForm @@ -6,7 +6,7 @@ from .models import StockItem, StockItemTracking class ReturnStockItemForm(HelperForm): - """Form for manually returning a StockItem into stock + """Form for manually returning a StockItem into stock. TODO: This could be a simple API driven form! """ diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py index f0581e9651..23ccbe7f6b 100644 --- a/InvenTree/stock/models.py +++ b/InvenTree/stock/models.py @@ -1,4 +1,4 @@ -"""Stock database model definitions""" +"""Stock database model definitions.""" import os from datetime import datetime, timedelta @@ -117,7 +117,7 @@ class StockLocation(MetadataMixin, InvenTreeTree): return reverse('stock-location-detail', kwargs={'pk': self.id}) def format_barcode(self, **kwargs): - """Return a JSON string for formatting a barcode for this StockLocation object""" + """Return a JSON string for formatting a barcode for this StockLocation object.""" return InvenTree.helpers.MakeBarcode( 'stocklocation', self.pk, @@ -147,7 +147,7 @@ class StockLocation(MetadataMixin, InvenTreeTree): return query def stock_item_count(self, cascade=True): - """Return the number of StockItem objects which live in or under this category""" + """Return the number of StockItem objects which live in or under this category.""" return self.get_stock_items(cascade).count() def has_items(self, cascade=True): @@ -250,7 +250,7 @@ class StockItem(MetadataMixin, MPTTModel): return reverse('api-stock-list') def api_instance_filters(self): - """Custom API instance filters""" + """Custom API instance filters.""" return { 'parent': { 'exclude_tree': self.pk, @@ -408,7 +408,7 @@ class StockItem(MetadataMixin, MPTTModel): @property def serialized(self): - """Return True if this StockItem is serialized""" + """Return True if this StockItem is serialized.""" return self.serial is not None and len(str(self.serial).strip()) > 0 and self.quantity == 1 def validate_unique(self, exclude=None): @@ -538,11 +538,10 @@ class StockItem(MetadataMixin, MPTTModel): def format_barcode(self, **kwargs): """Return a JSON string for formatting a barcode for this StockItem. - Can be used to perform lookup of a stockitem using barcode + Can be used to perform lookup of a stockitem using barcode. Contains the following data: - - { type: 'StockItem', stock_id: , part_id: } + `{ type: 'StockItem', stock_id: , part_id: }` Voltagile data (e.g. stock quantity) should be looked up using the InvenTree API (as it may change) """ @@ -724,7 +723,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def convert_to_variant(self, variant, user, notes=None): - """Convert this StockItem instance to a "variant", i.e. change the "part" reference field""" + """Convert this StockItem instance to a "variant", i.e. change the "part" reference field.""" if not variant: # Ignore null values return @@ -764,7 +763,7 @@ class StockItem(MetadataMixin, MPTTModel): return None def check_ownership(self, user): - """Check if the user "owns" (or is one of the owners of) the item""" + """Check if the user "owns" (or is one of the owners of) the item.""" # Superuser accounts automatically "own" everything if user.is_superuser: return True @@ -786,7 +785,6 @@ class StockItem(MetadataMixin, MPTTModel): """Returns True if this Stock item is "stale". To be "stale", the following conditions must be met: - - Expiry date is not None - Expiry date will "expire" within the configured stale date - The StockItem is otherwise "in stock" @@ -812,7 +810,6 @@ class StockItem(MetadataMixin, MPTTModel): """Returns True if this StockItem is "expired". To be "expired", the following conditions must be met: - - Expiry date is not None - Expiry date is "in the past" - The StockItem is otherwise "in stock" @@ -923,7 +920,7 @@ class StockItem(MetadataMixin, MPTTModel): infinite = models.BooleanField(default=False) def is_allocated(self): - """Return True if this StockItem is allocated to a SalesOrder or a Build""" + """Return True if this StockItem is allocated to a SalesOrder or a Build.""" # TODO - For now this only checks if the StockItem is allocated to a SalesOrder # TODO - In future, once the "build" is working better, check this too @@ -936,7 +933,7 @@ class StockItem(MetadataMixin, MPTTModel): return False def build_allocation_count(self): - """Return the total quantity allocated to builds""" + """Return the total quantity allocated to builds.""" query = self.allocations.aggregate(q=Coalesce(Sum('quantity'), Decimal(0))) total = query['q'] @@ -947,7 +944,7 @@ class StockItem(MetadataMixin, MPTTModel): return total def sales_order_allocation_count(self): - """Return the total quantity allocated to SalesOrders""" + """Return the total quantity allocated to SalesOrders.""" query = self.sales_order_allocations.aggregate(q=Coalesce(Sum('quantity'), Decimal(0))) total = query['q'] @@ -958,14 +955,14 @@ class StockItem(MetadataMixin, MPTTModel): return total def allocation_count(self): - """Return the total quantity allocated to builds or orders""" + """Return the total quantity allocated to builds or orders.""" bo = self.build_allocation_count() so = self.sales_order_allocation_count() return bo + so def unallocated_quantity(self): - """Return the quantity of this StockItem which is *not* allocated""" + """Return the quantity of this StockItem which is *not* allocated.""" return max(self.quantity - self.allocation_count(), 0) def can_delete(self): @@ -1110,7 +1107,7 @@ class StockItem(MetadataMixin, MPTTModel): @property def children(self): - """Return a list of the child items which have been split from this stock item""" + """Return a list of the child items which have been split from this stock item.""" return self.get_descendants(include_self=False) @property @@ -1135,7 +1132,7 @@ class StockItem(MetadataMixin, MPTTModel): @property def can_adjust_location(self): - """Returns True if the stock location can be "adjusted" for this part + """Returns True if the stock location can be "adjusted" for this part. Cannot be adjusted if: - Has been delivered to a customer @@ -1161,7 +1158,7 @@ class StockItem(MetadataMixin, MPTTModel): return self.tracking_info_count > 0 def add_tracking_entry(self, entry_type, user, deltas=None, notes='', **kwargs): - """Add a history tracking entry for this StockItem + """Add a history tracking entry for this StockItem. Args: entry_type - Integer code describing the "type" of historical action (see StockHistoryCode) @@ -1281,7 +1278,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def copyHistoryFrom(self, other): - """Copy stock history from another StockItem""" + """Copy stock history from another StockItem.""" for item in other.tracking_info.all(): item.item = self @@ -1290,7 +1287,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def copyTestResultsFrom(self, other, filters={}): - """Copy all test results from another StockItem""" + """Copy all test results from another StockItem.""" for result in other.test_results.all().filter(**filters): # Create a copy of the test result by nulling-out the pk @@ -1299,7 +1296,7 @@ class StockItem(MetadataMixin, MPTTModel): result.save() def can_merge(self, other=None, raise_error=False, **kwargs): - """Check if this stock item can be merged into another stock item""" + """Check if this stock item can be merged into another stock item.""" allow_mismatched_suppliers = kwargs.get('allow_mismatched_suppliers', False) allow_mismatched_status = kwargs.get('allow_mismatched_status', False) @@ -1612,7 +1609,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def add_stock(self, quantity, user, notes=''): - """Add items to stock + """Add items to stock. This function can be called by initiating a ProjectRun, or by manually adding the items to the stock location @@ -1646,7 +1643,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def take_stock(self, quantity, user, notes='', code=StockHistoryCode.STOCK_REMOVE): - """Remove items from stock""" + """Remove items from stock.""" # Cannot remove items from a serialized part if self.serialized: return False @@ -1696,7 +1693,7 @@ class StockItem(MetadataMixin, MPTTModel): @transaction.atomic def clear_test_results(self, **kwargs): - """Remove all test results""" + """Remove all test results.""" # All test results results = self.test_results.all() @@ -1767,7 +1764,7 @@ class StockItem(MetadataMixin, MPTTModel): return result_map def testResultList(self, **kwargs): - """Return a list of test-result objects for this StockItem""" + """Return a list of test-result objects for this StockItem.""" return self.testResultMap(**kwargs).values() def requiredTestStatus(self): @@ -1807,15 +1804,15 @@ class StockItem(MetadataMixin, MPTTModel): @property def required_test_count(self): - """Return the number of 'required tests' for this StockItem""" + """Return the number of 'required tests' for this StockItem.""" return self.part.getRequiredTests().count() def hasRequiredTests(self): - """Return True if there are any 'required tests' associated with this StockItem""" + """Return True if there are any 'required tests' associated with this StockItem.""" return self.part.getRequiredTests().count() > 0 def passedAllRequiredTests(self): - """Returns True if this StockItem has passed all required tests""" + """Returns True if this StockItem has passed all required tests.""" status = self.requiredTestStatus() return status['passed'] >= status['total'] @@ -1840,11 +1837,11 @@ class StockItem(MetadataMixin, MPTTModel): @property def has_test_reports(self): - """Return True if there are test reports available for this stock item""" + """Return True if there are test reports available for this stock item.""" return len(self.available_test_reports()) > 0 def available_labels(self): - """Return a list of Label objects which match this StockItem""" + """Return a list of Label objects which match this StockItem.""" labels = [] item_query = StockItem.objects.filter(pk=self.pk) @@ -1863,7 +1860,7 @@ class StockItem(MetadataMixin, MPTTModel): @property def has_labels(self): - """Return True if there are any label templates available for this stock item""" + """Return True if there are any label templates available for this stock item.""" return len(self.available_labels()) > 0 @@ -1882,7 +1879,7 @@ def before_delete_stock_item(sender, instance, using, **kwargs): @receiver(post_delete, sender=StockItem, dispatch_uid='stock_item_post_delete_log') def after_delete_stock_item(sender, instance: StockItem, **kwargs): - """Function to be executed after a StockItem object is deleted""" + """Function to be executed after a StockItem object is deleted.""" from part import tasks as part_tasks if not InvenTree.ready.isImportingData(): @@ -1892,7 +1889,7 @@ def after_delete_stock_item(sender, instance: StockItem, **kwargs): @receiver(post_save, sender=StockItem, dispatch_uid='stock_item_post_save_log') def after_save_stock_item(sender, instance: StockItem, created, **kwargs): - """Hook function to be executed after StockItem object is saved/updated""" + """Hook function to be executed after StockItem object is saved/updated.""" from part import tasks as part_tasks if not InvenTree.ready.isImportingData(): diff --git a/InvenTree/stock/serializers.py b/InvenTree/stock/serializers.py index 1f1cf1ed44..7f7d1529a9 100644 --- a/InvenTree/stock/serializers.py +++ b/InvenTree/stock/serializers.py @@ -1,4 +1,4 @@ -"""JSON serializers for Stock app""" +"""JSON serializers for Stock app.""" from datetime import datetime, timedelta from decimal import Decimal @@ -27,7 +27,7 @@ from .models import (StockItem, StockItemAttachment, StockItemTestResult, class LocationBriefSerializer(InvenTree.serializers.InvenTreeModelSerializer): - """Provides a brief serializer for a StockLocation object""" + """Provides a brief serializer for a StockLocation object.""" class Meta: model = StockLocation @@ -39,7 +39,7 @@ class LocationBriefSerializer(InvenTree.serializers.InvenTreeModelSerializer): class StockItemSerializerBrief(InvenTree.serializers.InvenTreeModelSerializer): - """Brief serializers for a StockItem""" + """Brief serializers for a StockItem.""" location_name = serializers.CharField(source='location', read_only=True) part_name = serializers.CharField(source='part.full_name', read_only=True) @@ -74,7 +74,7 @@ class StockItemSerializer(InvenTree.serializers.InvenTreeModelSerializer): """ def update(self, instance, validated_data): - """Custom update method to pass the user information through to the instance""" + """Custom update method to pass the user information through to the instance.""" instance._user = self.context['user'] return super().update(instance, validated_data) @@ -272,7 +272,7 @@ class SerializeStockItemSerializer(serializers.Serializer): ) def validate_quantity(self, quantity): - """Validate that the quantity value is correct""" + """Validate that the quantity value is correct.""" item = self.context['item'] if quantity < 0: @@ -308,7 +308,7 @@ class SerializeStockItemSerializer(serializers.Serializer): ) def validate(self, data): - """Check that the supplied serial numbers are valid""" + """Check that the supplied serial numbers are valid.""" data = super().validate(data) item = self.context['item'] @@ -363,7 +363,7 @@ class SerializeStockItemSerializer(serializers.Serializer): class InstallStockItemSerializer(serializers.Serializer): - """Serializer for installing a stock item into a given part""" + """Serializer for installing a stock item into a given part.""" stock_item = serializers.PrimaryKeyRelatedField( queryset=StockItem.objects.all(), @@ -381,7 +381,7 @@ class InstallStockItemSerializer(serializers.Serializer): ) def validate_stock_item(self, stock_item): - """Validate the selected stock item""" + """Validate the selected stock item.""" if not stock_item.in_stock: # StockItem must be in stock to be "installed" raise ValidationError(_("Stock item is unavailable")) @@ -396,7 +396,7 @@ class InstallStockItemSerializer(serializers.Serializer): return stock_item def save(self): - """Install the selected stock item into this one""" + """Install the selected stock item into this one.""" data = self.validated_data stock_item = data['stock_item'] @@ -414,7 +414,7 @@ class InstallStockItemSerializer(serializers.Serializer): class UninstallStockItemSerializer(serializers.Serializer): - """API serializers for uninstalling an installed item from a stock item""" + """API serializers for uninstalling an installed item from a stock item.""" class Meta: fields = [ @@ -454,7 +454,7 @@ class UninstallStockItemSerializer(serializers.Serializer): class LocationTreeSerializer(InvenTree.serializers.InvenTreeModelSerializer): - """Serializer for a simple tree view""" + """Serializer for a simple tree view.""" class Meta: model = StockLocation @@ -466,7 +466,7 @@ class LocationTreeSerializer(InvenTree.serializers.InvenTreeModelSerializer): class LocationSerializer(InvenTree.serializers.InvenTreeModelSerializer): - """Detailed information about a stock location""" + """Detailed information about a stock location.""" url = serializers.CharField(source='get_absolute_url', read_only=True) @@ -490,7 +490,7 @@ class LocationSerializer(InvenTree.serializers.InvenTreeModelSerializer): class StockItemAttachmentSerializer(InvenTree.serializers.InvenTreeAttachmentSerializer): - """Serializer for StockItemAttachment model""" + """Serializer for StockItemAttachment model.""" def __init__(self, *args, **kwargs): user_detail = kwargs.pop('user_detail', False) @@ -527,7 +527,7 @@ class StockItemAttachmentSerializer(InvenTree.serializers.InvenTreeAttachmentSer class StockItemTestResultSerializer(InvenTree.serializers.InvenTreeModelSerializer): - """Serializer for the StockItemTestResult model""" + """Serializer for the StockItemTestResult model.""" user_detail = InvenTree.serializers.UserSerializerBrief(source='user', read_only=True) @@ -568,7 +568,7 @@ class StockItemTestResultSerializer(InvenTree.serializers.InvenTreeModelSerializ class StockTrackingSerializer(InvenTree.serializers.InvenTreeModelSerializer): - """Serializer for StockItemTracking model""" + """Serializer for StockItemTracking model.""" def __init__(self, *args, **kwargs): @@ -761,7 +761,7 @@ class StockMergeItemSerializer(serializers.Serializer): class StockMergeSerializer(serializers.Serializer): - """Serializer for merging two (or more) stock items together""" + """Serializer for merging two (or more) stock items together.""" class Meta: fields = [ @@ -904,7 +904,7 @@ class StockAdjustmentItemSerializer(serializers.Serializer): class StockAdjustmentSerializer(serializers.Serializer): - """Base class for managing stock adjustment actions via the API""" + """Base class for managing stock adjustment actions via the API.""" class Meta: fields = [ @@ -934,7 +934,7 @@ class StockAdjustmentSerializer(serializers.Serializer): class StockCountSerializer(StockAdjustmentSerializer): - """Serializer for counting stock items""" + """Serializer for counting stock items.""" def save(self): diff --git a/InvenTree/stock/test_api.py b/InvenTree/stock/test_api.py index 1bd7009760..69642f8bee 100644 --- a/InvenTree/stock/test_api.py +++ b/InvenTree/stock/test_api.py @@ -1,4 +1,4 @@ -"""Unit testing for the Stock API""" +"""Unit testing for the Stock API.""" import io import os @@ -45,7 +45,7 @@ class StockAPITestCase(InvenTreeAPITestCase): class StockLocationTest(StockAPITestCase): - """Series of API tests for the StockLocation API""" + """Series of API tests for the StockLocation API.""" list_url = reverse('api-location-list') def setUp(self): @@ -72,12 +72,12 @@ class StockLocationTest(StockAPITestCase): class StockItemListTest(StockAPITestCase): - """Tests for the StockItem API LIST endpoint""" + """Tests for the StockItem API LIST endpoint.""" list_url = reverse('api-stock-list') def get_stock(self, **kwargs): - """Filter stock and return JSON object""" + """Filter stock and return JSON object.""" response = self.client.get(self.list_url, format='json', data=kwargs) self.assertEqual(response.status_code, status.HTTP_200_OK) @@ -92,7 +92,7 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 29) def test_filter_by_part(self): - """Filter StockItem by Part reference""" + """Filter StockItem by Part reference.""" response = self.get_stock(part=25) self.assertEqual(len(response), 17) @@ -102,12 +102,12 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 12) def test_filter_by_IPN(self): - """Filter StockItem by IPN reference""" + """Filter StockItem by IPN reference.""" response = self.get_stock(IPN="R.CH") self.assertEqual(len(response), 3) def test_filter_by_location(self): - """Filter StockItem by StockLocation reference""" + """Filter StockItem by StockLocation reference.""" response = self.get_stock(location=5) self.assertEqual(len(response), 1) @@ -121,7 +121,7 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 18) def test_filter_by_depleted(self): - """Filter StockItem by depleted status""" + """Filter StockItem by depleted status.""" response = self.get_stock(depleted=1) self.assertEqual(len(response), 1) @@ -129,7 +129,7 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 28) def test_filter_by_in_stock(self): - """Filter StockItem by 'in stock' status""" + """Filter StockItem by 'in stock' status.""" response = self.get_stock(in_stock=1) self.assertEqual(len(response), 26) @@ -137,7 +137,7 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 3) def test_filter_by_status(self): - """Filter StockItem by 'status' field""" + """Filter StockItem by 'status' field.""" codes = { StockStatus.OK: 27, StockStatus.DESTROYED: 1, @@ -153,12 +153,12 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), num) def test_filter_by_batch(self): - """Filter StockItem by batch code""" + """Filter StockItem by batch code.""" response = self.get_stock(batch='B123') self.assertEqual(len(response), 1) def test_filter_by_serialized(self): - """Filter StockItem by serialized status""" + """Filter StockItem by serialized status.""" response = self.get_stock(serialized=1) self.assertEqual(len(response), 12) @@ -172,7 +172,7 @@ class StockItemListTest(StockAPITestCase): self.assertIsNone(item['serial']) def test_filter_by_has_batch(self): - """Test the 'has_batch' filter, which tests if the stock item has been assigned a batch code""" + """Test the 'has_batch' filter, which tests if the stock item has been assigned a batch code.""" with_batch = self.get_stock(has_batch=1) without_batch = self.get_stock(has_batch=0) @@ -208,7 +208,7 @@ class StockItemListTest(StockAPITestCase): self.assertTrue(item['batch'] in blank and item['serial'] in blank) def test_filter_by_expired(self): - """Filter StockItem by expiry status""" + """Filter StockItem by expiry status.""" # First, we can assume that the 'stock expiry' feature is disabled response = self.get_stock(expired=1) self.assertEqual(len(response), 29) @@ -246,7 +246,7 @@ class StockItemListTest(StockAPITestCase): self.assertEqual(len(response), 25) def test_paginate(self): - """Test that we can paginate results correctly""" + """Test that we can paginate results correctly.""" for n in [1, 5, 10]: response = self.get_stock(limit=n) @@ -275,7 +275,7 @@ class StockItemListTest(StockAPITestCase): return dataset def test_export(self): - """Test exporting of Stock data via the API""" + """Test exporting of Stock data via the API.""" dataset = self.export_data({}) # Check that *all* stock item objects have been exported @@ -312,7 +312,7 @@ class StockItemListTest(StockAPITestCase): class StockItemTest(StockAPITestCase): - """Series of API tests for the StockItem API""" + """Series of API tests for the StockItem API.""" list_url = reverse('api-stock-list') @@ -368,7 +368,7 @@ class StockItemTest(StockAPITestCase): self.assertEqual(response.data['location'], None) def test_stock_item_create(self): - """Test creation of a StockItem via the API""" + """Test creation of a StockItem via the API.""" # POST with an empty part reference response = self.client.post( @@ -485,7 +485,6 @@ class StockItemTest(StockAPITestCase): Notes: - Part <25> has a default_expiry of 10 days - """ # First test - create a new StockItem without an expiry date data = { @@ -524,7 +523,7 @@ class StockItemTest(StockAPITestCase): self.assertEqual(response.data['expiry_date'], expiry.isoformat()) def test_purchase_price(self): - """Test that we can correctly read and adjust purchase price information via the API""" + """Test that we can correctly read and adjust purchase price information via the API.""" url = reverse('api-stock-detail', kwargs={'pk': 1}) data = self.get(url, expected_code=200).data @@ -582,7 +581,7 @@ class StockItemTest(StockAPITestCase): self.assertEqual(data['purchase_price_currency'], 'NZD') def test_install(self): - """Test that stock item can be installed into antoher item, via the API""" + """Test that stock item can be installed into antoher item, via the API.""" # Select the "parent" stock item parent_part = part.models.Part.objects.get(pk=100) @@ -664,10 +663,10 @@ class StockItemTest(StockAPITestCase): class StocktakeTest(StockAPITestCase): - """Series of tests for the Stocktake API""" + """Series of tests for the Stocktake API.""" def test_action(self): - """Test each stocktake action endpoint, for validation""" + """Test each stocktake action endpoint, for validation.""" for endpoint in ['api-stock-count', 'api-stock-add', 'api-stock-remove']: url = reverse(endpoint) @@ -723,7 +722,7 @@ class StocktakeTest(StockAPITestCase): self.assertContains(response, 'Ensure this value is greater than or equal to 0', status_code=status.HTTP_400_BAD_REQUEST) def test_transfer(self): - """Test stock transfers""" + """Test stock transfers.""" data = { 'items': [ { @@ -749,7 +748,7 @@ class StocktakeTest(StockAPITestCase): class StockItemDeletionTest(StockAPITestCase): - """Tests for stock item deletion via the API""" + """Tests for stock item deletion via the API.""" def test_delete(self): @@ -861,7 +860,7 @@ class StockTestResultTest(StockAPITestCase): self.assertEqual(test['user'], self.user.pk) def test_post_bitmap(self): - """2021-08-25 + """2021-08-25. For some (unknown) reason, prior to fix https://github.com/inventree/InvenTree/pull/2018 uploading a bitmap image would result in a failure. @@ -894,7 +893,7 @@ class StockTestResultTest(StockAPITestCase): class StockAssignTest(StockAPITestCase): - """Unit tests for the stock assignment API endpoint, where stock items are manually assigned to a customer""" + """Unit tests for the stock assignment API endpoint, where stock items are manually assigned to a customer.""" URL = reverse('api-stock-assign') @@ -1000,7 +999,7 @@ class StockAssignTest(StockAPITestCase): class StockMergeTest(StockAPITestCase): - """Unit tests for merging stock items via the API""" + """Unit tests for merging stock items via the API.""" URL = reverse('api-stock-merge') @@ -1032,7 +1031,7 @@ class StockMergeTest(StockAPITestCase): ) def test_missing_data(self): - """Test responses which are missing required data""" + """Test responses which are missing required data.""" # Post completely empty data = self.post( @@ -1057,7 +1056,7 @@ class StockMergeTest(StockAPITestCase): self.assertIn('At least two stock items', str(data)) def test_invalid_data(self): - """Test responses which have invalid data""" + """Test responses which have invalid data.""" # Serialized stock items should be rejected data = self.post( self.URL, @@ -1138,7 +1137,7 @@ class StockMergeTest(StockAPITestCase): self.assertIn('Stock items must refer to the same supplier part', str(data)) def test_valid_merge(self): - """Test valid merging of stock items""" + """Test valid merging of stock items.""" # Check initial conditions n = StockItem.objects.filter(part=self.part).count() self.assertEqual(self.item_1.quantity, 100) diff --git a/InvenTree/stock/test_views.py b/InvenTree/stock/test_views.py index 48f1126395..eaf28b112e 100644 --- a/InvenTree/stock/test_views.py +++ b/InvenTree/stock/test_views.py @@ -22,7 +22,7 @@ class StockViewTestCase(InvenTreeTestCase): class StockListTest(StockViewTestCase): - """Tests for Stock list views""" + """Tests for Stock list views.""" def test_stock_index(self): response = self.client.get(reverse('stock-index')) @@ -30,10 +30,10 @@ class StockListTest(StockViewTestCase): class StockOwnershipTest(StockViewTestCase): - """Tests for stock ownership views""" + """Tests for stock ownership views.""" def setUp(self): - """Add another user for ownership tests""" + """Add another user for ownership tests.""" """ TODO: Refactor this following test to use the new API form diff --git a/InvenTree/stock/tests.py b/InvenTree/stock/tests.py index 325df9a677..afe31b9c73 100644 --- a/InvenTree/stock/tests.py +++ b/InvenTree/stock/tests.py @@ -13,7 +13,7 @@ from .models import (StockItem, StockItemTestResult, StockItemTracking, class StockTest(InvenTreeTestCase): - """Tests to ensure that the stock location tree functions correcly""" + """Tests to ensure that the stock location tree functions correcly.""" fixtures = [ 'category', @@ -188,7 +188,7 @@ class StockTest(InvenTreeTestCase): self.assertEqual(s_item.location, self.office) def test_move(self): - """Test stock movement functions""" + """Test stock movement functions.""" # Move 4,000 screws to the bathroom it = StockItem.objects.get(pk=1) self.assertNotEqual(it.location, self.bathroom) @@ -330,7 +330,7 @@ class StockTest(InvenTreeTestCase): w2 = StockItem.objects.get(pk=101) def test_serials(self): - """Tests for stock serialization""" + """Tests for stock serialization.""" p = Part.objects.create( name='trackable part', description='trackable part', @@ -361,7 +361,7 @@ class StockTest(InvenTreeTestCase): self.assertTrue(item.serialized) def test_big_serials(self): - """Unit tests for "large" serial numbers which exceed integer encoding""" + """Unit tests for "large" serial numbers which exceed integer encoding.""" p = Part.objects.create( name='trackable part', description='trackable part', @@ -464,7 +464,7 @@ class StockTest(InvenTreeTestCase): item.serializeStock(3, "hello", self.user) def test_serialize_stock_valid(self): - """Perform valid stock serializations""" + """Perform valid stock serializations.""" # There are 10 of these in stock # Item will deplete when deleted item = StockItem.objects.get(pk=100) @@ -668,7 +668,7 @@ class StockTest(InvenTreeTestCase): class VariantTest(StockTest): - """Tests for calculation stock counts against templates / variants""" + """Tests for calculation stock counts against templates / variants.""" def test_variant_stock(self): # Check the 'Chair' variant diff --git a/InvenTree/stock/urls.py b/InvenTree/stock/urls.py index 6a6b8da44e..859a9114a4 100644 --- a/InvenTree/stock/urls.py +++ b/InvenTree/stock/urls.py @@ -1,4 +1,4 @@ -"""URL lookup for Stock app""" +"""URL lookup for Stock app.""" from django.urls import include, re_path diff --git a/InvenTree/stock/views.py b/InvenTree/stock/views.py index b739c4b624..c67d9676ad 100644 --- a/InvenTree/stock/views.py +++ b/InvenTree/stock/views.py @@ -1,4 +1,4 @@ -"""Django views for interacting with Stock app""" +"""Django views for interacting with Stock app.""" from datetime import datetime @@ -19,7 +19,7 @@ from .models import StockItem, StockItemTracking, StockLocation class StockIndex(InvenTreeRoleMixin, InvenTreePluginViewMixin, ListView): - """StockIndex view loads all StockLocation and StockItem object""" + """StockIndex view loads all StockLocation and StockItem object.""" model = StockItem template_name = 'stock/location.html' context_obect_name = 'locations' @@ -45,7 +45,7 @@ class StockIndex(InvenTreeRoleMixin, InvenTreePluginViewMixin, ListView): class StockLocationDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detailed view of a single StockLocation object""" + """Detailed view of a single StockLocation object.""" context_object_name = 'location' template_name = 'stock/location.html' @@ -64,7 +64,7 @@ class StockLocationDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailVi class StockItemDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): - """Detailed view of a single StockItem object""" + """Detailed view of a single StockItem object.""" context_object_name = 'item' template_name = 'stock/item.html' @@ -92,7 +92,7 @@ class StockItemDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): return data def get(self, request, *args, **kwargs): - """Check if item exists else return to stock index""" + """Check if item exists else return to stock index.""" stock_pk = kwargs.get('pk', None) if stock_pk: @@ -108,14 +108,14 @@ class StockItemDetail(InvenTreeRoleMixin, InvenTreePluginViewMixin, DetailView): class StockLocationQRCode(QRCodeView): - """View for displaying a QR code for a StockLocation object""" + """View for displaying a QR code for a StockLocation object.""" ajax_form_title = _("Stock Location QR code") role_required = ['stock_location.view', 'stock.view'] def get_qr_data(self): - """Generate QR code data for the StockLocation""" + """Generate QR code data for the StockLocation.""" try: loc = StockLocation.objects.get(id=self.pk) return loc.format_barcode() @@ -152,7 +152,7 @@ class StockItemReturnToStock(AjaxUpdateView): class StockItemDeleteTestData(AjaxUpdateView): - """View for deleting all test data""" + """View for deleting all test data.""" model = StockItem form_class = ConfirmForm @@ -187,13 +187,13 @@ class StockItemDeleteTestData(AjaxUpdateView): class StockItemQRCode(QRCodeView): - """View for displaying a QR code for a StockItem object""" + """View for displaying a QR code for a StockItem object.""" ajax_form_title = _("Stock Item QR Code") role_required = 'stock.view' def get_qr_data(self): - """Generate QR code data for the StockItem""" + """Generate QR code data for the StockItem.""" try: item = StockItem.objects.get(id=self.pk) return item.format_barcode() @@ -231,7 +231,7 @@ class StockItemConvert(AjaxUpdateView): class StockLocationDelete(AjaxDeleteView): - """View to delete a StockLocation + """View to delete a StockLocation. Presents a deletion confirmation form to the user """ @@ -244,7 +244,7 @@ class StockLocationDelete(AjaxDeleteView): class StockItemDelete(AjaxDeleteView): - """View to delete a StockItem + """View to delete a StockItem. Presents a deletion confirmation form to the user """ @@ -257,7 +257,7 @@ class StockItemDelete(AjaxDeleteView): class StockItemTrackingDelete(AjaxDeleteView): - """View to delete a StockItemTracking object + """View to delete a StockItemTracking object. Presents a deletion confirmation form to the user """ @@ -268,7 +268,7 @@ class StockItemTrackingDelete(AjaxDeleteView): class StockItemTrackingEdit(AjaxUpdateView): - """View for editing a StockItemTracking object""" + """View for editing a StockItemTracking object.""" model = StockItemTracking ajax_form_title = _('Edit Stock Tracking Entry') diff --git a/InvenTree/users/admin.py b/InvenTree/users/admin.py index 4aab89399f..7513d245c8 100644 --- a/InvenTree/users/admin.py +++ b/InvenTree/users/admin.py @@ -73,7 +73,7 @@ class InvenTreeGroupAdminForm(forms.ModelForm): class RoleGroupAdmin(admin.ModelAdmin): # pragma: no cover - """Custom admin interface for the Group model""" + """Custom admin interface for the Group model.""" form = InvenTreeGroupAdminForm @@ -85,7 +85,7 @@ class RoleGroupAdmin(admin.ModelAdmin): # pragma: no cover 'stock_item', 'build', 'purchase_order', 'sales_order') def get_rule_set(self, obj, rule_set_type): - """Return list of permissions for the given ruleset""" + """Return list of permissions for the given ruleset.""" # Get all rulesets associated to object rule_sets = RuleSet.objects.filter(group=obj.pk) @@ -206,7 +206,7 @@ class InvenTreeUserAdmin(UserAdmin): class OwnerAdmin(admin.ModelAdmin): - """Custom admin interface for the Owner model""" + """Custom admin interface for the Owner model.""" pass diff --git a/InvenTree/users/api.py b/InvenTree/users/api.py index a12a3acc12..9fbfa255df 100644 --- a/InvenTree/users/api.py +++ b/InvenTree/users/api.py @@ -14,7 +14,10 @@ from users.serializers import OwnerSerializer, UserSerializer class OwnerList(generics.ListAPIView): - """List API endpoint for Owner model. Cannot create.""" + """List API endpoint for Owner model. + + Cannot create. + """ queryset = Owner.objects.all() serializer_class = OwnerSerializer @@ -50,14 +53,17 @@ class OwnerList(generics.ListAPIView): class OwnerDetail(generics.RetrieveAPIView): - """Detail API endpoint for Owner model. Cannot edit or delete""" + """Detail API endpoint for Owner model. + + Cannot edit or delete + """ queryset = Owner.objects.all() serializer_class = OwnerSerializer class RoleDetails(APIView): - """API endpoint which lists the available role permissions for the current user + """API endpoint which lists the available role permissions for the current user. (Requires authentication) """ @@ -100,7 +106,7 @@ class RoleDetails(APIView): class UserDetail(generics.RetrieveAPIView): - """Detail endpoint for a single user""" + """Detail endpoint for a single user.""" queryset = User.objects.all() serializer_class = UserSerializer @@ -108,7 +114,7 @@ class UserDetail(generics.RetrieveAPIView): class UserList(generics.ListAPIView): - """List endpoint for detail on all users""" + """List endpoint for detail on all users.""" queryset = User.objects.all() serializer_class = UserSerializer diff --git a/InvenTree/users/models.py b/InvenTree/users/models.py index 9a2975917b..6346757441 100644 --- a/InvenTree/users/models.py +++ b/InvenTree/users/models.py @@ -217,7 +217,7 @@ class RuleSet(models.Model): @classmethod def check_table_permission(cls, user, table, permission): - """Check if the provided user has the specified permission against the table""" + """Check if the provided user has the specified permission against the table.""" # If the table does *not* require permissions if table in cls.RULESET_IGNORE: return True @@ -258,7 +258,7 @@ class RuleSet(models.Model): ) def __str__(self, debug=False): # pragma: no cover - """Ruleset string representation""" + """Ruleset string representation.""" if debug: # Makes debugging easier return f'{str(self.group).ljust(15)}: {self.name.title().ljust(15)} | ' \ @@ -290,7 +290,7 @@ class RuleSet(models.Model): def split_model(model): - """Get modelname and app from modelstring""" + """Get modelname and app from modelstring.""" *app, model = model.split('_') # handle models that have @@ -303,7 +303,7 @@ def split_model(model): def split_permission(app, perm): - """Split permission string into permission and model""" + """Split permission string into permission and model.""" permission_name, *model = perm.split('_') # handle models that have underscores if len(model) > 1: # pragma: no cover @@ -397,7 +397,7 @@ def update_group_roles(group, debug=False): add_model(model, 'delete', ruleset.can_delete) def get_permission_object(permission_string): - """Find the permission object in the database, from the simplified permission string + """Find the permission object in the database, from the simplified permission string. Args: permission_string - a simplified permission_string e.g. 'part.view_partcategory' @@ -563,20 +563,20 @@ class Owner(models.Model): owner = GenericForeignKey('owner_type', 'owner_id') def __str__(self): - """Defines the owner string representation""" + """Defines the owner string representation.""" return f'{self.owner} ({self.owner_type.name})' def name(self): - """Return the 'name' of this owner""" + """Return the 'name' of this owner.""" return str(self.owner) def label(self): - """Return the 'type' label of this owner i.e. 'user' or 'group'""" + """Return the 'type' label of this owner i.e. 'user' or 'group'.""" return str(self.owner_type.name) @classmethod def create(cls, obj): - """Check if owner exist then create new owner entry""" + """Check if owner exist then create new owner entry.""" # Check for existing owner existing_owner = cls.get_owner(obj) @@ -591,7 +591,7 @@ class Owner(models.Model): @classmethod def get_owner(cls, user_or_group): - """Get owner instance for a group or user""" + """Get owner instance for a group or user.""" user_model = get_user_model() owner = None content_type_id = 0 diff --git a/InvenTree/users/serializers.py b/InvenTree/users/serializers.py index 70a80f7d7f..6a33f17c49 100644 --- a/InvenTree/users/serializers.py +++ b/InvenTree/users/serializers.py @@ -10,7 +10,7 @@ from .models import Owner class UserSerializer(InvenTreeModelSerializer): - """Serializer for a User""" + """Serializer for a User.""" class Meta: model = User diff --git a/InvenTree/users/test_migrations.py b/InvenTree/users/test_migrations.py index 0adffe070b..5edbcb50af 100644 --- a/InvenTree/users/test_migrations.py +++ b/InvenTree/users/test_migrations.py @@ -1,4 +1,4 @@ -"""Unit tests for the user model database migrations""" +"""Unit tests for the user model database migrations.""" from django_test_migrations.contrib.unittest_case import MigratorTestCase @@ -6,7 +6,7 @@ from InvenTree import helpers class TestForwardMigrations(MigratorTestCase): - """Test entire schema migration sequence for the users app""" + """Test entire schema migration sequence for the users app.""" migrate_from = ('users', helpers.getOldestMigrationFile('users')) migrate_to = ('users', helpers.getNewestMigrationFile('users')) diff --git a/InvenTree/users/tests.py b/InvenTree/users/tests.py index 476e65bec3..eb285c9c0b 100644 --- a/InvenTree/users/tests.py +++ b/InvenTree/users/tests.py @@ -201,7 +201,7 @@ class OwnerModelTest(InvenTreeTestCase): self.assertEqual(group_as_owner, None) def test_api(self): - """Test user APIs""" + """Test user APIs.""" self.client.logout() # not authed @@ -218,7 +218,7 @@ class OwnerModelTest(InvenTreeTestCase): # self.do_request(reverse('api-owner-detail', kwargs={'pk': self.user.id}), {}) def test_token(self): - """Test token mechanisms""" + """Test token mechanisms.""" self.client.logout() token = Token.objects.filter(user=self.user)