简体   繁体   中英

Pytest, using fixtures as instances of class in prolog method setup_method

I've started using unitest infrastructure that based on pytest for adding additional test class (see below TestMyStuff )

It seems that if I add the fixtures xi and yi as inputs of method setup_method it refer to them as functions from fixtures.py , but adding them to each of the test functions, they get their return value of classX and classY respectively rather then the function value.

Both test methods share identical code block which require xi and yi , and also an additional per-test unique code. I wish to take the common code and add it to test_method but for that I need that xi and yi as instances of classX and classY which the fixtures method returns, and not the methods themselves from fixtures.py

In brief, is there any way to share some pre-built fixtures between all class functions (both the test methods and the prolog method) ?

test_xy.py

from fixtures import *

class TestMyStuff
    def setup_method(self, test_method, xi, yi):
        # here xi and yi are functions :-(
        self.x = classX.makeX()
        self.y = classY.makeY()


    def test_X(self, xi, yi):
        # here xi and yi are instances of classX and classY
        # do shared stuff with xi and yi
        # do unique stuff with xi and yi

    def test_Y(self, xi,yi):
        # here xi and yi are instances of classX and classY
        # do shared stuff with xi and yi
        # do other stuff with xi and yi

fixtures.py

from classY import classY
from classX import classX


@pytest.fixture()
def xi(request):
    ...
    return classX(request.var1, request.var2, request.var3)
    #classX is implemented on different file called classX.py

@pytest.fixture()
def yi(request, xi)
    ...
    return classY(request.var1, xi) 

From the pytest documentation:

You can mix both fixture mechanisms in the same file but test methods of unittest.TestCase subclasses cannot receive fixture arguments.

https://docs.pytest.org/en/latest/xunit_setup.html

I do not think you can build things as elegantly as you would like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM