pytest-dev / pytest-dev/pytest-django

Suggestion: module-level fixtures for populating a database

Open
#1,145 0 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

I had a lot of trouble figuring out how to set up my tests given that various tests needed different things in the database, and some tests used live_server which removes all data from the database at the end of the particular test (this prevented me from using a session level fixture, since the live_server test would get rid of all the data that the session level fixture adds to the db)

I also didn't want tests to interfere with each other, and I finally came up with the following solution:

from django.db import transaction 
import pytest

@pytest.fixture(scope='module')
def self_restoring_test_setup(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        with transaction.atomic():
            sid = transaction.savepoint()
            yield
            transaction.savepoint_rollback(sid)

However, this feels like something the plugin should provide. I tried using various fixtures like db and transactional_db, but I kept getting issues with ScopeMismatch because they are scoped at the default function level.

I also tried various things to get the live_server tests to roll back the database to where it had been before with serialized_rollback and such things, but they didn't work. Actually the solution above could probably be applied to a live_server test just as effectively.

I'm not entirely sure how a fixture like the above would fit within this plugin but I hope you find it helpful.

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 comparing the module-scoped self_restoring_test_setup example with the plugin's existing db, transactional_db, django_db_setup, django_db_blocker, live_server, and serialized_rollback fixtures. Reproduce the ScopeMismatch and live_server cleanup behavior described in the issue, then determine the expected module-level fixture behavior and verify that data is restored after the module's tests complete.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 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.