pytest 自定义参数

本贴最后更新于 514 天前,其中的信息可能已经时移世改

使用 pytest 的人会看到他的命令行参数中可以加很多的参数,那能不能自己定制参数呢? 这个在 pytest 是比较容易做到的。

具体步骤如下:

将自定义命令行参数注册到 pytest

为了使我们能够将命令行参数传递给 pytest 并在我们的测试中使用这些参数,我们需要采取的第一步是向 pytest 注册我们的新命令行参数。这可以通过将以下代码段添加到conftest.py放置在我们项目的根文件夹中的文件中:

def pytest_addoption(parser):
    parser.addoption(
        '--base-url', action='store', default='http://localhost:8080', help='Base URL for the API tests'
    )

这允许我们在调用 pytest 时传递自定义参数--base-url,例如:

pytest --base-url=http://api.zippopotam.us zip_api_test.py

--base-url当我们调用 pytest 时不包含参数时,http://localhost:8080将使用默认值。

这里parser是一个默认情况下可用于 pytest 的对象,可用于解析命令行参数以及 .ini 文件值。

在测试中使用命令行参数值

接下来,我们需要读取命令行参数值并将其传递给我们的测试。最方便的方法之一是使用 fixture

@pytest.fixture
def base_url(request):
    return request.config.getoption('--base-url')

这个夹具从命令行参数中读取值并返回它。我们现在可以在我们的任何测试中使用这个夹具,如下所示:

def test_api(base_url):
    response = requests.get(f'{base_url}/abc/55')
    print(response.request.url)
    assert response.status_code == 200

此测试方法使用base_url夹具检索调用 pytest 时通过命令行传递的基本 URL(或未指定时的默认值),以使用该基本 URL 向端点发送 HTTP 请求。

如果我们现在使用

pytest -s zip_api_test.py

它会打印

http://localhost:8080/us/90210

作为用于 HTTP 调用的端点,因为我们没有为base-url命令行参数指定任何值。如果我们调用 pytest 使用

pytest -s --base-url=http://api.zippopotam.us zip_api_test.py

它会打印

http://api.zippopotam.us/us/90210

作为请求中使用的端点,表明我们使用命令行参数传递的值已成功使用。结果!

多个变量

如果我们想传递多个变量呢?如果除了基本 URL 之外,我们还想将凭据传递给我们的测试,这样我们就不必将这些凭据存储在我们的测试代码中怎么办?

在我看来,有两种处理方法。在这两种情况下,您首先要做的是注册额外的命令行参数,例如:

def pytest_addoption(parser):
    parser.addoption(
        '--base-url', action='store', default='http://localhost:8080', help='Base URL for the API tests'
    )
    parser.addoption(
        '--username', action='store', default='test_user', help='Username to be used in the API tests'
    )
    parser.addoption(
        '--password', action='store', default='test_password', help='Password to be used in the API tests'
    )

现在,我们有两个选择。

选项一:我们将所有命令行参数值存储在夹具中的单个对象中,如下所示:

@pytest.fixture
def command_line_args(request):
    args = {}
    args['base_url'] = request.config.getoption('--base-url')
    args['username'] = request.config.getoption('--username')
    args['password'] = request.config.getoption('--password')
    return args

然后我们可以在我们的测试中使用这个fixture,并从我们的测试方法体中的字典中提取值。

选项二:我们为每个命令行参数创建一个单独的夹具。

这可以保持固定装置很小,但它要求您在所有测试中使用多个固定装置,这可能会有点冗长并且不能很好地扩展。不过,它确实增加了一些灵活性,可以决定您要使用哪个夹具进行哪些测试。

与生活中的许多事情一样,哪种方法最有效取决于具体情况。不过,总的来说,我认为我更喜欢第一种选择。

回帖
请输入回帖内容 ...