【问题标题】:Return variable from conftest to test class从 conftest 返回变量到测试类
【发布时间】:2017-05-31 21:27:35
【问题描述】:

我有以下脚本:

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()中,我想从conftest.py中的setup_env()获取返回值“结果”。

有高手可以指导我怎么做吗?

【问题讨论】:

    标签: python pytest fixture


    【解决方案1】:

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

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

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

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

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

    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

    很抱歉有这么多文档链接,但我认为他们有很好的例子。希望能解决问题。

    【讨论】:

      猜你喜欢
      • 2023-02-26
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多