pytest-dev / pytest-dev/pytest-django

Database fixtures are run when they shouldn't be for SimpleTestCase unit tests

Open
#472 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

pytest-django uses a function internally for checking if a test is a Django test case class, named is_django_unittest. This class is used to determine if database setup is needed or not. This is implemented with an issubclass check for SimpleTestCase. However, the Django documentation states the following:

SimpleTestCase disallows database queries by default. This helps to avoid executing write queries which will affect other tests since each SimpleTestCase test isn’t run in a transaction.

See here: https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.SimpleTestCase.allow_database_queries

If you write a unit test in a TestCase class which inherits SimpleTestCase, where allow_database_queries is set to False, which is the default, you will hit problems when you have a fixture defined like so in your conftest.py file:

@pytest.fixture(autouse=True)
def setup_db_tenant(db):
    # ... Create something in the database here ...

The fixture will be run, and database access will be done, and then Django will print the following error message: (Where YourClassNameHere is whatever your class name is for your test case.)

AssertionError: Database queries aren't allowed in SimpleTestCase. Either use TestCase
or TransactionTestCase to ensure proper test isolation or set 
YourClassNameHere.allow_database_queries to True to silence this failure.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the is_django_unittest check and the database setup path described in the issue. Reproduce the autouse fixture with a SimpleTestCase whose allow_database_queries remains false, then verify that database fixtures are not run and the test no longer raises Django's database-query assertion.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
databases, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.