2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-28 03:26:45 +00:00

Add more liniting rules (mostly for imports) (#7846)

* remove unused imports

* enable pyflake checks

* various fixes

* fix assert
This commit is contained in:
Matthias Mair 2024-08-10 00:12:58 +02:00 committed by GitHub
parent d68d52ba88
commit 8eea8812e4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
39 changed files with 28 additions and 79 deletions

View File

@ -20,7 +20,7 @@ src = ["src/backend/InvenTree"]
"__init__.py" = ["D104"] "__init__.py" = ["D104"]
[tool.ruff.lint] [tool.ruff.lint]
select = ["A", "B", "C4", "D", "I", "N"] select = ["A", "B", "C4", "D", "I", "N", "F"]
# Things that should be enabled in the future: # Things that should be enabled in the future:
# - LOG # - LOG
# - DJ # for Django stuff # - DJ # for Django stuff

View File

@ -8,7 +8,6 @@ from pathlib import Path
from django.conf import settings from django.conf import settings
from django.db import transaction from django.db import transaction
from django.http import JsonResponse from django.http import JsonResponse
from django.urls import include, path
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django_q.models import OrmQ from django_q.models import OrmQ
@ -21,9 +20,7 @@ from rest_framework.views import APIView
import InvenTree.version import InvenTree.version
import users.models import users.models
from InvenTree.filters import SEARCH_ORDER_FILTER
from InvenTree.mixins import ListCreateAPI from InvenTree.mixins import ListCreateAPI
from InvenTree.permissions import RolePermission
from InvenTree.templatetags.inventree_extras import plugins_info from InvenTree.templatetags.inventree_extras import plugins_info
from part.models import Part from part.models import Part
from plugin.serializers import MetadataSerializer from plugin.serializers import MetadataSerializer

View File

@ -11,7 +11,7 @@ from django.core.exceptions import AppRegistryNotReady
from django.db import transaction from django.db import transaction
from django.db.utils import IntegrityError, OperationalError from django.db.utils import IntegrityError, OperationalError
from allauth.socialaccount.signals import social_account_added, social_account_updated from allauth.socialaccount.signals import social_account_updated
import InvenTree.conversion import InvenTree.conversion
import InvenTree.ready import InvenTree.ready

View File

@ -153,7 +153,7 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
if unit: if unit:
try: try:
valid = unit in ureg valid = unit in ureg
except Exception as exc: except Exception:
valid = False valid = False
if not valid: if not valid:
@ -196,7 +196,7 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
try: try:
value = convert_value(attempt, unit) value = convert_value(attempt, unit)
break break
except Exception as exc: except Exception:
value = None value = None
if value is None: if value is None:

View File

@ -9,7 +9,6 @@ import traceback
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError as DjangoValidationError from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.utils import IntegrityError, OperationalError
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import rest_framework.views as drfviews import rest_framework.views as drfviews

View File

@ -3,7 +3,6 @@
import datetime import datetime
import hashlib import hashlib
import io import io
import json
import logging import logging
import os import os
import os.path import os.path
@ -27,7 +26,6 @@ from bleach import clean
from djmoney.money import Money from djmoney.money import Money
from PIL import Image from PIL import Image
import InvenTree.version
from common.currency import currency_code_default from common.currency import currency_code_default
from .settings import MEDIA_URL, STATIC_URL from .settings import MEDIA_URL, STATIC_URL

View File

@ -36,8 +36,6 @@ def get_base_url(request=None):
3. If settings.SITE_URL is set (e.g. in the Django settings), use that 3. If settings.SITE_URL is set (e.g. in the Django settings), use that
4. If the InvenTree setting INVENTREE_BASE_URL is set, use that 4. If the InvenTree setting INVENTREE_BASE_URL is set, use that
""" """
import common.models
# Check if a request is provided # Check if a request is provided
if request: if request:
return request.build_absolute_uri('/') return request.build_absolute_uri('/')
@ -104,8 +102,6 @@ def download_image_from_url(remote_url, timeout=2.5):
ValueError: Server responded with invalid 'Content-Length' value ValueError: Server responded with invalid 'Content-Length' value
TypeError: Response is not a valid image TypeError: Response is not a valid image
""" """
import common.models
# Check that the provided URL at least looks valid # Check that the provided URL at least looks valid
validator = URLValidator() validator = URLValidator()
validator(remote_url) validator(remote_url)
@ -203,8 +199,6 @@ def render_currency(
max_decimal_places: The maximum number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES setting. max_decimal_places: The maximum number of decimal places to render to. If unspecified, uses the PRICING_DECIMAL_PLACES setting.
include_symbol: If True, include the currency symbol in the output include_symbol: If True, include the currency symbol in the output
""" """
import common.models
if money in [None, '']: if money in [None, '']:
return '-' return '-'

View File

@ -93,7 +93,7 @@ class PluginValidationMixin(DiffMixin):
return return
except ValidationError as exc: except ValidationError as exc:
raise exc raise exc
except Exception as exc: except Exception:
# Log the exception to the database # Log the exception to the database
import InvenTree.exceptions import InvenTree.exceptions

View File

@ -18,7 +18,6 @@ import django.conf.locale
import django.core.exceptions import django.core.exceptions
from django.core.validators import URLValidator from django.core.validators import URLValidator
from django.http import Http404 from django.http import Http404
from django.utils.translation import gettext_lazy as _
import pytz import pytz
from dotenv import load_dotenv from dotenv import load_dotenv
@ -301,7 +300,7 @@ if (
and get_boolean_setting('INVENTREE_DEBUG_SHELL', 'debug_shell', False) and get_boolean_setting('INVENTREE_DEBUG_SHELL', 'debug_shell', False)
): # noqa ): # noqa
try: try:
import django_admin_shell import django_admin_shell # noqa: F401
INSTALLED_APPS.append('django_admin_shell') INSTALLED_APPS.append('django_admin_shell')
ADMIN_SHELL_ENABLE = True ADMIN_SHELL_ENABLE = True

View File

@ -4,6 +4,6 @@ This file remains here for backwards compatibility,
as external plugins may import status codes from this file. as external plugins may import status codes from this file.
""" """
from build.status_codes import * from build.status_codes import * # noqa: F403
from order.status_codes import * from order.status_codes import * # noqa: F403
from stock.status_codes import * from stock.status_codes import * # noqa: F403

View File

@ -9,7 +9,6 @@ from allauth.socialaccount.models import SocialAccount, SocialLogin
from common.models import InvenTreeSetting from common.models import InvenTreeSetting
from InvenTree import sso from InvenTree import sso
from InvenTree.forms import RegistratonMixin from InvenTree.forms import RegistratonMixin
from InvenTree.unit_test import InvenTreeTestCase
class Dummy: class Dummy:

View File

@ -1,6 +1,5 @@
"""Test general functions and helpers.""" """Test general functions and helpers."""
import json
import os import os
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta

View File

@ -117,7 +117,7 @@ def inventreeDocUrl():
def inventreeAppUrl(): def inventreeAppUrl():
"""Return URL for InvenTree app site.""" """Return URL for InvenTree app site."""
return f'https://docs.inventree.org/app/' return 'https://docs.inventree.org/app/'
def inventreeCreditsUrl(): def inventreeCreditsUrl():

View File

@ -407,8 +407,6 @@ class SettingsTest(InvenTreeTestCase):
@override_settings(SITE_URL=None, PLUGIN_TESTING=True, PLUGIN_TESTING_SETUP=True) @override_settings(SITE_URL=None, PLUGIN_TESTING=True, PLUGIN_TESTING_SETUP=True)
def test_defaults(self): def test_defaults(self):
"""Populate the settings with default values.""" """Populate the settings with default values."""
N = len(InvenTreeSetting.SETTINGS.keys())
for key in InvenTreeSetting.SETTINGS.keys(): for key in InvenTreeSetting.SETTINGS.keys():
value = InvenTreeSetting.get_setting_default(key) value = InvenTreeSetting.get_setting_default(key)
@ -1103,7 +1101,6 @@ class CommonTest(InvenTreeAPITestCase):
def test_restart_flag(self): 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 from plugin import registry
# set flag true # set flag true

View File

@ -45,7 +45,7 @@ def validate_attachment_model_type(value):
"""Ensure that the provided attachment model is valid.""" """Ensure that the provided attachment model is valid."""
model_names = [el[0] for el in attachment_model_options()] model_names = [el[0] for el in attachment_model_options()]
if value not in model_names: if value not in model_names:
raise ValidationError(f'Model type does not support attachments') raise ValidationError('Model type does not support attachments')
def validate_notes_model_type(value): def validate_notes_model_type(value):

View File

@ -1,7 +1,6 @@
"""Admin site specification for the 'importer' app.""" """Admin site specification for the 'importer' app."""
from django.contrib import admin from django.contrib import admin
from django.urls import path
import importer.models import importer.models
import importer.registry import importer.registry

View File

@ -1,7 +1,6 @@
"""Django admin interface for the machine app.""" """Django admin interface for the machine app."""
from django.contrib import admin from django.contrib import admin
from django.http.request import HttpRequest
from machine import models from machine import models

View File

@ -13,7 +13,7 @@ logger = logging.getLogger('inventree')
class MachineRegistry( class MachineRegistry(
get_shared_class_instance_state_mixin(lambda _x: f'machine:registry') get_shared_class_instance_state_mixin(lambda _x: 'machine:registry')
): ):
"""Machine registry class.""" """Machine registry class."""
@ -44,7 +44,7 @@ class MachineRegistry(
"""Initialize the machine registry.""" """Initialize the machine registry."""
# clear cache for machines (only needed for global redis cache) # clear cache for machines (only needed for global redis cache)
if main and hasattr(cache, 'delete_pattern'): # pragma: no cover if main and hasattr(cache, 'delete_pattern'): # pragma: no cover
cache.delete_pattern(f'machine:*') cache.delete_pattern('machine:*')
self.discover_machine_types() self.discover_machine_types()
self.discover_drivers() self.discover_drivers()

View File

@ -292,7 +292,7 @@ class TestLabelPrinterMachineType(TestMachineRegistryMixin, InvenTreeAPITestCase
# test the single print label method calls # test the single print label method calls
self.assertEqual(self.print_label.call_count, 2) self.assertEqual(self.print_label.call_count, 2)
self.assertEqual(self.print_label.call_args.args[0], self.machine.machine) self.assertEqual(self.print_label.call_args.args[0], self.machine.machine)
self.assertEqual(self.print_label.call_args.args[1], label) self.assertEqual(self.print_label.call_args.args[1], template)
self.assertEqual(self.print_label.call_args.args[2], parts[1]) self.assertEqual(self.print_label.call_args.args[2], parts[1])
self.assertIn('printing_options', self.print_labels.call_args.kwargs) self.assertIn('printing_options', self.print_labels.call_args.kwargs)
self.assertEqual( self.assertEqual(

View File

@ -1,7 +1,6 @@
"""Order model definitions.""" """Order model definitions."""
import logging import logging
import os
import sys import sys
from datetime import datetime from datetime import datetime
from decimal import Decimal from decimal import Decimal

View File

@ -1126,9 +1126,9 @@ class PartFilter(rest_filters.FilterSet):
# TODO: We should cache BOM checksums to make this process more efficient # TODO: We should cache BOM checksums to make this process more efficient
pks = [] pks = []
for part in queryset: for item in queryset:
if part.is_bom_valid() == value: if item.is_bom_valid() == value:
pks.append(part.pk) pks.append(item.pk)
return queryset.filter(pk__in=pks) return queryset.filter(pk__in=pks)

View File

@ -3,7 +3,6 @@
import io import io
import logging import logging
import time import time
from datetime import datetime
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.files.base import ContentFile from django.core.files.base import ContentFile

View File

@ -4,7 +4,6 @@ import os
from datetime import datetime from datetime import datetime
from decimal import Decimal from decimal import Decimal
from enum import IntEnum from enum import IntEnum
from pathlib import Path
from random import randint from random import randint
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
@ -13,7 +12,6 @@ from django.test.utils import CaptureQueriesContext
from django.urls import reverse from django.urls import reverse
import PIL import PIL
from rest_framework import status
from rest_framework.test import APIClient from rest_framework.test import APIClient
import build.models import build.models
@ -371,7 +369,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
params['delete_parts'] = '1' params['delete_parts'] = '1'
if delete_child_categories: if delete_child_categories:
params['delete_child_categories'] = '1' params['delete_child_categories'] = '1'
response = self.delete(url, params, expected_code=204) self.delete(url, params, expected_code=204)
if delete_parts: if delete_parts:
if i == Target.delete_subcategories_delete_parts: if i == Target.delete_subcategories_delete_parts:
@ -539,7 +537,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
) )
sub4 = PartCategory.objects.create(name='sub4', parent=sub3) sub4 = PartCategory.objects.create(name='sub4', parent=sub3)
sub5 = PartCategory.objects.create(name='sub5', parent=sub2) sub5 = PartCategory.objects.create(name='sub5', parent=sub2)
part = Part.objects.create(name='test', category=sub4) Part.objects.create(name='test', category=sub4)
PartCategory.objects.rebuild() PartCategory.objects.rebuild()
# This query will trigger an internal server error if annotation results are not limited to 1 # This query will trigger an internal server error if annotation results are not limited to 1
@ -973,7 +971,7 @@ class PartAPITest(PartAPITestBase):
"""Return list of part thumbnails.""" """Return list of part thumbnails."""
url = reverse('api-part-thumbs') url = reverse('api-part-thumbs')
response = self.get(url) self.get(url)
def test_paginate(self): def test_paginate(self):
"""Test pagination of the Part list API.""" """Test pagination of the Part list API."""

View File

@ -151,22 +151,7 @@ class BomExportTest(InvenTreeTestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
content = response.headers['Content-Disposition'] content = response.headers['Content-Disposition']
self.assertEqual(content, 'attachment; filename="BOB | Bob | A2_BOM.xls"') self.assertEqual(content, 'attachment; filename="BOB | Bob | A2_BOM.xlsx"')
def test_export_xlsx(self):
"""Test BOM download in XLSX format."""
params = {
'format': 'xlsx',
'cascade': True,
'parameter_data': True,
'stock_data': True,
'supplier_data': True,
'manufacturer_data': True,
}
response = self.client.get(self.url, data=params)
self.assertEqual(response.status_code, 200)
def test_export_json(self): def test_export_json(self):
"""Test BOM download in JSON format.""" """Test BOM download in JSON format."""

View File

@ -12,7 +12,7 @@ import company.models
import order.models import order.models
import part.models import part.models
import stock.models import stock.models
from common.settings import get_global_setting, set_global_setting from common.settings import set_global_setting
from InvenTree.unit_test import InvenTreeTestCase from InvenTree.unit_test import InvenTreeTestCase
from order.status_codes import PurchaseOrderStatus from order.status_codes import PurchaseOrderStatus

View File

@ -3,8 +3,6 @@
from typing import Union from typing import Union
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import pdf2image import pdf2image

View File

@ -1,6 +1,5 @@
"""API for location plugins.""" """API for location plugins."""
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import permissions, serializers from rest_framework import permissions, serializers
from rest_framework.exceptions import NotFound, ParseError from rest_framework.exceptions import NotFound, ParseError
from rest_framework.generics import GenericAPIView from rest_framework.generics import GenericAPIView

View File

@ -5,7 +5,6 @@ import math
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import weasyprint import weasyprint

View File

@ -572,7 +572,7 @@ class PluginsRegistry:
try: try:
self._init_plugin(plg, plugin_configs) self._init_plugin(plg, plugin_configs)
break break
except IntegrationPluginError as error: except IntegrationPluginError:
# Error has been handled downstream # Error has been handled downstream
pass pass
except Exception as error: except Exception as error:

View File

@ -4,7 +4,6 @@ import random
from plugin import InvenTreePlugin from plugin import InvenTreePlugin
from plugin.mixins import ReportMixin from plugin.mixins import ReportMixin
from report.models import ReportTemplate
class SampleReportPlugin(ReportMixin, InvenTreePlugin): class SampleReportPlugin(ReportMixin, InvenTreePlugin):

View File

@ -92,4 +92,4 @@ def copy_plugin_static_files(slug, check_reload=True):
logger.debug('- copied %s to %s', str(item), str(destination_path)) logger.debug('- copied %s to %s', str(item), str(destination_path))
copied += 1 copied += 1
logger.info(f"Copied %s static files for plugin '%s'.", copied, slug) logger.info("Copied %s static files for plugin '%s'.", copied, slug)

View File

@ -354,7 +354,7 @@ class ReportPrint(GenericAPIView):
for plugin in registry.with_mixin('report'): for plugin in registry.with_mixin('report'):
try: try:
plugin.report_callback(self, instance, output, request) plugin.report_callback(self, instance, output, request)
except Exception as e: except Exception:
InvenTree.exceptions.log_error( InvenTree.exceptions.log_error(
f'plugins.{plugin.slug}.report_callback' f'plugins.{plugin.slug}.report_callback'
) )

View File

@ -15,7 +15,6 @@ from django.template.loader import render_to_string
from django.urls import reverse from django.urls import reverse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import common.models
import InvenTree.exceptions import InvenTree.exceptions
import InvenTree.helpers import InvenTree.helpers
import InvenTree.models import InvenTree.models

View File

@ -583,7 +583,7 @@ class TestReportTest(PrintTestMixins, ReportTest):
InvenTreeSetting.set_setting('REPORT_ATTACH_TEST_REPORT', True, None) InvenTreeSetting.set_setting('REPORT_ATTACH_TEST_REPORT', True, None)
response = self.post( response = self.post(
url, {'template': report.pk, 'items': [item.pk]}, expected_code=201 url, {'template': template.pk, 'items': [item.pk]}, expected_code=201
) )
# There should be a link to the generated PDF # There should be a link to the generated PDF

View File

@ -1,6 +1,5 @@
"""JSON API for the Stock app.""" """JSON API for the Stock app."""
import json
from collections import OrderedDict from collections import OrderedDict
from datetime import timedelta from datetime import timedelta
@ -59,7 +58,6 @@ from order.serializers import (
) )
from part.models import BomItem, Part, PartCategory from part.models import BomItem, Part, PartCategory
from part.serializers import PartBriefSerializer from part.serializers import PartBriefSerializer
from stock.admin import LocationResource, StockItemResource
from stock.generators import generate_batch_code, generate_serial_number from stock.generators import generate_batch_code, generate_serial_number
from stock.models import ( from stock.models import (
StockItem, StockItem,

View File

@ -3,8 +3,6 @@
from django.db.models import F, Func, IntegerField, OuterRef, Q, Subquery from django.db.models import F, Func, IntegerField, OuterRef, Q, Subquery
from django.db.models.functions import Coalesce from django.db.models.functions import Coalesce
from sql_util.utils import SubqueryCount
import stock.models import stock.models

View File

@ -76,8 +76,6 @@ def generate_batch_code(**kwargs):
def generate_serial_number(part=None, quantity=1, **kwargs) -> str: def generate_serial_number(part=None, quantity=1, **kwargs) -> str:
"""Generate a default 'serial number' for a new StockItem.""" """Generate a default 'serial number' for a new StockItem."""
from plugin.registry import registry
quantity = quantity or 1 quantity = quantity or 1
if part is None: if part is None:

View File

@ -9,7 +9,7 @@ from decimal import Decimal, InvalidOperation
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.exceptions import FieldError, ValidationError from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator from django.core.validators import MinValueValidator
from django.db import models, transaction from django.db import models, transaction
from django.db.models import Q, Sum from django.db.models import Q, Sum

View File

@ -19,7 +19,7 @@ from rest_framework import exceptions, permissions
from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import BasicAuthentication
from rest_framework.decorators import authentication_classes from rest_framework.decorators import authentication_classes
from rest_framework.generics import DestroyAPIView from rest_framework.generics import DestroyAPIView
from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.views import APIView from rest_framework.views import APIView