gpt4 book ai didi

python - 如何访问 conftest.py 中的 json 文件(测试数据如 config.json)

转载 作者:行者123 更新时间:2023-11-28 20:37:05 25 4
gpt4 key购买 nike

假设在此示例中,如何在使用 pytest 执行测试套件时访问 conftest fixture 中的相应 config.json 文件。

$ pwd
/home/user/repo/main
$ pytest testcases/project_(1/2)/test_suite_(1/2).py

目录结构:

├── main
│ ├── conftest.py # conftest file for my fixtures
│ ├── testcases
│ ├── project_1
│ │ (contains these files -- test_suite_1.py, config.json)
│ └── project_2
│ (contains these files -- test_suite_2.py, config.json)
├── workflows
│ └── libs

最佳答案

您可以通过request.node.fspath 访问当前执行模块的路径,并构建相对于它的config.json 的路径。 requestpytest 提供的 fixture。这是一个基于您提供的目录结构的示例。

# main/conftest.py
import json
import pathlib
import pytest


@pytest.fixture(autouse=True)
def read_config(request):
file = pathlib.Path(request.node.fspath)
print('current test file:', file)
config = file.with_name('config.json')
print('current config file:', config)
with config.open() as fp:
contents = json.load(fp)
print('config contents:', contents)

如果您将上面的代码复制到您的 conftest.py 并使用 -s 运行测试,您应该会得到类似这样的输出:

$ pytest -sv
=============================== test session starts ===============================
platform linux -- Python 3.6.5, pytest-3.4.1, py-1.5.3, pluggy-0.6.0 -- /data/gentoo64/usr/bin/python3.6
cachedir: .pytest_cache
rootdir: /data/gentoo64/tmp/so-50329629, inifile:
collected 2 items

main/project1/test_one.py::test_spam
current file: /data/gentoo64/tmp/so-50329629/main/project1/test_one.py
current config: /data/gentoo64/tmp/so-50329629/main/project1/config.json
config contents: {'name': 'spam'}
PASSED
main/project2/test_two.py::test_eggs
current file: /data/gentoo64/tmp/so-50329629/main/project2/test_two.py
current config: /data/gentoo64/tmp/so-50329629/main/project2/config.json
config contents: {'name': 'eggs'}
PASSED

============================= 2 passed in 0.08 seconds ============================

使用解析的配置值

您可以通过在 fixture 中返回解析的 JSON 数据并将 fixture 用作测试参数之一来访问它。我稍微修改了上面的 fixture ,使其返回解析后的数据并删除了 autouse=True:

@pytest.fixture
def json_config(request):
file = pathlib.Path(request.node.fspath.strpath)
config = file.with_name('config.json')
with config.open() as fp:
return json.load(fp)

现在只需在测试参数中使用 fixture 名称,值将是 fixture 返回的值。例如:

def test_config_has_foo_set_to_bar(json_config):
assert json_config['foo'] == 'bar'

关于python - 如何访问 conftest.py 中的 json 文件(测试数据如 config.json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50329629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com