gpt4 book ai didi

python - 将变量从conftest返回到测试类

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:57 25 4
gpt4 key购买 nike

我有以下脚本:

conftest.py:

import pytest
@pytest.fixture(scope="session")
def setup_env(request):
# run some setup
return("result")

测试.py:

import pytest
@pytest.mark.usefixtures("setup_env")
class TestDirectoryInit(object):
def setup(cls):
print("this is setup")
ret=setup_env()
print(ret)

def test1():
print("test1")

def teardown(cls):
print("this teardown")

我收到错误:

    def setup(cls):
print("this is setup")
> ret=setup_env()
E NameError: name 'setup_env' is not defined

setup()中,我想从conftest.py中的setup_env()获取返回值“result”。

有高手可以指导一下吗?

最佳答案

我相信 @pytest.mark.usefixtures 更适合在执行每个测试之前进行状态更改。来自文档:

“有时测试函数并不直接需要访问固定对象。”

https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects

这意味着您的装置在每次测试开始时运行,但您的函数无权访问它。

当您的测试需要访问固定装置返回的对象时,在放入 conftest.py 并用 @pytest.fixture 标记时,该对象应该已按名称填充。 。您需要做的就是将 fixture 的名称作为测试函数的参数,如下所示:

https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects

如果您希望在类或模块级别上执行此操作,则需要更改 @pytest.fixture 语句的范围,如下所示:

https://docs.pytest.org/en/latest/fixture.html#sharing-a-fixture-across-tests-in-a-module-or-class-session

很抱歉有这么多文档链接,但我认为他们有很好的例子。希望事情能够澄清。

关于python - 将变量从conftest返回到测试类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com