pytestfixturestest-class

How to get fixture value from test method declared within a unittest TestCase class?


My google search here only shows this most-related answer here; though I can only have my code working for test method BUT NOT with unittest TestCase class method.

My question is how to get fixture value from test method declared within a unittest TestCase class?

I quote the code snippet here

import pytest
from unittest import TestCase


@pytest.fixture()
def fx_return_value():
    yield 'some returned value'


@pytest.mark.usefixtures(fx_return_value.__name__)
def test0(fx_return_value):
    print(fx_return_value)


class Test1(TestCase):
    @pytest.mark.usefixtures(fx_return_value.__name__)
    def test1(self, fx_return_value):  #TODO Error here > TypeError: test1() missing 1 required positional argument: 'fx_return_value'
        print(fx_return_value)

Solution

  • pytest and unittest are separate test frameworks and are not intended to be mixed. You can use test classes in pytest alongside with setup and teardown methods without the need of a specific base class.

    So to fix your problem you just have to remove the unittest.TestCase base from your test class.

    Edit:
    The statement about not mixing pytest and unittest may be a bit misleading. For clarification: you can always run unittest tests using pytest, just not the other way around. Pytest is specifically written with compatibility to unittest (and nosetest) in mind, maing the conversion to pytest easier.
    In contrast, unittest cannot know about pytest, so pytest features like fixtures cannot be used in unittest.