Search code examples
python-3.xpytestautotest

How can i pass current (running) test module in fixtures which placed in conftest?


I would like to know how to pass current running test module to fixture or how do fixture can know it? (I need to load specific config-file for every test module inside the package).

I can create fixture in every test module, but I want to the more universal solution. Thanks in advance.


Solution

  • Generally, you can get module name into fixture like that:

    @pytest.fixture
    def fixture_global(request):
        module_name = request.module.__name__
        print(module_name) 
        # some logic depends on module name
    

    It may be even global fixture in conftest but this way does not work with session scope fixtures because they are not called every module which use it.


    If you want to have a base shared fixture code and additionally some specific code for specific modules I would suggest a better way.

    In global conftest.py put "base" fixture with universal code. If you want use it into specific test module, just inject global fixture to local fixture as argument. Something like that:

    conftest.py

    @pytest.fixture
    def global_fixture():
      # universal code for vary modules
      return universal_obj
    

    test_module.py

    @pytest.fixture
    def local_fixture(global_fixture):
      # specific code that uses global fixture result