Skip to content

Better order tests when mixing transactional tests and Django test classes #830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,20 @@ def pytest_runtest_setup(item):

@pytest.hookimpl(tryfirst=True)
def pytest_collection_modifyitems(items):
# If Django is not configured we don't need to bother
if not django_settings_is_configured():
return

from django.test import TestCase, TransactionTestCase

def get_order_number(test):
if hasattr(test, "cls") and test.cls:
# Beware, TestCase is a subclass of TransactionTestCase
if issubclass(test.cls, TestCase):
return 0
if issubclass(test.cls, TransactionTestCase):
return 1

marker_db = test.get_closest_marker('django_db')
if marker_db:
transaction = validate_django_db(marker_db)[0]
Expand Down
22 changes: 22 additions & 0 deletions tests/test_db_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def test_db_order(django_testdir):
"""Test order in which tests are being executed."""

django_testdir.create_test_module('''
from unittest import TestCase
import pytest
from django.test import SimpleTestCase, TestCase as DjangoTestCase, TransactionTestCase

from .app.models import Item

Expand All @@ -50,14 +52,34 @@ def test_run_first_fixture(db):
@pytest.mark.django_db
def test_run_first_decorator():
pass

class MyTestCase(TestCase):
def test_run_last_test_case(self):
pass

class MySimpleTestCase(SimpleTestCase):
def test_run_last_simple_test_case(self):
pass

class MyDjangoTestCase(DjangoTestCase):
def test_run_first_django_test_case(self):
pass

class MyTransactionTestCase(TransactionTestCase):
def test_run_second_transaction_test_case(self):
pass
''')
result = django_testdir.runpytest_subprocess('-v', '-s')
assert result.ret == 0
result.stdout.fnmatch_lines([
"*test_run_first_fixture*",
"*test_run_first_decorator*",
"*test_run_first_django_test_case*",
"*test_run_second_decorator*",
"*test_run_second_fixture*",
"*test_run_second_transaction_test_case*",
"*test_run_last_test_case*",
"*test_run_last_simple_test_case*",
])


Expand Down