使用 pytest 管理测试数据的正确方法是什么?

2024-01-07

我需要为多个相关应用程序创建自动化测试,并面临测试之间的测试数据管理问题。 问题是相同的数据必须在多个应用程序和/或不同的 API 之间共享。 现在我有了 pytest 的下一个结构,它对我很有用,但我怀疑在 conftest.py 中使用测试数据管理是正确的方法:

整体结构如下:

tests/
    conftest.py
    app1/
        conftest.py
        test_1.py
        test_2.py
    app2/
        conftest.py
        test_1.py
        test_2.py
test_data/
    test_data_shared.py
    test_data_app1.py
    test_data_app2.py

以下是tests/conftest.py中的测试数据示例:

from test_data.test_data_shared import test_data_generator, default_data

@pytest.fixture
def random_email():
    email = test_data_generator.generate_random_email()
    yield email
    delete_user_by_email(email)

@pytest.fixture()
def sign_up_api_test_data(environment, random_email):
"""
environment is also fixture, capture value from pytest options
"""
    data = {"email": random_email, "other_data": default_data.get_required_data(), "hash": test_data_generator.generate_hash(environment)}
    yield data
    do_some_things_with_data(data)

使用固定装置来达到这个目的非常舒服,因为后置条件、作用域和其他甜蜜的东西(请注意,应用程序有很多逻辑和关系,所以我不能简单地硬编码数据或将其迁移到 json 文件中) 类似的东西可以在tests/app1/conftest.py和tests/app2/conftest.py中找到,以获取app1和app 2中相应使用的数据。

所以,这里有两个问题: 1.conftest.py 变成了代码量巨大的怪物 2.据我所知,使用conftest来测试数据是一个不好的方法还是我错了?

提前致谢!


我使用conftest.py作为测试数据。
夹具是向测试提供测试数据的推荐方法。
conftest.py 是在多个测试文件之间共享固定装置的推荐方法。

至于#2。我认为使用conftest.py来测试数据是可以的。

现在#1,“conftest.py 变得太大”。

特别是对于位于 test/conftest.py 的顶层 conftest.py 文件,您可以将该内容移至一个或多个 pytest 插件中。由于conftest.py文件可以被认为是“本地插件”,因此将它们转换为插件的过程并不太困难。

See https://docs.pytest.org/en/latest/writing_plugins.html https://docs.pytest.org/en/latest/writing_plugins.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pytest 管理测试数据的正确方法是什么? 的相关文章

随机推荐