如何将多个dict作为参数发送到pytestfixture

2024-04-29 14:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个测试来通过有效和无效的代理详细信息。我已经编写了一个pytestfixture,它将执行请求并返回响应。但我的问题是,我想在fixture期间发送无效和有效的代理详细信息。有人能纠正我这个方法是否正确或建议我的有效方法,我是新的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

Tags: 方法httpswebjsonhttp代理pytestresponse
1条回答
网友
1楼 · 发布于 2024-04-29 14:44:25

您需要参数化测试用例,而不是夹具。而且,这不是使用固定装置的用例。所以,你应该这样处理:

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

You can choose to have different data for the positive and negative scenarios depending on the requirement.

相关问题 更多 >