对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

教程:测试和打包Python库

本教程介绍如何添加 pytest 固定装置来运行针对MongoDB 的测试并使用事务回滚更改。它还展示了如何使用 hatchling 库包Python库并将包发布到 PyPI。

提示

使用标记进行编码

本教程基于“Coding with Mark”直播的第二集。您可以在MongoDB YouTube渠道上观看录制。

pytest 中的固定装置是创建用于单元测试的资源的函数。通常,fixtures 在项目目录中名为 conftest.py 的文件中定义。您可以使用 yield声明向测试函数返回一个值。

每个装置都有一个作用域,用于控制装置的运行频率。以下装置 sample_fixture 使用默认作用域 function。这意味着 pytest 在每个使用该装置的测试函数之前运行该装置。该装置使用 yield声明将 string "Hello, World" 返回给测试函数。

def sample_fixture(): # Code before the test runs yield "Hello, World" # Code after the test runs

在开始本教程之前,请完成以下步骤:

  1. 按照入门指南中的步骤安装PyMongo及其依赖项。请务必复制连接字符串,以便在后续步骤中使用。

  2. 运行以下命令以在您的环境中安装 pytest:

    pip install -U pytest
  3. 找到您在上一步中复制的MongoDB连接字符串。运行以下命令,将连接字符串存储在 MDB_URI 环境变量中:

    export MDB_URI="<your connection string>"
  4. 安装 build 和 twine 软件包以包并发布您的库。build包会安装构建依赖项并打包您的项目,而 twine包则会将您的包安全地上传到 PyPI。

    python -m pip install --upgrade build twine

本部分教程包括以下任务:

  1. 为 MongoClient对象和回滚会话添加 pytest 固定装置

  2. 编写使用这些装置的测试

: style: connected

1

为项目创建一个新目录,然后在终端中导航到该目录:

mkdir sample_applicationcd sample_application
2

以下代码示例显示了一个名为 mongodb 的装置。该装置使用 MDB_URI 环境变量中的连接字符串来创建 MongoClient对象,然后确保它可以连接到指定的MongoDB 部署。该装置具有 session 作用域,这意味着 pytest 在测试会话开始时运行该装置,并将其重复用于所有测试。

此固定装置通过将 mongodb 固定装置作为函数参数来使用。这指示 pytest 将 mongodb 作为参数传递给固定装置。

将以下代码添加到名为 conftest.py 的文件中:

import pytestimport pymongoimport os @pytest.fixture(scope="session")def mongodb(): client = pymongo.MongoClient(os.environ["MDB_URI"]) assert client.admin.command("ping")["ok"] != 0.0 yield client client.close()

要测试装置,请将以下代码添加到名为 test_mongodb_fixture.py 的文件中:

def test_mongodb_fixture(mongodb): """This test passes if `MDB_URI` is set to a valid connection string.""" assert mongodb.admin.command("ping")["ok"] > 0

通过在终端中执行以下命令来运行测试:

pytest test_mongodb_fixture.py

如果测试成功,则会打印类似于以下内容的消息:

============================= test session starts ==============================collected 1 item test_mongodb_fixture.py . [100%] ============================== 1 passed in 0.XXs ===============================
3

如果您的测试修改了MongoDB中的数据,但您不希望这些更改持续存在,则可以使用事务在每次测试后回滚这些更改。为此,请在装置中执行以下步骤:

  1. 创建会话

  2. 启动事务

  3. 让会话进行测试

  4. 测试运行后中止ACID 事务

以下代码示例中的装置实现了此模式:

@pytest.fixturedef rollback_session(mongodb): session = mongodb.start_session() session.start_transaction() try: yield session finally: session.abort_transaction()

前面的装置使用默认的function 作用域,因此 abort_transaction 在每个测试函数之后运行。

要测试装置,请将以下代码添加到名为 test_update_mongodb.py 的文件中:

def test_update_mongodb(mongodb, rollback_session): my_collection = mongodb["sample_db"]["sample_collection"] my_collection.insert_one( { "_id": "bad_document", "description": ( "If this still exists, then transactions are not working." ), }, session=rollback_session, ) assert ( my_collection.find_one( {"_id": "bad_document"}, session=rollback_session ) is not None )

注意

session Argument

将 session 参数传递给所有查询。这可确保它们是ACID 事务的一部分。

通过在终端中执行以下命令来运行测试:

pytest test_update_mongodb.py

如果测试成功,则会打印类似于以下内容的消息:

============================= test session starts ==============================collected 1 item test_update_mongodb.py . [100%] ============================== 1 passed in 0.XXs ===============================

在本节中,您可以学习;了解如何通过执行以下操作来包示例Python库:

  1. 描述包

  2. 构建包

  3. 将包发布到 PyPI

1

在名为 pyproject.toml 的文件中描述您的项目。以下文件描述了使用 hatchling构建后端的包:

[build-system]requires = ["hatchling"]build-backend = "hatchling.build" [project]name = "sample_application"version = "0.0.1"authors = [{ name = "<your name>", email = "<your email address>" }]description = "An example application to demonstrate packaging a Python project."requires-python = ">=3.10"dependencies = ["pymongo>=4.15.5"]classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Development Status :: 1 - Planning", "Intended Audience :: Developers", "Topic :: Database",] [tool.hatch.build.targets.wheel]packages = ["sample_application"] [project.urls]Homepage = "https://github.com/mongodb"

提示

更多 pyproject 设置

有关编写 pyproject.toml 文件的更多信息,请参阅编写 pyproject.toml。

2

要从包构建版,请在项目目录中运行以下命令:

python3 -m build

前面的步骤为您的包创建了一个轮子和 gzip 压缩包。如果构建操作成功,则会打印类似于以下内容的输出:

* Creating isolated environment: venv+pip...* Installing packages in isolated environment: - hatchling* Getting build dependencies for sdist...* Building sdist...* Building wheel from sdist* Creating isolated environment: venv+pip...* Installing packages in isolated environment: - hatchling* Getting build dependencies for wheel...* Building wheel...Successfully built sample_application-0.0.1.tar.gz and sample_application-0.0.1-py3-none-any.whl
3

构建后,您可以使用 twine 上传轮子和 gzip 压缩的 tarball。要上传这些文件,请在项目目录中运行以下命令:

python3 -m twine upload dist/*

成功上传会产生类似于以下消息的输出:

* Uploading distributions to https://upload.pypi.org/legacy/* Enter your username:* Enter your password:* Uploading sample_application-0.0.1-py3-none-any.whl* Uploading sample_application-0.0.1.tar.gz* View at: https://pypi.org/project/sample_application/0.0.1/

有关本教程中使用的Python包和代码的更多信息,请参阅以下资源: