Python 使用pytest管理测试数据的正确方法是什么?
我需要为几个相关的应用程序创建自动测试,并且在测试之间的测试数据管理方面遇到了一个问题。 问题是相同的数据必须在多个应用程序和/或不同的API之间共享。 现在我有了pytest的下一个结构,它对我来说很好,但我怀疑在conftest.py中使用测试数据管理是正确的方法: 整体结构如下所示:Python 使用pytest管理测试数据的正确方法是什么?,python,testing,design-patterns,automated-tests,pytest,Python,Testing,Design Patterns,Automated Tests,Pytest,我需要为几个相关的应用程序创建自动测试,并且在测试之间的测试数据管理方面遇到了一个问题。 问题是相同的数据必须在多个应用程序和/或不同的API之间共享。 现在我有了pytest的下一个结构,它对我来说很好,但我怀疑在conftest.py中使用测试数据管理是正确的方法: 整体结构如下所示: tests/ conftest.py app1/ conftest.py test_1.py test_2.py app2/
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)
出于这个目的使用fixture非常方便,因为后置条件、作用域和其他美妙的东西(注意,应用程序有很多逻辑和关系,所以我不能简单地硬编码数据或将其迁移到json文件中)
类似的情况可以在tests/app1/conftest.py和tests/app2/conftest.py中找到,它们对应于app1和app2中使用的数据
因此,这里有两个问题:
1.conftest.py成为一个拥有大量代码的怪物
2.正如我所知,对测试数据使用conftest是一种糟糕的方法,还是我错了
提前谢谢 我使用conftest.py作为测试数据。
夹具是向测试提供测试数据的推荐方式。
建议使用conftest.py在多个测试文件之间共享装置 至于#2。我认为可以使用conftest.py作为测试数据 现在来看#1,“conftest.py变得太大” 特别是对于顶级conftest.py文件,在test/conftest.py中,您可以将该内容移动到一个或多个pytest插件中。由于conftest.py文件可视为“本地插件”,因此将其转换为插件的过程并不太困难
请参见您可能会感兴趣的内容:它实际上是为了解决这个问题而设计的。您将在文档中找到大量的示例,案例可以放在专用模块、类或测试文件中—这取决于您的需要。例如,将两种测试数据生成器放在同一模块中:
from pytest_cases import parametrize_with_cases, parametrize
def data_a():
return 'a'
@parametrize("hello", [True, False])
def data_b(hello):
return "hello" if hello else "world"
def user_bob():
return "bob"
@parametrize_with_cases("data", cases='.', prefix="data_")
@parametrize_with_cases("user", cases='.', prefix="user_")
def test_with_data(data, user):
assert data in ('a', "hello", "world")
assert user == 'bob'
有关详细信息,请参阅。顺便说一句,我是作者;) 谢谢。我会尝试使用插件!