2017-05-31 104 views
1

我有以下脚本:从conftest返回变量测试类

conftest.py

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

test.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()中,我想从setup_env()得到conftest.py的返回值“result”。

任何专家可以指导我如何做到这一点?

回答

1

我认为@pytest.mark.usefixtures更多的意思是在执行每个测试之前的状态改变。从文档:

“有时测试函数不直接需要访问一个灯具对象。”

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

也就是说你的灯具在每个测试开始运行,但你的函数没有访问它。

当你的测试需要访问你的夹具返回的对象,应该已经姓名列入conftest.py时并打上@pytest.fixture填充。所有你需要做的是那么delcare夹具作为参数的名称,您的测试功能,像这样:

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

如果你喜欢做这一个类或模块级,你想改变您@pytest.fixture声明scope,像这样:

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

对不起,这么多的链接的文档,但我认为他们有很好的例子。希望这能说明问题。