How to make PyTest use the `conftest.py` of a parent directory

Question:

I am working on a suite of tests for a project that were not written by me. The way they were set up is as follows

root/
   conftest.py
   testType1/
      a.py
   testType2/
   etc.

The file a.py is as follows

class TestClass:
    value_thats_important = None

    def test_to_test(self):
        do work that uses self.value_thats_important

Heres the problem I am encountering, the way it was originally developer, self.value_thats_important is set during the conftest.py generate tests. So if I run

pytest root/ arg=ARG_THAT_I_NEED

or

pytest testType1/ arg=ARG_THAT_I_NEED

It works totally fine. However, I also need to be able to run the test individually without calling every other test, and when I run

pytest testType1/a.py::TestClass arg=ARG_THAT_I_NEED

I get the error that Nonetype not subscriptable, which is telling me that the conftest is not getting called. I’m pretty new to pytest so is there a way I can salvage this without having to rewrite the entire test?

Asked By: wjmccann

||

Answers:

This is a job for fixtures. The details will vary based on the specifics of your implementation, so here’s a toy example that demonstrates the functionality.

Directory structure

tests/
   conftest.py
   testType1/
      a.py

tests/conftest.py

import pytest

@pytest.fixture(scope="session")
def my_arg():
    yield "foo"

tests/testType1/a.py

import pytest

@pytest.mark.usefixtures("my_arg")
class TestClass():
    value_thats_important = None

    def test_to_test(self,my_arg):
        self.value_thats_important = my_arg

        assert self.value_thats_important == "foo"

Running the test

PS myprojteststestType1> pytest -v a.py
================================================= test session starts =================================================
platform win32 -- Python 3.10.6, pytest-7.1.2, pluggy-1.0.0 -- myproj.venvScriptspython.exe
cachedir: .pytest_cache
rootdir: myprojteststestType1
collected 1 item

a.py::TestClass::test_to_test PASSED
Answered By: picobit
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.