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

标签 python mongodb testing automated-tests pytest

我有一个带有非常大集合的 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/

相关文章:

mongodb - 为什么 mongo db serverStatus connections current 不等于 netstat count

testing - 将系统测试用例包含到应用程序的最终打包产品中是否会导致膨胀或增加风险?

java - 如何测试junit5中的日志记录?

python - 如果 kwargs 中的键与函数关键字冲突怎么办

java - 如何将 mongo 集合从 java 导出到 json 文件

python - 在 sys.modules 中动态创建模块导致 sys 变为 None

ruby - 你如何创建一个 mongoid 对象的副本/复制?

google-chrome - Protractor/Selenium 嵌入式凭据放弃了对 chrome 的支持

Python - 通过 enumerate() 迭代和替换列表索引

python - 将两个整数列表添加到第三个列表中?