Skip to content

Commit 35e7697

Browse files
authored
Improve test ordering with Django test classes (#830)
1 parent 27379cb commit 35e7697

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

pytest_django/plugin.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,20 @@ def pytest_runtest_setup(item):
417417

418418
@pytest.hookimpl(tryfirst=True)
419419
def pytest_collection_modifyitems(items):
420+
# If Django is not configured we don't need to bother
421+
if not django_settings_is_configured():
422+
return
423+
424+
from django.test import TestCase, TransactionTestCase
425+
420426
def get_order_number(test):
427+
if hasattr(test, "cls") and test.cls:
428+
# Beware, TestCase is a subclass of TransactionTestCase
429+
if issubclass(test.cls, TestCase):
430+
return 0
431+
if issubclass(test.cls, TransactionTestCase):
432+
return 1
433+
421434
marker_db = test.get_closest_marker('django_db')
422435
if marker_db:
423436
transaction = validate_django_db(marker_db)[0]

tests/test_db_setup.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ def test_db_order(django_testdir):
3333
"""Test order in which tests are being executed."""
3434

3535
django_testdir.create_test_module('''
36+
from unittest import TestCase
3637
import pytest
38+
from django.test import SimpleTestCase, TestCase as DjangoTestCase, TransactionTestCase
3739
3840
from .app.models import Item
3941
@@ -50,14 +52,34 @@ def test_run_first_fixture(db):
5052
@pytest.mark.django_db
5153
def test_run_first_decorator():
5254
pass
55+
56+
class MyTestCase(TestCase):
57+
def test_run_last_test_case(self):
58+
pass
59+
60+
class MySimpleTestCase(SimpleTestCase):
61+
def test_run_last_simple_test_case(self):
62+
pass
63+
64+
class MyDjangoTestCase(DjangoTestCase):
65+
def test_run_first_django_test_case(self):
66+
pass
67+
68+
class MyTransactionTestCase(TransactionTestCase):
69+
def test_run_second_transaction_test_case(self):
70+
pass
5371
''')
5472
result = django_testdir.runpytest_subprocess('-v', '-s')
5573
assert result.ret == 0
5674
result.stdout.fnmatch_lines([
5775
"*test_run_first_fixture*",
5876
"*test_run_first_decorator*",
77+
"*test_run_first_django_test_case*",
5978
"*test_run_second_decorator*",
6079
"*test_run_second_fixture*",
80+
"*test_run_second_transaction_test_case*",
81+
"*test_run_last_test_case*",
82+
"*test_run_last_simple_test_case*",
6183
])
6284

6385

0 commit comments

Comments
 (0)