How to override a pytest fixture calling the original in pytest 4

后端 未结 2 1814
無奈伤痛
無奈伤痛 2021-02-10 02:59

I am defining a pytest fixture that to overrides the django_db_setup fixture.

The change I have sets up additional teardown for safety, as there are integration tests th

2条回答
  •  忘了有多久
    2021-02-10 03:51

    There is a simple trick to redefine a fixture with a custom impl. Just declare a fixture with the same name and signature in your local test code (I usually do it in the conftest.py in project root). Examples:

    "Inheritance"

    # conftest.py
    
    import pytest
    
    
    @pytest.fixture(scope='session')
    def django_db_setup(
        request,
        django_db_setup,
        django_test_environment,
        django_db_blocker,
        django_db_use_migrations,
        django_db_keepdb,
        django_db_createdb,
        django_db_modify_db_settings,
    ):
        # do custom stuff here
        print('my custom django_db_setup executing')
    

    Notice I have django_db_setup argument in the custom django_db_setup fixture - this ensures the original fixture is called before the custom one.

    "Redeclaration"

    If you omit the argument, the custom fixture will replace the original one, so it won't be executed:

    @pytest.fixture(scope='session')
    def django_db_setup(
        request,
        django_test_environment,
        django_db_blocker,
        django_db_use_migrations,
        django_db_keepdb,
        django_db_createdb,
        django_db_modify_db_settings,
    ):
        print((
            'my custom django_db_setup executing - '
            'original django_db_setup will not run at all'
        ))
    

    BTW, this is another handy trick to use when you e.g. want to turn off a fixture that is defined elsewhere.

提交回复
热议问题