0

如何将参数从文件传递conftest.pytest文件?

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。我怎样才能做到这一点 ?

测试.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的新手。你能帮我么 ?

4

1 回答 1

1

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

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

conftest.py

import pytest

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

测试.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,此函数不会作为测试用例运行。

于 2020-07-06T13:01:37.100 回答