1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
|
import os
import sys
import pytest
from django.contrib.sites import models as site_models
from django.contrib.sites.models import Site
from django.core import mail
from django.db import connection
from django.test import TestCase
from .helpers import DjangoPytester
from pytest_django_test.app.models import Item
# It doesn't matter which order all the _again methods are run, we just need
# to check the environment remains constant.
# This is possible with some of the pytester magic, but this is the lazy way
# to do it.
@pytest.mark.parametrize("subject", ["subject1", "subject2"])
def test_autoclear_mailbox(subject: str) -> None:
assert len(mail.outbox) == 0
mail.send_mail(subject, "body", "from@example.com", ["to@example.com"])
assert len(mail.outbox) == 1
m = mail.outbox[0]
assert m.subject == subject
assert m.body == "body"
assert m.from_email == "from@example.com"
assert m.to == ["to@example.com"]
class TestDirectAccessWorksForDjangoTestCase(TestCase):
def _do_test(self) -> None:
assert len(mail.outbox) == 0
mail.send_mail("subject", "body", "from@example.com", ["to@example.com"])
assert len(mail.outbox) == 1
def test_one(self) -> None:
self._do_test()
def test_two(self) -> None:
self._do_test()
@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
ROOT_URLCONF = 'tpkg.app.urls'
"""
)
def test_invalid_template_variable(django_pytester: DjangoPytester) -> None:
django_pytester.create_app_file(
"""
from django.urls import path
from tpkg.app import views
urlpatterns = [path('invalid_template/', views.invalid_template)]
""",
"urls.py",
)
django_pytester.create_app_file(
"""
from django.shortcuts import render
def invalid_template(request):
return render(request, 'invalid_template.html', {})
""",
"views.py",
)
django_pytester.create_app_file(
"<div>{{ invalid_var }}</div>", "templates/invalid_template_base.html"
)
django_pytester.create_app_file(
"{% include 'invalid_template_base.html' %}", "templates/invalid_template.html"
)
django_pytester.create_test_module(
"""
import pytest
def test_for_invalid_template(client):
client.get('/invalid_template/')
@pytest.mark.ignore_template_errors
def test_ignore(client):
client.get('/invalid_template/')
"""
)
result = django_pytester.runpytest_subprocess("-s", "--fail-on-template-vars")
origin = "'*/tpkg/app/templates/invalid_template_base.html'"
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py F.*",
f"E * Failed: Undefined template variable 'invalid_var' in {origin}",
]
)
@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
"""
)
def test_invalid_template_variable_marker_cleanup(django_pytester: DjangoPytester) -> None:
django_pytester.create_app_file(
"<div>{{ invalid_var }}</div>", "templates/invalid_template_base.html"
)
django_pytester.create_app_file(
"{% include 'invalid_template_base.html' %}", "templates/invalid_template.html"
)
django_pytester.create_test_module(
"""
from django.template.loader import render_to_string
import pytest
@pytest.mark.ignore_template_errors
def test_ignore(client):
render_to_string('invalid_template.html')
def test_for_invalid_template(client):
render_to_string('invalid_template.html')
"""
)
result = django_pytester.runpytest_subprocess("-s", "--fail-on-template-vars")
origin = "'*/tpkg/app/templates/invalid_template_base.html'"
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py .F*",
f"E * Failed: Undefined template variable 'invalid_var' in {origin}",
]
)
@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "Something clever"
"""
)
def test_invalid_template_variable_behaves_normally_when_ignored(
django_pytester: DjangoPytester,
) -> None:
django_pytester.create_app_file(
"<div>{{ invalid_var }}</div>", "templates/invalid_template_base.html"
)
django_pytester.create_app_file(
"{% include 'invalid_template_base.html' %}", "templates/invalid_template.html"
)
django_pytester.create_test_module(
"""
from django.template.loader import render_to_string
import pytest
@pytest.mark.ignore_template_errors
def test_ignore(client):
assert render_to_string('invalid_template.html') == "<div>Something clever</div>"
def test_for_invalid_template(client):
render_to_string('invalid_template.html')
"""
)
result = django_pytester.runpytest_subprocess("-s", "--fail-on-template-vars")
origin = "'*/tpkg/app/templates/invalid_template_base.html'"
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py .F*",
f"E * Failed: Undefined template variable 'invalid_var' in {origin}",
]
)
@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
ROOT_URLCONF = 'tpkg.app.urls'
"""
)
def test_invalid_template_with_default_if_none(django_pytester: DjangoPytester) -> None:
django_pytester.create_app_file(
"""
<div>{{ data.empty|default:'d' }}</div>
<div>{{ data.none|default:'d' }}</div>
<div>{{ data.empty|default_if_none:'d' }}</div>
<div>{{ data.none|default_if_none:'d' }}</div>
<div>{{ data.missing|default_if_none:'d' }}</div>
""",
"templates/the_template.html",
)
django_pytester.create_test_module(
"""
def test_for_invalid_template():
from django.shortcuts import render
render(
request=None,
template_name='the_template.html',
context={'data': {'empty': '', 'none': None}},
)
"""
)
result = django_pytester.runpytest_subprocess("--fail-on-template-vars")
result.stdout.fnmatch_lines(
[
"tpkg/test_the_test.py F",
"E * Failed: Undefined template variable 'data.missing' in *the_template.html'",
]
)
@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
ROOT_URLCONF = 'tpkg.app.urls'
"""
)
def test_invalid_template_variable_opt_in(django_pytester: DjangoPytester) -> None:
django_pytester.create_app_file(
"""
from django.urls import path
from tpkg.app import views
urlpatterns = [path('invalid_template', views.invalid_template)]
""",
"urls.py",
)
django_pytester.create_app_file(
"""
from django.shortcuts import render
def invalid_template(request):
return render(request, 'invalid_template.html', {})
""",
"views.py",
)
django_pytester.create_app_file(
"<div>{{ invalid_var }}</div>", "templates/invalid_template.html"
)
django_pytester.create_test_module(
"""
import pytest
def test_for_invalid_template(client):
client.get('/invalid_template/')
@pytest.mark.ignore_template_errors
def test_ignore(client):
client.get('/invalid_template/')
"""
)
result = django_pytester.runpytest_subprocess("-s")
result.stdout.fnmatch_lines_random(["tpkg/test_the_test.py ..*"])
@pytest.mark.django_db
def test_database_rollback() -> None:
assert Item.objects.count() == 0
Item.objects.create(name="blah")
assert Item.objects.count() == 1
@pytest.mark.django_db
def test_database_rollback_again() -> None:
test_database_rollback()
@pytest.mark.django_db
def test_database_name() -> None:
dirname, name = os.path.split(connection.settings_dict["NAME"])
assert "file:memorydb" in name or name == ":memory:" or name.startswith("test_")
def test_database_noaccess() -> None:
with pytest.raises(RuntimeError):
Item.objects.count()
class TestrunnerVerbosity:
"""Test that Django's code to setup and teardown the databases uses
pytest's verbosity level."""
@pytest.fixture
def pytester(self, django_pytester: DjangoPytester) -> pytest.Pytester:
django_pytester.create_test_module(
"""
import pytest
@pytest.mark.django_db
def test_inner_testrunner():
pass
"""
)
return django_pytester
def test_default(self, pytester: pytest.Pytester) -> None:
"""Not verbose by default."""
result = pytester.runpytest_subprocess("-s")
result.stdout.fnmatch_lines(["tpkg/test_the_test.py .*"])
def test_vq_verbosity_0(self, pytester: pytest.Pytester) -> None:
"""-v and -q results in verbosity 0."""
result = pytester.runpytest_subprocess("-s", "-v", "-q")
result.stdout.fnmatch_lines(["tpkg/test_the_test.py .*"])
def test_verbose_with_v(self, pytester: pytest.Pytester) -> None:
"""Verbose output with '-v'."""
result = pytester.runpytest_subprocess("-s", "-v")
result.stdout.fnmatch_lines_random(["tpkg/test_the_test.py:*", "*PASSED*"])
result.stderr.fnmatch_lines(["*Destroying test database for alias 'default'*"])
def test_more_verbose_with_vv(self, pytester: pytest.Pytester) -> None:
"""More verbose output with '-v -v'."""
result = pytester.runpytest_subprocess("-s", "-v", "-v")
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py:*",
"*Operations to perform:*",
"*Apply all migrations:*",
"*PASSED*",
]
)
result.stderr.fnmatch_lines(
[
"*Creating test database for alias*",
"*Destroying test database for alias 'default'*",
]
)
def test_more_verbose_with_vv_and_reusedb(self, pytester: pytest.Pytester) -> None:
"""More verbose output with '-v -v', and --create-db."""
result = pytester.runpytest_subprocess("-s", "-v", "-v", "--create-db")
result.stdout.fnmatch_lines(["tpkg/test_the_test.py:*", "*PASSED*"])
result.stderr.fnmatch_lines(["*Creating test database for alias*"])
assert "*Destroying test database for alias 'default' ('*')...*" not in result.stderr.str()
@pytest.mark.django_db
@pytest.mark.parametrize("site_name", ["site1", "site2"])
def test_clear_site_cache(site_name: str, rf, monkeypatch: pytest.MonkeyPatch) -> None:
request = rf.get("/")
monkeypatch.setattr(request, "get_host", lambda: "foo.com")
Site.objects.create(domain="foo.com", name=site_name)
assert Site.objects.get_current(request=request).name == site_name
@pytest.mark.django_db
@pytest.mark.parametrize("site_name", ["site1", "site2"])
def test_clear_site_cache_check_site_cache_size(site_name: str, settings) -> None:
assert len(site_models.SITE_CACHE) == 0
site = Site.objects.create(domain="foo.com", name=site_name)
settings.SITE_ID = site.id
assert Site.objects.get_current() == site
assert len(site_models.SITE_CACHE) == 1
@pytest.mark.django_project(
project_root="django_project_root",
create_manage_py=True,
extra_settings="""
TEST_RUNNER = 'pytest_django.runner.TestRunner'
""",
)
def test_manage_test_runner(django_pytester: DjangoPytester) -> None:
django_pytester.create_test_module(
"""
import pytest
@pytest.mark.django_db
def test_inner_testrunner():
pass
"""
)
result = django_pytester.run(*[sys.executable, "django_project_root/manage.py", "test"])
assert "1 passed" in "\n".join(result.outlines)
@pytest.mark.django_project(
project_root="django_project_root",
create_manage_py=True,
)
def test_manage_test_runner_without(django_pytester: DjangoPytester) -> None:
django_pytester.create_test_module(
"""
import pytest
@pytest.mark.django_db
def test_inner_testrunner():
pass
"""
)
result = django_pytester.run(*[sys.executable, "django_project_root/manage.py", "test"])
assert "Found 0 test(s)." in "\n".join(result.outlines)
|