Python 3.x Pytest:测试的运行时参数化

Python 3.x Pytest:测试的运行时参数化,python-3.x,python-requests,pytest,Python 3.x,Python Requests,Pytest,有人知道动态参数化pytest测试的解决方法吗 例如: resp = [] def test_1(): r = requests.get(<some url>) resp = <parse a list out of response r> @pytest.mark.parameterize("response",resp) def test_2(response): <Use resp values and pass it one b

有人知道动态参数化pytest测试的解决方法吗

例如:

resp = []

def test_1():
    r = requests.get(<some url>)
    resp = <parse a list out of response r>


@pytest.mark.parameterize("response",resp)
def test_2(response):
    <Use resp values and pass it one by one to another api>
resp=[]
def测试_1():
r=requests.get()
响应=
@pytest.mark.parameterize(“响应”,resp)
def测试_2(响应):
我在pytest github上遇到了以下问题,这与我的问题几乎相同


根据本文的讨论,pytest在执行任何测试之前将测试参数化。不支持运行时参数化。有人知道处理这种行为的变通方法或python方法吗?

不要让测试相互依赖。这不是所描述的好做法

如果您想重用请求-响应,可以将其包装成一个


Adrian Krupa的答案很接近,现在添加响应参数化:

CANNED_RESPONSES = dict(OK=200, REDIRECT=304, SERVER_ERROR=500)
RESPONSE = 'response'

def pytest_generate_tests(metafunc):
    if RESPONSE in metafunc.fixturenames:
        ids = list(CANNED_RESPONSES.keys())
        responses = list(CANNED_RESPONSES.values())
        metafunc.parametrize(RESPONSE, responses, ids=ids)


def test_flar(response):
    print response
通过这种方式,您可以在-v中获得命名ID,并对一组固定答案进行多个测试:

test_in.py::test_flar[OK] 200
PASSED
test_in.py::test_flar[REDIRECT] 304
PASSED
test_in.py::test_flar[SERVER_ERROR] 500
PASSED

在测试执行开始后更改测试集是一个危险的进入路径,并且由于某种原因,
pytest
不支持该路径。你为什么还需要它?将
resp
填充代码提取到一个单独的函数中,并在测试执行开始之前调用它。但是这样我就无法在测试中实现参数化。解析response的值并为每个值运行test会很好。有没有其他方法可以实现这一点?然后使用请求参数对测试进行参数化,在测试中发出请求并使用响应。它将更容易维护。但是您应该避免在测试中发出真实的请求(如果它们不是集成测试)。
CANNED_RESPONSES = dict(OK=200, REDIRECT=304, SERVER_ERROR=500)
RESPONSE = 'response'

def pytest_generate_tests(metafunc):
    if RESPONSE in metafunc.fixturenames:
        ids = list(CANNED_RESPONSES.keys())
        responses = list(CANNED_RESPONSES.values())
        metafunc.parametrize(RESPONSE, responses, ids=ids)


def test_flar(response):
    print response
test_in.py::test_flar[OK] 200
PASSED
test_in.py::test_flar[REDIRECT] 304
PASSED
test_in.py::test_flar[SERVER_ERROR] 500
PASSED