Skip to content

Commit fcd4ab3

Browse files
committed
Switch mypy to pyproject.toml, use stricter config
1 parent f7e0058 commit fcd4ab3

File tree

8 files changed

+71
-58
lines changed

8 files changed

+71
-58
lines changed

pyproject.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,21 @@ build-backend = "setuptools.build_meta"
88

99
[tool.setuptools_scm]
1010
write_to = "pytest_django/_version.py"
11+
12+
[tool.mypy]
13+
strict = true
14+
disallow_incomplete_defs = false
15+
disallow_untyped_defs = false
16+
disallow_subclassing_any = false
17+
files = [
18+
"pytest_django",
19+
"pytest_django_test",
20+
"tests",
21+
]
22+
[[tool.mypy.overrides]]
23+
module = [
24+
"django.*",
25+
"configurations.*",
26+
"psycopg2cffi.*",
27+
]
28+
ignore_missing_imports = true

pytest_django/fixtures.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,14 @@ def django_db_use_migrations(request: pytest.FixtureRequest) -> bool:
8989

9090
@pytest.fixture(scope="session")
9191
def django_db_keepdb(request: pytest.FixtureRequest) -> bool:
92-
return request.config.getvalue("reuse_db")
92+
reuse_db: bool = request.config.getvalue("reuse_db")
93+
return reuse_db
9394

9495

9596
@pytest.fixture(scope="session")
9697
def django_db_createdb(request: pytest.FixtureRequest) -> bool:
97-
return request.config.getvalue("create_db")
98+
create_db: bool = request.config.getvalue("create_db")
99+
return create_db
98100

99101

100102
@pytest.fixture(scope="session")
@@ -407,7 +409,8 @@ def django_user_model(db: None):
407409
@pytest.fixture()
408410
def django_username_field(django_user_model) -> str:
409411
"""The fieldname for the username used with Django's user model."""
410-
return django_user_model.USERNAME_FIELD
412+
field: str = django_user_model.USERNAME_FIELD
413+
return field
411414

412415

413416
@pytest.fixture()

pytest_django/lazy_django.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,13 @@ def django_settings_is_configured() -> bool:
2525

2626
if not ret and "django.conf" in sys.modules:
2727
django_conf: Any = sys.modules["django.conf"]
28-
return django_conf.settings.configured
28+
ret = django_conf.settings.configured
2929

3030
return ret
3131

3232

3333
def get_django_version() -> Tuple[int, int, int, str, int]:
3434
import django
3535

36-
return django.VERSION
36+
version: Tuple[int, int, int, str, int] = django.VERSION
37+
return version

pytest_django/plugin.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -491,14 +491,14 @@ def non_debugging_runtest(self) -> None:
491491
self._testcase(result=self)
492492

493493
try:
494-
TestCaseFunction.runtest = non_debugging_runtest # type: ignore[assignment]
494+
TestCaseFunction.runtest = non_debugging_runtest # type: ignore[method-assign]
495495

496496
request.getfixturevalue("django_db_setup")
497497

498498
with django_db_blocker.unblock():
499499
yield
500500
finally:
501-
TestCaseFunction.runtest = original_runtest # type: ignore[assignment]
501+
TestCaseFunction.runtest = original_runtest # type: ignore[method-assign]
502502

503503

504504
@pytest.fixture(scope="function", autouse=True)
@@ -521,7 +521,7 @@ def mailoutbox(
521521

522522
from django.core import mail
523523

524-
return mail.outbox
524+
return mail.outbox # type: ignore[no-any-return]
525525

526526

527527
@pytest.fixture(scope="function")
@@ -589,7 +589,7 @@ def __contains__(self, key: str) -> bool:
589589
return key == "%s"
590590

591591
@staticmethod
592-
def _get_origin():
592+
def _get_origin() -> Optional[str]:
593593
stack = inspect.stack()
594594

595595
# Try to use topmost `self.origin` first (Django 1.9+, and with
@@ -598,10 +598,11 @@ def _get_origin():
598598
func = f[3]
599599
if func == "render":
600600
frame = f[0]
601+
origin: Optional[str]
601602
try:
602603
origin = frame.f_locals["self"].origin
603604
except (AttributeError, KeyError):
604-
continue
605+
origin = None
605606
if origin is not None:
606607
return origin
607608

@@ -620,7 +621,9 @@ def _get_origin():
620621
# ``django.template.base.Template``
621622
template = f_locals["self"]
622623
if isinstance(template, Template):
623-
return template.name
624+
name: str = template.name
625+
return name
626+
return None
624627

625628
def __mod__(self, var: str) -> str:
626629
origin = self._get_origin()
@@ -704,8 +707,8 @@ class _DatabaseBlocker:
704707
This is the object returned by django_db_blocker.
705708
"""
706709

707-
def __init__(self):
708-
self._history = []
710+
def __init__(self) -> None:
711+
self._history = [] # type: ignore[var-annotated]
709712
self._real_ensure_connection = None
710713

711714
@property

pytest_django_test/db_helpers.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import sqlite3
33
import subprocess
4+
from typing import Mapping, Optional
45

56
import pytest
67
from django.conf import settings
@@ -10,8 +11,8 @@
1011
# Construct names for the "inner" database used in runpytest tests
1112
_settings = settings.DATABASES["default"]
1213

13-
DB_NAME = _settings["NAME"]
14-
TEST_DB_NAME = _settings["TEST"]["NAME"]
14+
DB_NAME: str = _settings["NAME"]
15+
TEST_DB_NAME: str = _settings["TEST"]["NAME"]
1516

1617
if _settings["ENGINE"] == "django.db.backends.sqlite3" and TEST_DB_NAME is None:
1718
TEST_DB_NAME = ":memory:"
@@ -31,18 +32,19 @@
3132
SECOND_TEST_DB_NAME = TEST_DB_NAME + '_second' if DB_NAME is not None else None
3233

3334

34-
def get_db_engine():
35-
return _settings["ENGINE"].split(".")[-1]
35+
def get_db_engine() -> str:
36+
db_engine: str = _settings["ENGINE"].split(".")[-1]
37+
return db_engine
3638

3739

3840
class CmdResult:
39-
def __init__(self, status_code, std_out, std_err):
41+
def __init__(self, status_code: int, std_out: bytes, std_err: bytes) -> None:
4042
self.status_code = status_code
4143
self.std_out = std_out
4244
self.std_err = std_err
4345

4446

45-
def run_cmd(*args, env=None):
47+
def run_cmd(*args: str, env: Optional[Mapping[str, str]] = None) -> CmdResult:
4648
r = subprocess.Popen(
4749
args,
4850
stdout=subprocess.PIPE,
@@ -54,7 +56,7 @@ def run_cmd(*args, env=None):
5456
return CmdResult(ret, stdoutdata, stderrdata)
5557

5658

57-
def run_psql(*args):
59+
def run_psql(*args: str) -> CmdResult:
5860
env = {}
5961
user = _settings.get("USER")
6062
if user: # pragma: no branch
@@ -68,7 +70,7 @@ def run_psql(*args):
6870
return run_cmd("psql", *args, env=env)
6971

7072

71-
def run_mysql(*args):
73+
def run_mysql(*args: str) -> CmdResult:
7274
user = _settings.get("USER")
7375
if user: # pragma: no branch
7476
args = ("-u", user, *args)
@@ -82,22 +84,22 @@ def run_mysql(*args):
8284
return run_cmd("mysql", *args)
8385

8486

85-
def skip_if_sqlite_in_memory():
87+
def skip_if_sqlite_in_memory() -> None:
8688
if (
8789
_settings["ENGINE"] == "django.db.backends.sqlite3"
8890
and _settings["TEST"]["NAME"] is None
8991
):
9092
pytest.skip("Do not test db reuse since database does not support it")
9193

9294

93-
def _get_db_name(db_suffix=None):
95+
def _get_db_name(db_suffix: Optional[str] = None) -> str:
9496
name = TEST_DB_NAME
9597
if db_suffix:
9698
name = f"{name}_{db_suffix}"
9799
return name
98100

99101

100-
def drop_database(db_suffix=None):
102+
def drop_database(db_suffix: Optional[str] = None) -> None:
101103
name = _get_db_name(db_suffix)
102104
db_engine = get_db_engine()
103105

@@ -119,7 +121,7 @@ def drop_database(db_suffix=None):
119121
os.unlink(name)
120122

121123

122-
def db_exists(db_suffix=None):
124+
def db_exists(db_suffix: Optional[str] = None) -> bool:
123125
name = _get_db_name(db_suffix)
124126
db_engine = get_db_engine()
125127

@@ -137,7 +139,7 @@ def db_exists(db_suffix=None):
137139
return os.path.exists(name)
138140

139141

140-
def mark_database():
142+
def mark_database() -> None:
141143
db_engine = get_db_engine()
142144

143145
if db_engine == "postgresql":
@@ -162,7 +164,7 @@ def mark_database():
162164
conn.close()
163165

164166

165-
def mark_exists():
167+
def mark_exists() -> bool:
166168
db_engine = get_db_engine()
167169

168170
if db_engine == "postgresql":

setup.cfg

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -75,21 +75,3 @@ line_length = 79
7575
multi_line_output = 5
7676
lines_after_imports = 2
7777
extend_skip = pytest_django/_version.py
78-
79-
[mypy]
80-
check_untyped_defs = True
81-
disallow_any_generics = True
82-
no_implicit_optional = True
83-
show_error_codes = True
84-
strict_equality = True
85-
warn_redundant_casts = True
86-
warn_unreachable = True
87-
warn_unused_configs = True
88-
no_implicit_reexport = True
89-
90-
[mypy-django.*]
91-
ignore_missing_imports = True
92-
[mypy-configurations.*]
93-
ignore_missing_imports = True
94-
[mypy-psycopg2cffi.*]
95-
ignore_missing_imports = True

tests/test_database.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88

99
def db_supports_reset_sequences() -> bool:
1010
"""Return if the current db engine supports `reset_sequences`."""
11-
return (
11+
ret: bool = (
1212
connection.features.supports_transactions
1313
and connection.features.supports_sequence_reset
1414
)
15+
return ret
1516

1617

1718
def test_noaccess() -> None:
@@ -57,13 +58,13 @@ class TestDatabaseFixtures:
5758
])
5859
def all_dbs(self, request: pytest.FixtureRequest) -> None:
5960
if request.param == "django_db_reset_sequences":
60-
return request.getfixturevalue("django_db_reset_sequences")
61+
request.getfixturevalue("django_db_reset_sequences")
6162
elif request.param == "transactional_db":
62-
return request.getfixturevalue("transactional_db")
63+
request.getfixturevalue("transactional_db")
6364
elif request.param == "db":
64-
return request.getfixturevalue("db")
65+
request.getfixturevalue("db")
6566
elif request.param == "django_db_serialized_rollback":
66-
return request.getfixturevalue("django_db_serialized_rollback")
67+
request.getfixturevalue("django_db_serialized_rollback")
6768
else:
6869
assert False # pragma: no cover
6970

tests/test_fixtures.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def test_admin_user_no_db_marker(admin_user, django_user_model) -> None:
8181
assert isinstance(admin_user, django_user_model)
8282

8383

84-
def test_rf(rf) -> None:
84+
def test_rf(rf: RequestFactory) -> None:
8585
assert isinstance(rf, RequestFactory)
8686

8787

@@ -336,7 +336,7 @@ def test_deleted_again(self, settings) -> None:
336336
def test_signals(self, settings) -> None:
337337
result = []
338338

339-
def assert_signal(signal, sender, setting, value, enter):
339+
def assert_signal(signal, sender, setting, value, enter) -> None:
340340
result.append((setting, value, enter))
341341

342342
from django.test.signals import setting_changed
@@ -463,25 +463,28 @@ def test_fixture_transactional_db(self, transactional_db: None, live_server) ->
463463
assert force_str(response_data) == "Item count: 1"
464464

465465
@pytest.fixture
466-
def item(self) -> None:
466+
def item(self) -> Item:
467467
# This has not requested database access explicitly, but the
468468
# live_server fixture auto-uses the transactional_db fixture.
469-
Item.objects.create(name="foo")
469+
item: Item = Item.objects.create(name="foo")
470+
return item
470471

471-
def test_item(self, item, live_server) -> None:
472+
def test_item(self, item: Item, live_server) -> None:
472473
pass
473474

474475
@pytest.fixture
475476
def item_db(self, db: None) -> Item:
476-
return Item.objects.create(name="foo")
477+
item: Item = Item.objects.create(name="foo")
478+
return item
477479

478480
def test_item_db(self, item_db: Item, live_server) -> None:
479481
response_data = urlopen(live_server + "/item_count/").read()
480482
assert force_str(response_data) == "Item count: 1"
481483

482484
@pytest.fixture
483485
def item_transactional_db(self, transactional_db: None) -> Item:
484-
return Item.objects.create(name="foo")
486+
item: Item = Item.objects.create(name="foo")
487+
return item
485488

486489
def test_item_transactional_db(self, item_transactional_db: Item, live_server) -> None:
487490
response_data = urlopen(live_server + "/item_count/").read()
@@ -570,7 +573,7 @@ def test_with_live_server(live_server):
570573
ROOT_URLCONF = 'tpkg.app.urls'
571574
"""
572575
)
573-
def test_custom_user_model(django_pytester: DjangoPytester, username_field) -> None:
576+
def test_custom_user_model(django_pytester: DjangoPytester, username_field: str) -> None:
574577
django_pytester.create_app_file(
575578
f"""
576579
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

0 commit comments

Comments
 (0)