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"]
[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:
# - LOG
# - DJ # for Django stuff

View File

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

View File

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

View File

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

View File

@ -3,7 +3,6 @@
import datetime
import hashlib
import io
import json
import logging
import os
import os.path
@ -27,7 +26,6 @@ from bleach import clean
from djmoney.money import Money
from PIL import Image
import InvenTree.version
from common.currency import currency_code_default
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
4. If the InvenTree setting INVENTREE_BASE_URL is set, use that
"""
import common.models
# Check if a request is provided
if request:
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
TypeError: Response is not a valid image
"""
import common.models
# Check that the provided URL at least looks valid
validator = URLValidator()
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.
include_symbol: If True, include the currency symbol in the output
"""
import common.models
if money in [None, '']:
return '-'

View File

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

View File

@ -18,7 +18,6 @@ import django.conf.locale
import django.core.exceptions
from django.core.validators import URLValidator
from django.http import Http404
from django.utils.translation import gettext_lazy as _
import pytz
from dotenv import load_dotenv
@ -301,7 +300,7 @@ if (
and get_boolean_setting('INVENTREE_DEBUG_SHELL', 'debug_shell', False)
): # noqa
try:
import django_admin_shell
import django_admin_shell # noqa: F401
INSTALLED_APPS.append('django_admin_shell')
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.
"""
from build.status_codes import *
from order.status_codes import *
from stock.status_codes import *
from build.status_codes import * # noqa: F403
from order.status_codes import * # noqa: F403
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 InvenTree import sso
from InvenTree.forms import RegistratonMixin
from InvenTree.unit_test import InvenTreeTestCase
class Dummy:

View File

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

View File

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

View File

@ -407,8 +407,6 @@ class SettingsTest(InvenTreeTestCase):
@override_settings(SITE_URL=None, PLUGIN_TESTING=True, PLUGIN_TESTING_SETUP=True)
def test_defaults(self):
"""Populate the settings with default values."""
N = len(InvenTreeSetting.SETTINGS.keys())
for key in InvenTreeSetting.SETTINGS.keys():
value = InvenTreeSetting.get_setting_default(key)
@ -1103,7 +1101,6 @@ class CommonTest(InvenTreeAPITestCase):
def test_restart_flag(self):
"""Test that the restart flag is reset on start."""
import common.models
from plugin import registry
# set flag true

View File

@ -45,7 +45,7 @@ def validate_attachment_model_type(value):
"""Ensure that the provided attachment model is valid."""
model_names = [el[0] for el in attachment_model_options()]
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):

View File

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

View File

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

View File

@ -13,7 +13,7 @@ logger = logging.getLogger('inventree')
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."""
@ -44,7 +44,7 @@ class MachineRegistry(
"""Initialize the machine registry."""
# clear cache for machines (only needed for global redis cache)
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_drivers()

View File

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

View File

@ -1,7 +1,6 @@
"""Order model definitions."""
import logging
import os
import sys
from datetime import datetime
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
pks = []
for part in queryset:
if part.is_bom_valid() == value:
pks.append(part.pk)
for item in queryset:
if item.is_bom_valid() == value:
pks.append(item.pk)
return queryset.filter(pk__in=pks)

View File

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

View File

@ -4,7 +4,6 @@ import os
from datetime import datetime
from decimal import Decimal
from enum import IntEnum
from pathlib import Path
from random import randint
from django.core.exceptions import ValidationError
@ -13,7 +12,6 @@ from django.test.utils import CaptureQueriesContext
from django.urls import reverse
import PIL
from rest_framework import status
from rest_framework.test import APIClient
import build.models
@ -371,7 +369,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
params['delete_parts'] = '1'
if delete_child_categories:
params['delete_child_categories'] = '1'
response = self.delete(url, params, expected_code=204)
self.delete(url, params, expected_code=204)
if delete_parts:
if i == Target.delete_subcategories_delete_parts:
@ -539,7 +537,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
)
sub4 = PartCategory.objects.create(name='sub4', parent=sub3)
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()
# 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."""
url = reverse('api-part-thumbs')
response = self.get(url)
self.get(url)
def test_paginate(self):
"""Test pagination of the Part list API."""

View File

@ -151,22 +151,7 @@ class BomExportTest(InvenTreeTestCase):
self.assertEqual(response.status_code, 200)
content = response.headers['Content-Disposition']
self.assertEqual(content, 'attachment; filename="BOB | Bob | A2_BOM.xls"')
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)
self.assertEqual(content, 'attachment; filename="BOB | Bob | A2_BOM.xlsx"')
def test_export_json(self):
"""Test BOM download in JSON format."""

View File

@ -12,7 +12,7 @@ import company.models
import order.models
import part.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 order.status_codes import PurchaseOrderStatus

View File

@ -3,8 +3,6 @@
from typing import Union
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 _
import pdf2image

View File

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

View File

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

View File

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

View File

@ -4,7 +4,6 @@ import random
from plugin import InvenTreePlugin
from plugin.mixins import ReportMixin
from report.models import ReportTemplate
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))
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'):
try:
plugin.report_callback(self, instance, output, request)
except Exception as e:
except Exception:
InvenTree.exceptions.log_error(
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.utils.translation import gettext_lazy as _
import common.models
import InvenTree.exceptions
import InvenTree.helpers
import InvenTree.models

View File

@ -583,7 +583,7 @@ class TestReportTest(PrintTestMixins, ReportTest):
InvenTreeSetting.set_setting('REPORT_ATTACH_TEST_REPORT', True, None)
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

View File

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

View File

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

View File

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

View File

@ -9,7 +9,7 @@ from decimal import Decimal, InvalidOperation
from django.conf import settings
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.db import models, transaction
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.decorators import authentication_classes
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.views import APIView