如何将参数从 'conftest,py' 传递到测试文件 (pytest)?

How to pass arguments from 'conftest,py' to test file (pytest)?

如何将参数从 conftest.py 传递到 test 文件?

conftest.py

import sys,pytest


def tear_down():
    print("teardown")

def pytest_addoption(parser):
    parser.addoption("--a1", action="store", default="some_default_value", help="provide a1")
    parser.addoption("--b1", action="store", default=None, help="provide b1")
    parser.addoption("--c1", action="store", default=None, help="provide c1")


@pytest.fixture(autouse=True)
def set_up(request):
    print("set up")

    a1 = request.config.getoption("--a1")
    b1 = request.config.getoption("--b1")
    c1 = request.config.getoption("--c1")

    if not(b1) and not(c1):
        sys.exit("Both values can't be empty")

    if b1 and c1:
        sys.exit("provide either b1 or c1, not both")

test.py 中,我需要访问所有这些参数 a,b & c。我该怎么做?

test.py

import pytest

class Test1:
    def fun1(self,a,b="",c=""):
        print("task1")

    def fun2(self,a,b="",c=""):
        print("task2")

class Test2:
    def fun12(self,a,b="",c=""):
        print("task12")

    def fun34(self, a, b="", c=""):
        print("task34")

我是 pytest 新手。你能帮帮我吗?

这个问题已经回答了很多次了。您可以在官方文档中轻松找到它 here。了解如何搜索解决方案和阅读文档,这是一项非常宝贵的技能。

要回答您的问题,您可以这样做:

conftest.py

import pytest

@pytest.fixture(autouse=True)
def set_up(request):    
    return {"a": 1, "b": 2, "c": 3}

test.py

import pytest

class Test1:
    def test_fun1(self, set_up):
        print("{0} - {1} - {2}".format(set_up["a"], set_up["b"], set_up["c"]))    

为了关注您遗漏的内容,我省略了示例的其余部分。我还重命名了测试函数,因为 pytest 默认情况下只会发现以 test 开头的函数作为实际测试用例:https://docs.pytest.org/en/latest/reference.html#confval-python_functions 所以除非你改变行为,例如pytest.ini,这个函数不会运行作为测试用例。