跳至主要内容

pytest插件,用于MongoDB fixture

项目描述

https://img.shields.io/pypi/v/pytest-mongodb.svg?style=flat-square https://img.shields.io/github/actions/workflow/status/mdomke/pytest-mongodb/lint-and-test.yml?branch=main&style=flat-square https://img.shields.io/pypi/l/pytest-mongodb.svg?style=flat-square https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square

这是什么?

这是一个pytest插件,它允许您测试依赖于与MongoDB数据库连接的代码,并期望存在某些数据。它允许您以JSON/BSON或YAML格式指定数据库集合的fixture。在底层,我们使用mongomock库,您应参考该库的文档以了解如何使用MongoDB模拟对象。如果适用,您也可以使用实际的MongoDB服务器。

注意:该项目已被重命名为humongouspytest-mongodb,以符合pytest插件命名约定,并更容易在Python包索引中找到。有关更多信息,请参阅迁移部分

配置

如果您不想将数据库fixture放在包的顶级目录中,您必须指定pytest查找数据定义的目录。

为此,在pytest部分的pytest.ini-文件中添加以下行:

[pytest]
mongodb_fixture_dir =
  tests/unit/fixtures

pytest-mongodb将在此目录中查找以.yaml.json结尾的文件。

如果您只想加载可用的部分 fixtures,可以使用 mongodb_fixtures 配置选项。它接受一个不带文件扩展名的集合文件名列表。例如:

[pytest]
mongodb_fixtures =
  players
  championships

在这种情况下,只会加载“players”和“championships”这两个集合。

您也可以选择使用真实的 MongoDB 服务器进行测试。在这种情况下,如果您不想坚持使用默认设置(localhost 和无凭据),可能还需要配置主机名和/或凭据。请使用以下配置值在您的 pytest.ini 文件中调整设置:

[pytest]
mongodb_engine = pymongo
mongodb_host = mongodb://user:passwd@server.tld
mongodb_dbname = mydbname

对于使用 homebrew 安装 MongoDB 的 Mac 用户,您可以通过在 pytest.ini 文件中使用 mongo_exec = /usr/local/bin/mongod 来配置可执行文件从 /usr/local/bin/mongod 而不是 /usr/local/bin/mongod 被选中。

基本用法

在您配置了 pytest-mongodb 以使其能够找到您的 fixtures 之后,您就可以指定一些数据了。无论您选择哪种标记语言,数据都以文档(字典)列表的形式提供。这些文档将被插入的集合由 fixtures 文件的文件名给出。例如:如果您有一个名为 players.yaml 的文件,其内容如下:

- name: Mario
  surname: Götze
  position: striker

- name: Manuel
  surname: Neuer
  position: keeper

您将得到一个名为 players 的集合,其中插入了上述球员定义。如果您的 fixtures 文件是 JSON/BSON 格式,您也可以使用 BSON 特定的类型,如 $oid$date 等。

您可以通过在测试函数中使用 mongodb fixture 来获取数据库:

def test_players(mongodb):
    assert 'players' in mongodb.list_collection_names()
    manuel = mongodb.players.find_one({'name': 'Manuel'})
    assert manuel['surname'] == 'Neuer'

有关更多信息,请参阅 mongomock 文档。

如果您想在引擎为例如 mongomock 引擎的情况下跳过特定的测试,可以这样做:

from pytest_mongodb.plugin import mongo_engine
from pytest import mark

@mark.skipif(mongo_engine() == 'mongomock', reason="mongomock does not support that")
def test_players(mongodb):
    assert 'players' in mongodb.list_collection_names()
    manuel = mongodb.players.find_one({'name': 'Manuel'})
    assert manuel['surname'] == 'Neuer'

从 humongous 迁移

在将包名从 humongous 迁移到 pytest-mongodb 的过程中,大多数以前带有 humongous_ 前缀的配置值已被重命名为具有 mongodb_-前缀的对应项。唯一的例外是 humongous_basedir 配置值,现在命名为 mongodb_fixture_dir。此外,命令行选项已统一,多词选项名称现在一致地用连字符而不是下划线分隔。

项目详情


下载文件

下载适合您平台的文件。如果您不确定要选择哪个,请了解有关 安装包 的更多信息。

源分发

pytest-mongodb-2.4.0.tar.gz (7.2 kB 查看哈希值)

上传时间

构建分发

pytest_mongodb-2.4.0-py3-none-any.whl (5.1 kB 查看哈希值)

上传时间 Python 3

由以下支持