Vikas Madoori
Vikas Madoori

Reputation: 157

How to use fixtures in a Class which is inherting UnitTest class in python pytest

conftest.py

import pytest

@pytest.fixture(scope="session")
def client():
    env_name = 'FLASK_ENV'
    return env_name

@pytest.fixture(scope="session")
def client_1():
    env_name = 'FLASK_ENV_1'
    return env_name

test_run.py

import pytest
import unittest

@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("client_1")
class TestStaticPages(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        self.value = "ABC"

    def test_base_route(self, client, client_1):
        response = client
        assert response  == 'FLASK_ENV'
        assert client_1  == 'FLASK_ENV_1'

I am new to UnitTest in python. When I am trying to use fixtures in the test class it is failing. Could you please help me with the solution. Thanks in advance.enter image description here

Upvotes: 3

Views: 1570

Answers (2)

mv1005
mv1005

Reputation: 21

This is an old question, but just in case someone stumbles over this post, I'll leave the solution I came up with here for reference.

You can define a new fixture as a wrapper, which will expose the original fixture as an attribute in your test class.

According to the code above, this would be:

import pytest
import unittest

@pytest.fixture(scope="class")
def wrapped_fixtures(request, client, client_1):
    request.cls.client = client
    request.cls.client = client_1

@pytest.mark.usefixtures("wrapped_fixtures")
class TestStaticPages(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        self.value = "ABC"

    def test_base_route(self):
        response = self.client
        assert response  == 'FLASK_ENV'
        assert self.client_1  == 'FLASK_ENV_1'

Upvotes: 2

ws_e_c421
ws_e_c421

Reputation: 1113

Unfortunately, I don't think there is a way to do this. In the pytest documentation, it is stated that:

unittest.TestCase methods cannot directly receive fixture arguments as implementing that is likely to inflict on the ability to run general unittest.TestCase test suites.

So your client and client_1 functions can be called when the test case is run, but you can't get access to their return values.

Upvotes: 2

Related Questions