Skip to content

Commit 6d53426

Browse files
committed
pytest: better single unit test
1 parent 367aeef commit 6d53426

15 files changed

+185
-113
lines changed

manage.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
import os
3+
import sys
4+
from pathlib import Path
5+
6+
if __name__ == "__main__":
7+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.config.settings")
8+
try:
9+
from django.core.management import execute_from_command_line
10+
except ImportError:
11+
# The above import may fail for some other reason. Ensure that the
12+
# issue is really that Django is missing to avoid masking other
13+
# exceptions on Python 2.
14+
try:
15+
import django # noqa
16+
except ImportError:
17+
raise ImportError(
18+
"Couldn't import Django. Are you sure it's installed and "
19+
"available on your PYTHONPATH environment variable? Did you "
20+
"forget to activate a virtual environment?"
21+
)
22+
23+
raise
24+
25+
# This allows easy placement of apps within the interior
26+
# tests directory.
27+
current_path = Path(__file__).parent.resolve()
28+
sys.path.append(str(current_path) / "tests")
29+
30+
execute_from_command_line(sys.argv)

pyproject.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,11 @@ doc = [
7979
"mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0",
8080
"markdown-include"
8181
]
82+
83+
[tool.pytest.ini_options]
84+
DJANGO_SETTINGS_MODULE = "tests.config.settings"
85+
asyncio_mode = "auto"
86+
addopts = "--nomigrations"
87+
filterwarnings = [
88+
"ignore::django.utils.deprecation.RemovedInDjango50Warning",
89+
]

pytest.ini

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

tests/config/__init__.py

Whitespace-only changes.

tests/config/settings.py

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"""
2+
With these settings, tests run faster.
3+
"""
4+
5+
# Admin API auto-generation settings
6+
AUTO_ADMIN_ENABLED_ALL_APPS = True
7+
AUTO_ADMIN_INCLUDE_APPS = []
8+
AUTO_ADMIN_EXCLUDE_APPS = []
9+
10+
# Django Settings
11+
INSTALLED_APPS = (
12+
"django.contrib.admin",
13+
"django.contrib.auth",
14+
"django.contrib.contenttypes",
15+
"django.contrib.sessions",
16+
"django.contrib.sites",
17+
"django.contrib.staticfiles",
18+
"ninja_extra",
19+
"tests.demo_app",
20+
"easy",
21+
)
22+
23+
MIDDLEWARE = (
24+
"django.middleware.security.SecurityMiddleware",
25+
"django.contrib.sessions.middleware.SessionMiddleware",
26+
"django.middleware.common.CommonMiddleware",
27+
"django.middleware.csrf.CsrfViewMiddleware",
28+
"django.contrib.auth.middleware.AuthenticationMiddleware",
29+
"django.contrib.messages.middleware.MessageMiddleware",
30+
"django.middleware.clickjacking.XFrameOptionsMiddleware",
31+
)
32+
33+
USE_I18N = True
34+
USE_TZ = True
35+
LANGUAGE_CODE = "en-us"
36+
37+
STATIC_URL = "/static/"
38+
ROOT_URLCONF = "tests.demo_app.urls"
39+
40+
AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend",)
41+
42+
# DB
43+
DATABASES = {
44+
"default": {
45+
"ENGINE": "django.db.backends.sqlite3",
46+
"NAME": ":memory:",
47+
# "TEST": {
48+
# # this gets you in-memory sqlite for faster testing
49+
# "ENGINE": "django.db.backends.sqlite3",
50+
# },
51+
}
52+
}
53+
54+
# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner
55+
TEST_RUNNER = "django.test.runner.DiscoverRunner"
56+
57+
# CACHES
58+
# ------------------------------------------------------------------------------
59+
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
60+
CACHES = {
61+
"default": {
62+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
63+
"LOCATION": "",
64+
}
65+
}
66+
67+
# PASSWORDS
68+
# ------------------------------------------------------------------------------
69+
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
70+
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
71+
72+
# TEMPLATES
73+
# ------------------------------------------------------------------------------
74+
TEMPLATES = [
75+
{
76+
"BACKEND": "django.template.backends.django.DjangoTemplates",
77+
"DIRS": [],
78+
"APP_DIRS": True,
79+
"OPTIONS": {
80+
"context_processors": [
81+
"django.template.context_processors.debug",
82+
"django.template.context_processors.request",
83+
"django.contrib.auth.context_processors.auth",
84+
"django.contrib.messages.context_processors.messages",
85+
],
86+
},
87+
},
88+
]
89+
90+
# EMAIL
91+
# ------------------------------------------------------------------------------
92+
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
93+
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
94+
95+
96+
# Security
97+
ALLOWED_HOSTS = ["*"]
98+
SECRET_KEY = "not very secret in tests"
99+
100+
# Debug
101+
DEBUG_PROPAGATE_EXCEPTIONS = True

tests/conftest.py

Lines changed: 45 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,45 @@
1-
import django
2-
3-
4-
def pytest_configure(config):
5-
from django.conf import settings
6-
7-
settings.configure(
8-
ALLOWED_HOSTS=["*"],
9-
DEBUG_PROPAGATE_EXCEPTIONS=True,
10-
DATABASES={
11-
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
12-
},
13-
SITE_ID=1,
14-
SECRET_KEY="not very secret in tests",
15-
USE_I18N=True,
16-
STATIC_URL="/static/",
17-
ROOT_URLCONF="tests.demo_app.urls",
18-
TEMPLATES=[
19-
{
20-
"BACKEND": "django.template.backends.django.DjangoTemplates",
21-
"DIRS": [],
22-
"APP_DIRS": True,
23-
"OPTIONS": {
24-
"context_processors": [
25-
"django.template.context_processors.debug",
26-
"django.template.context_processors.request",
27-
"django.contrib.auth.context_processors.auth",
28-
"django.contrib.messages.context_processors.messages",
29-
],
30-
},
31-
},
32-
],
33-
MIDDLEWARE=(
34-
"django.middleware.security.SecurityMiddleware",
35-
"django.contrib.sessions.middleware.SessionMiddleware",
36-
"django.middleware.common.CommonMiddleware",
37-
"django.middleware.csrf.CsrfViewMiddleware",
38-
"django.contrib.auth.middleware.AuthenticationMiddleware",
39-
"django.contrib.messages.middleware.MessageMiddleware",
40-
"django.middleware.clickjacking.XFrameOptionsMiddleware",
41-
),
42-
INSTALLED_APPS=(
43-
"django.contrib.admin",
44-
"django.contrib.auth",
45-
"django.contrib.contenttypes",
46-
"django.contrib.sessions",
47-
"django.contrib.sites",
48-
"django.contrib.staticfiles",
49-
"ninja_extra",
50-
"tests.demo_app",
51-
"easy",
52-
),
53-
PASSWORD_HASHERS=("django.contrib.auth.hashers.MD5PasswordHasher",),
54-
AUTHENTICATION_BACKENDS=("django.contrib.auth.backends.ModelBackend",),
55-
LANGUAGE_CODE="en-us",
56-
TIME_ZONE="UTC",
57-
AUTO_ADMIN_ENABLED_ALL_APPS=True,
58-
AUTO_ADMIN_INCLUDE_APPS=[],
59-
AUTO_ADMIN_EXCLUDE_APPS=[],
60-
)
61-
62-
django.setup()
1+
import copy
2+
3+
import pytest
4+
from django.contrib.auth import get_user_model
5+
6+
from easy.controller.base import CrudAPIController
7+
from easy.testing import EasyTestClient
8+
from tests.demo_app.auth import JWTAuthAsync, jwt_auth_async
9+
from tests.demo_app.factories import UserFactory
10+
11+
User = get_user_model()
12+
13+
14+
@pytest.fixture(autouse=True)
15+
def media_storage(settings, tmpdir):
16+
settings.MEDIA_ROOT = tmpdir.strpath
17+
18+
19+
@pytest.fixture
20+
def user(db) -> User:
21+
return UserFactory()
22+
23+
24+
@pytest.fixture
25+
def easy_api_client(user) -> EasyTestClient:
26+
orig_func = copy.deepcopy(JWTAuthAsync.__call__)
27+
28+
async def mock_func(self, request):
29+
setattr(request, "user", user)
30+
return True
31+
32+
setattr(JWTAuthAsync, "__call__", mock_func)
33+
34+
def create_client(
35+
api: CrudAPIController,
36+
is_staff: bool = False,
37+
is_superuser: bool = False,
38+
):
39+
setattr(user, "is_staff", is_staff)
40+
setattr(user, "is_superuser", is_superuser)
41+
client = EasyTestClient(api, auth=jwt_auth_async)
42+
return client
43+
44+
yield create_client
45+
setattr(JWTAuthAsync, "__call__", orig_func)

tests/demo_app/conftest.py

Lines changed: 0 additions & 45 deletions
This file was deleted.
File renamed without changes.

tests/demo_app/test_async_api_permissions.py renamed to tests/test_async_api_permissions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
PermissionAPIController,
1111
)
1212
from tests.demo_app.models import Client, Event
13-
from tests.demo_app.test_async_other_apis import dummy_data
13+
from tests.test_async_other_apis import dummy_data
1414

1515

1616
@pytest.mark.skipif(django.VERSION < (3, 1), reason="requires django 3.1 or higher")
File renamed without changes.

0 commit comments

Comments
 (0)