首页 > 解决方案 > 如何将多个字典作为参数发送到 pytest 夹具

问题描述

我正在尝试编写一个测试来传递有效和无效的代理详细信息。我已经编写了一个 Pytest 夹具,它将请求并返回响应。但我的问题是我想在固定期间发送无效和有效的代理详细信息。有人可以纠正我这种方法是否正确或建议我使用有效的方法,我是 Pytests 的新手。我尝试了以下方法。

@pytest.fixture(scope="module")
@pytest.mark.parametrize("proxyDict",[
    ({
        "http": "web-proxy.testsite:8080",
        "https": "web-proxy.testsite:8080"
        }),
({
        "http": "web-wrong:8080",
        "https": "web-.wrong:8080"
        })
])
def cve_response(proxy_dict):
    year="2018"
    base_url = 'https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-' + str(year) + '.json.zip'
    headers = {
        "content-type": "application/json"
    }
    response_data = requests.request("GET", base_url, headers=headers, verify=False, stream=True,
                                         proxies=proxy_dict)
    yield response_data

@pytest.mark.proxy
def test_valid_proxy(cve_response):
    assert 200 == cve_response.status_code

@pytest.mark.invalidproxy
def test_invalid_proxy(cve_response):
    assert not 200 == cve_response.status_code

标签: pythonpytest

解决方案


您需要参数化您的测试用例而不是您的夹具。此外,这不是使用固定装置的用例。所以,相反,你应该如何处理它:

data = [{
            "http": "web-proxy.testsite:8080",
            "https": "web-proxy.testsite:8080"
        },
        {
            "http": "web-wrong:8080",
            "https": "web-.wrong:8080"
        }]

def cve_response(proxy_dict):
    year="2018"
    base_url = 'https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-' + str(year) + '.json.zip'
    headers = {
        "content-type": "application/json"
    }
    response_data = requests.request("GET", base_url, headers=headers, verify=False, stream=True,
                                         proxies=proxy_dict)
    return response_data

@pytest.mark.proxy
@pytest.mark.parameterize("proxy", data)
def test_valid_proxy(proxy):
    assert 200 == cve_response(proxy).status_code

@pytest.mark.invalidproxy
@pytest.mark.parameterize("proxy", data)
def test_invalid_proxy(proxy):
    assert not 200 == cve_response(proxy).status_code

您可以根据要求为正面和负面场景选择不同的数据。


推荐阅读