Skip to main content

A plugin to show lint errors for IW

Project description

flake8-iw

Linters for some common issues we encounter.- flake8-iw

Building and testing

Run command to build wheel and tarball.

python3 -m build
twine check --strict dist/*
twine upload dist/*

Run command to test.

pytest

Supported lint checks

IW01: Use of patch

Lint check to prevent the use of patch directly. Recommendation: Use PatchingTestCase / PatchingTransactionTestCase instead

Correct

from instawork.tests import PatchingTestCase


class SignUpUpdatedTests(PatchingTestCase):
    def setUp(self):
        self.mock_call = self.patch("apps.auth.signals.task_send_email.delay")

    def test_email(self):
        expect(self.mock_call).to(have_been_called_once)

    def test_sms(self):
        mock_sms = self.patch("apps.auth.signals.task_send_sms.delay")
        expect(mock_sms).to(have_been_called_once)

Wrong ⚠️

from unittest.mock import patch


class SignUpUpdatedTests(TestCase):
    def setUp(self):
        self.patcher = patch("apps.auth.signals.task_send_email.delay")
        self.mock_email = self.patcher.start()

    def tearDown(self):
        self.patcher.stop()

    def test_email(self):
        ...
        expect(self.mock_email).to(have_been_called_once)

    @patch("apps.auth.signals.task_send_sms.delay")
    def test_sms(self, mock_sms):
        ...
        expect(mock_sms).to(have_been_called_once)

IW02: Use of patch for time freeze

Lint check to prevent the use of patch to freeze time. Recommendation: Use freeze_time from PatchingTestCase / PatchingTransactionTestCase or use freeze_time decorator or context manager from freezegun package.

Correct

from django.utils import timezone
from instawork.tests import PatchingTestCase


class UserFeatureViewTests(PatchingTestCase):
    def setUp(self):
        self.now = timezone.now()

    def test_feature_view(self):
        ufv = None

        # Option 1
        with freeze_time(self.now):
            ufv = UserFeatureView.objects.get_or_create(
                user=self.shift.worker, feature=UserFeatureView.FEATURE_1
            )

        # Option 2
        self.freeze_time(self.now)
        ufv = UserFeatureView.objects.get_or_create(
            user=self.shift.worker, feature=UserFeatureView.FEATURE_1
        )

        ...

        expect(ufv.date_created).to(equal(self.now))

Wrong ⚠️

from django.utils import timezone
from instawork.tests import PatchingTestCase


class UserFeatureViewTests(PatchingTestCase):
    def setUp(self):
        self.now = timezone.now()
        self.mock_call = self.patch("django.utils.timezone.now", return_value=self.now)

    def test_feature_view(self):
        ufv = UserFeatureView.objects.get_or_create(
            user=self.shift.worker, feature=UserFeatureView.FEATURE_1
        )

        ...

        expect(ufv.date_created).to(equal(self.now))

IW03: Error logging without exception info (exc_info)

Lint check to prevent error logging without exception info. Recommendation: Add exc_info=True keyword argument in logger.error()

Correct

import logging

custom_logger = logging.getLogger("module.logger")

class UserFeatureView(Model):
    def save(self):
        try:
            ...
        except ValueError as e:
            custom_logger.error(e, exc_info=True)
            return name

Wrong ⚠️

import logging

custom_logger = logging.getLogger("module.logger")

class UserFeatureView(Model):
    def save(self):
        try:
            ...
        except ValueError as e:
            custom_logger.error(e)
            return name

IW04: Use of datetime.now

Lint to avoid usage of datetime.now() which does not contain timezone information and causes various warnings in tests. Use timezone.now() instead.

Correct

from django.utils import timezone

now = timezone.now()

Wrong ⚠️

from datetime import datetime

now = datetime.now()

IW05: Use of datetime.replace(tzinfo=XXX)

Lint to avoid usage of datetime.replace(tzinfo=XXX) which is not a viable way of setting timezones with python/pytz.

Correct

import pytz
from django.utils import timezone

tz = pytz.timezone("America/Los_Angeles")
now_pt = timezone.now().astimezone(tz)

Wrong ⚠️

import pytz
from django.utils import timezone

tz = pytz.timezone("America/Los_Angeles")
now_pt = timezone.now().replace(tzinfo=tz)

IW06: Use of bulk_update/bulk_create without batch_size

Lint to avoid usage of Model.objects.bulk_update / Model.objects.bulk_create. Use Model.objects.bulk_update(batch_size=X) / Model.objects.bulk_create(batch_size=X) instead.

Correct

# Bulk update
Model.objects.bulk_update([obj1, obj2, ...], batch_size=10)

# Bulk create
Model.objects.bulk_create([obj1, obj2, ...], batch_size=10)

Wrong ⚠️

# Bulk update
Model.objects.bulk_update([obj1, obj2, ...])

# Bulk create
Model.objects.bulk_create([obj1, obj2, ...])

IW07: IW07 use of celery.shared_task, use instawork.decorators.shared_task

Use our internal decorator instead: instawork.decorators.shared_task.

Correct

from instawork.decorators import shared_task

@shared_task
def my_task():
    pass

Wrong ⚠️

from celery import shared_task

@shared_task
def my_task():
    pass

IW08 use of timezone.activate or timezone.deactivate, use with timezone.override instead

Lint to avoid usage of timezone.activate() and instead use with timezone.override(). This is to avoid timezone leakage between different tests and features.

Correct

from django.utils import timezone
with timezone.override(zoneinfo.ZoneInfo(tzname)):
    <Rest of the code>

Wrong ⚠️

from django.utils import timezone
timezone.activate(zoneinfo.ZoneInfo(tzname))
<Rest of the code>
timezone.deactivate()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flake8_iw-0.0.17.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

flake8_iw-0.0.17-py2.py3-none-any.whl (10.0 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file flake8_iw-0.0.17.tar.gz.

File metadata

  • Download URL: flake8_iw-0.0.17.tar.gz
  • Upload date:
  • Size: 8.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for flake8_iw-0.0.17.tar.gz
Algorithm Hash digest
SHA256 77b68916dbddf788d1640d3777b305edcdc4d57a7c8d893e0a1453841fdcdb7b
MD5 26f879ca0412a49c8fba405b491c962b
BLAKE2b-256 dd25e29dc78efd582ac5f9e6706ab06af6a499ca2daa531bfb23416e0e623b39

See more details on using hashes here.

File details

Details for the file flake8_iw-0.0.17-py2.py3-none-any.whl.

File metadata

  • Download URL: flake8_iw-0.0.17-py2.py3-none-any.whl
  • Upload date:
  • Size: 10.0 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for flake8_iw-0.0.17-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 094a5f894578eab8dfbf4ce2056e0db5063f014184cb12be682f877c720023b1
MD5 474a8401065fad5690f71d445fd18e3b
BLAKE2b-256 c5e286484435936882700906bbf827ce1c68c356b46169cee6a8f4bf21796a8e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page