unittest Vs pytest

1) First of all, you can declare those fixtures not only in conftest.py, but in every Python module you want. And you can import that module. Also you can use fixtures in the same way as you used setUp method:

@pytest.fixture(scope='class')
def input(request):
    request.cls.varA = 1
    request.cls.varB = 2
    request.cls.varC = 3
    request.cls.modified_varA = 2

@pytest.usefixtures('input')
class TestClass:
    def test_1(self):
        do_something_with_self.varA, self.varB

    def test_2(self):
        do_something_with_self_modified_varA, self.varC

or you can define separate variables in separate fixtures:

def fixture_a():
    return varA

def fixture_b():
    return varB

def fixture_c():
    return varC

def fixture_mod_A():
    return modified_varA

or make one fixture which returns all the variables (why not?) or even make indirect parametrized fixture which returns variables by your choice (quite confusing way):

@pytest.fixture()
def parametrized_input(request):
   vars = {'varA': 1, 'varB': 2, 'varC': 3}
   var_names = request.param
   return (vars[var_name] for var_name in var_names)

@pytest.mark.parametrize('parametrized_input', [('varA', 'varC')], indirect=True)
def test_1(parametrized_input)
   varA, varC = parametrized_input
   ...

Or even you can make fixture factory which will make fixtures for you on the fly. Sounds curiously when you have only 5 tests and 5 configurations of variables, but when you get hundreds of both, it can be useful.

3) Of course you can. But I recommend you not to import this file directly, but use command line option pointing what file to import. In this case you can choose another file with variables without changing your code.

4) I use classes in my tests because I migrated from nosetest. I didn’t mention any problem with using classes in pytest.

5) In that case I propose you to do the following: fist make the function with desired actions:

def some_actions(a, b):
    # some actions here
    ...
    return c

then use it both in test and fixture:

def test():
    assert some_actions(1,2) == 10

@pytest.fixture()
def some_fixture():
     return some_actions(1,2)

Leave a Comment