12

Consider the following pseudocode demonstrating my question:

import pytest


@pytest.fixture
def param1():
    # return smth
    yield "wilma"


@pytest.fixture
def param2():
    # return smth
    yield "fred"


@pytest.fixture
def bar(param1, param2):
    #do smth
    return [Bar(param1, param2), Bar(param1, param2)]


@pytest.fixture
def first_bar(bar):
    return bar[0]


class Test_first_bar:

    # FIXME: how do I do that?
    #def setup_smth???(self, first_bar):
    #    self.bar = first_bar


    def test_first_bar_has_wilma(self):
        # some meaningful check number 1
        assert self.bar.wilma == "wilma"


    def test_first_bar_some_other_check(self):
        # some meaningful check number 2
        assert self.bar.fred == "fred"

Basically I want to pass first_bar fixture to my Test_first_bar class in order to reuse that object in all its test methods. How should I go about dealing with such situation?

Python 3, if that matters.

varnie
  • 2,523
  • 3
  • 35
  • 42

1 Answers1

7

Here, you can define your fixture as autouse. Which would be called automatically for all the tests of your class. Here, I cant understand what is [Bar(param1, param2), Bar(param1, param2)]. Well, that's not the point, if rest of the code is working fine than you can try the below solution. I have replaced the code with static variables to verify if it's working or not and it's working fine at my end.

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"


@pytest.fixture
def param2():
    # return smth
    yield "fred"


@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]


@pytest.fixture(scope='function', autouse=True)
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    def test_first_bar_some_other_check(self,request):
        print request.instance.bar

And if you do not want to make fixture as autouse, than you can call it before your test. Like,

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"


@pytest.fixture
def param2():
    # return smth
    yield "fred"


@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]


@pytest.fixture(scope='function')
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_some_other_check(self,request):
        print request.instance.bar
Chanda Korat
  • 2,453
  • 2
  • 19
  • 23
  • 9
    I got error > E TypeError: test_first_bar_has_wilma() missing 1 required positional argument: 'request' – Nam G VU Feb 08 '20 at 14:29