gpt4 book ai didi

python - Pytest- 使用生成器进行 mark.parametrize

转载 作者:行者123 更新时间:2023-12-04 16:44:56 26 4
gpt4 key购买 nike

我有一个带有非常大集合的 mongo 数据库,我需要用 Pytest 对其运行测试。我正在尝试使用 mark.parametrize dectorator 但使用 pymongo.cursor Cursor 对象的通常路径:

def get_all_data():
return db["collection"].find({}) # query to retrieve all documents from the collection

@pytest.mark.parametrize("doc", get_all_data())
def test_1(doc):
assert doc["val"] == 1
....

此代码的问题是在运行测试之前的收集阶段中的 pytest 自动将生成器转换为列表。我不想要这个有两个原因:

  1. 由于集合非常大,所以速度非常慢。
  2. 堆栈溢出 - 没有足够的 RAM 来加载所有这些数据。

这意味着我不能使用 mark.parametrize,但是我如何仍然使用生成器一次运行测试 1 而不是立即将所有内容加载到内存中? Pytest 甚至可能吗?

最佳答案

我可以想到这个解决方法 - 编写一个 fixture 来将生成器传递给单个测试。然后使用 pytest-check 在同一测试中分别检查 每个条目。 (因为我想您需要分别断言每个条目并继续,即使某些条目失败)。

@pytest.fixture
def get_all_data():
yield db["collection"].find({})

def test_1(get_all_data):
for each in get_all_data:
check.is_(each["val"], 1)

关于python - Pytest- 使用生成器进行 mark.parametrize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70141879/

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