What are the best practices for managing test variables in pytest
compared to unittest
?
In unittest
, I can set up variables in a class, and then the methods of this class can choose whichever variable they want to use. Here’s an example:
class TestClass(unittest.TestCase):
def setUp(self):
self.varA = 1
self.varB = 2
self.varC = 3
self.modified_varA = 2
def test_1(self):
do_something_with(self.varA, self.varB)
def test_2(self):
do_something_with(self.modified_varA, self.varC)
With unittest
, it’s easy to group tests together in one class and use various variables across different methods. In pytest
, however, I’m using fixtures in conftest.py
instead of a class, like this:
@pytest.fixture(scope="module")
def input1():
varA = 1
varB = 2
return varA, varB
@pytest.fixture(scope="module")
def input2():
varA = 2
varC = 3
return varA, varC
I then feed these fixtures to my functions in a different file (let’s say test_this.py
) for different test functions. But, I’m running into a couple of challenges:
-
Since I can’t just declare local variables in
conftest.py
and directly import them, is there a better way to declare different variables inconftest.py
that can be used in multiple functions intest_this.py
? I have five different configurations for these variables, and defining that many different fixtures sounds cumbersome. I would rather go back to theunittest
class structure, where I can define my variables and pick and choose what I want. -
Should I declare global variables in
test_this.py
and use them across functions? That doesn’t seem very Pythonic since these variables are only used in that file. -
Let’s say I have multiple test files, such as
test_that.py
andtest_them.py
. If I have shared variables between these files, how should I manage them? Should I create a file likevariables.py
in the same directory and import it where needed? This way, I can keep all data separate from the test logic. -
Does
pytest
discourage organizing tests using classes? Every example I read online uses a bunch of functions with fixtures only. What is the recommended way to define a class and methods for organizing tests inpytest
? -
In a scenario where I need to use the result of one function in another, how would I do that in
pytest
? Since I have anassert
statement at the end of a function instead of a return, I won’t be able to use this function as a fixture. How can I accomplish this? I understand that it’s not ideal for one test to rely on another, but is there a workaround?
In summary, what are the differences between pytest vs unittest
in terms of managing variables and organizing tests? How can I effectively use the fixtures in pytest
while keeping things flexible like I did with the unittest
class structure?