pytest-dev / pytest-django

A Django plugin for pytest.
https://pytest-django.readthedocs.io/
Other
1.33k stars 341 forks source link

pytest-django should handle MEDIA_ROOT #1126

Open JasonGrace2282 opened 6 days ago

JasonGrace2282 commented 6 days ago

Pytest django should redirect settings.MEDIA_ROOT automatically so that the state isn't shared between tests in the form of media. For compatibility with pytest-xdist, maybe each test run can have it's own folder, so that folders can get deleted without other tests running at the same time being effected (note: this would be io heavy)

JasonGrace2282 commented 6 days ago

For now I've implemented my own fixture

@pytest.fixture(autouse=True)
# the other fixtures come from pytest-xdist
# if not using that plugin just hash the current test
def media_setup(settings, worker_id: str, testrun_uid: str):
    # setup
    settings.MEDIA_ROOT = (
        Path(settings.BASE_DIR) / "test-media" / f"media-{worker_id}-{testrun_uid}"
    )

    # make sure no old/manual stuff added affects tests
    if settings.MEDIA_ROOT.exists():
        shutil.rmtree(settings.MEDIA_ROOT)
    settings.MEDIA_ROOT.mkdir(parents=True)

    yield
    # cleanup the media so it doesn't cause
    # problems elsewhere
    if settings.MEDIA_ROOT.exists():
        shutil.rmtree(settings.MEDIA_ROOT)