Skip to content

Commit 57d0bc0

Browse files
Switch to explicit testing style (#199)
1 parent 88b318f commit 57d0bc0

File tree

9 files changed

+150
-200
lines changed

9 files changed

+150
-200
lines changed

Makefile

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
venv = venv
22
bin = ${venv}/bin/
33
pysources = src/ test_project/ tests/
4-
pysources_mypy = src/ test_project/ tests/conftest.py
54

65
build:
76
${python} setup.py sdist bdist_wheel
@@ -11,7 +10,7 @@ build:
1110
check:
1211
${bin}black --check --diff --target-version=py36 ${pysources}
1312
${bin}flake8 ${pysources}
14-
${bin}mypy ${pysources_mypy}
13+
${bin}mypy ${pysources}
1514
${bin}isort --check --diff ${pysources}
1615
make migrations-check
1716

tests/compat.py

Lines changed: 0 additions & 12 deletions
This file was deleted.

tests/conftest.py

Lines changed: 0 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
1-
import typing
21
from pathlib import Path
32

43
import dj_database_url
54
import dotenv
6-
import pytest
75
from django.conf import settings
8-
from django.http import HttpRequest
9-
from django.test import override_settings
10-
11-
from .compat import nullcontext
12-
13-
if typing.TYPE_CHECKING:
14-
from django.contrib.auth.base_user import AbstractBaseUser
156

167

178
def pytest_configure() -> None:
@@ -58,85 +49,3 @@ def pytest_configure() -> None:
5849
},
5950
}
6051
)
61-
62-
63-
def _create_user() -> "AbstractBaseUser":
64-
from django.contrib.auth import get_user_model
65-
66-
User = get_user_model()
67-
return User.objects.create_user(username="foo", password="bar")
68-
69-
70-
@pytest.fixture(
71-
name="key_header_config",
72-
params=[
73-
{"header": "HTTP_AUTHORIZATION", "default": "Api-Key {key}"},
74-
{
75-
"header": "HTTP_X_API_KEY",
76-
"default": "{key}",
77-
"set_custom_header_setting": True,
78-
},
79-
],
80-
)
81-
def fixture_key_header_config(request: typing.Any) -> typing.Iterator[dict]:
82-
config: dict = request.param
83-
84-
ctx: typing.ContextManager[None]
85-
if config.get("set_custom_header_setting"):
86-
ctx = override_settings(API_KEY_CUSTOM_HEADER=config["header"]) # type: ignore
87-
else:
88-
ctx = nullcontext()
89-
90-
with ctx:
91-
yield config
92-
93-
94-
@pytest.fixture(name="build_create_request")
95-
def fixture_build_create_request(key_header_config: dict) -> typing.Callable:
96-
from rest_framework.test import APIRequestFactory, force_authenticate
97-
98-
from rest_framework_api_key.models import AbstractAPIKey
99-
100-
def build_create_request(model: typing.Type[AbstractAPIKey]) -> typing.Callable:
101-
request_factory = APIRequestFactory()
102-
103-
_MISSING = object()
104-
105-
def create_request(
106-
authenticated: bool = False,
107-
**kwargs: typing.Any,
108-
) -> HttpRequest:
109-
headers = {}
110-
111-
authorization = kwargs.pop("authorization", _MISSING)
112-
113-
if authorization is not None:
114-
kwargs.setdefault("name", "test")
115-
_, key = model.objects.create_key(**kwargs)
116-
117-
if callable(authorization):
118-
authorization = authorization(key)
119-
120-
if authorization is _MISSING:
121-
authorization = key_header_config["default"]
122-
123-
headers[key_header_config["header"]] = authorization.format(key=key)
124-
125-
request = request_factory.get("/test/", **headers)
126-
127-
if authenticated:
128-
user = _create_user()
129-
force_authenticate(request, user)
130-
131-
return request
132-
133-
return create_request
134-
135-
return build_create_request
136-
137-
138-
@pytest.fixture(name="create_request")
139-
def fixture_create_request(build_create_request: typing.Callable) -> typing.Callable:
140-
from rest_framework_api_key.models import APIKey
141-
142-
return build_create_request(APIKey)

tests/test_compatibility.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
@pytest.mark.skipif(
88
django.VERSION < (3, 2), reason="app config is automatically defined by django"
99
)
10-
def test_app_config_not_defined():
10+
def test_app_config_not_defined() -> None:
1111
assert hasattr(rest_framework_api_key, "default_app_config") is False
1212

1313

1414
@pytest.mark.skipif(
1515
django.VERSION >= (3, 2), reason="app config is not automatically defined by django"
1616
)
17-
def test_app_config_defined():
17+
def test_app_config_defined() -> None:
1818
assert hasattr(rest_framework_api_key, "default_app_config") is True

tests/test_model.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import datetime as dt
12
import string
23

34
import pytest
@@ -12,7 +13,7 @@
1213
pytestmark = pytest.mark.django_db
1314

1415

15-
def test_key_generation():
16+
def test_key_generation() -> None:
1617
api_key, generated_key = APIKey.objects.create_key(name="test")
1718
prefix = api_key.prefix
1819
hashed_key = api_key.hashed_key
@@ -29,12 +30,12 @@ def test_key_generation():
2930
assert api_key.is_valid(hashed_key) is False
3031

3132

32-
def test_name_is_required():
33+
def test_name_is_required() -> None:
3334
with pytest.raises(IntegrityError):
3435
APIKey.objects.create()
3536

3637

37-
def test_cannot_unrevoke():
38+
def test_cannot_unrevoke() -> None:
3839
api_key, _ = APIKey.objects.create_key(name="test", revoked=True)
3940

4041
# Try to unrevoke the API key programmatically.
@@ -51,12 +52,12 @@ def test_cannot_unrevoke():
5152
"expiry_date, has_expired",
5253
[(None, False), (NOW, True), (TOMORROW, False), (YESTERDAY, True)],
5354
)
54-
def test_has_expired(expiry_date, has_expired):
55+
def test_has_expired(expiry_date: dt.datetime, has_expired: bool) -> None:
5556
api_key, _ = APIKey.objects.create_key(name="test", expiry_date=expiry_date)
5657
assert api_key.has_expired is has_expired
5758

5859

59-
def test_custom_api_key_model():
60+
def test_custom_api_key_model() -> None:
6061
hero = Hero.objects.create()
6162
hero_api_key, generated_key = HeroAPIKey.objects.create_key(name="test", hero=hero)
6263
assert hero_api_key.is_valid(generated_key)
@@ -65,28 +66,28 @@ def test_custom_api_key_model():
6566

6667

6768
@pytest.mark.django_db
68-
def test_api_key_manager_get_from_key():
69+
def test_api_key_manager_get_from_key() -> None:
6970
api_key, generated_key = APIKey.objects.create_key(name="test")
7071
retrieved_key = APIKey.objects.get_from_key(generated_key)
7172
assert retrieved_key == api_key
7273

7374

7475
@pytest.mark.django_db
75-
def test_api_key_manager_get_from_key_missing_key():
76+
def test_api_key_manager_get_from_key_missing_key() -> None:
7677
with pytest.raises(APIKey.DoesNotExist):
7778
APIKey.objects.get_from_key("foobar")
7879

7980

8081
@pytest.mark.django_db
81-
def test_api_key_manager_get_from_key_invalid_key():
82+
def test_api_key_manager_get_from_key_invalid_key() -> None:
8283
api_key, generated_key = APIKey.objects.create_key(name="test")
8384
prefix, _, _ = generated_key.partition(".")
8485
invalid_key = f"{prefix}.foobar"
8586
with pytest.raises(APIKey.DoesNotExist):
8687
APIKey.objects.get_from_key(invalid_key)
8788

8889

89-
def test_api_key_str():
90+
def test_api_key_str() -> None:
9091
_, generated_key = APIKey.objects.create_key(name="test")
9192
retrieved_key = APIKey.objects.get_from_key(generated_key)
9293
assert str(retrieved_key) == "test"

0 commit comments

Comments
 (0)