setup_method 中的 py.test 会话级装置 [英] py.test session level fixtures in setup_method

查看:35
本文介绍了setup_method 中的 py.test 会话级装置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在测试类的设置中以某种方式使用来自 conftest.py 的 pytest 固定装置?我需要在会话开始时初始化一个对象并在某些测试类的设置中使用它.

Is there a way to somehow use pytest fixtures from conftest.py in a test class's setup? I need to initialize an object when the session starts and use it in some test classes' setup.

像这样:

# conftest.py:

import pytest

@pytest.fixture(scope="session", autouse=True)
def myfixture(request):
    return "myfixture"

<小时>

# test_aaa.py

class TestAAA(object):

    def setup(self, method, myfixture):
        print("setup myfixture: {}".format(myfixture))

    ...

推荐答案

我在 pytest<=3.7.0 的测试类中使用了这种设置(它停止使用 pytest 3.7.1 版本):

I used this kind of a setup for a test class with pytest<=3.7.0 (it stopped working with pytest 3.7.1 release):

# conftest.py:

import pytest

# autouse=True does not work for fixtures that return value
# request param for fixture function is only required if the fixture uses it:
# e.g. for a teardown or parametrization. Otherwise don't use it.
@pytest.fixture(scope="session")
def myfixture():
    return "myfixture"

<小时>

# test_aaa.py

import pytest

class TestAAA(object):
    @classmethod
    @pytest.fixture(scope="class", autouse=True)
    def setup(self, myfixture):
        self.myfixture = myfixture

    def test_function1(self):
        # now you can use myfixture without passing it as param to each test function   
        assert self.myfixture == "myfixture"

这篇关于setup_method 中的 py.test 会话级装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆