Overview
本教程介绍如何添加 pytest 固定装置来运行针对MongoDB 的测试并使用事务回滚更改。它还展示了如何使用 hatchling 库包Python库并将包发布到 PyPI。
赛程
pytest 中的固定装置是创建用于单元测试的资源的函数。通常,fixtures 在项目目录中名为 conftest.py 的文件中定义。您可以使用 yield声明向测试函数返回一个值。
每个装置都有一个作用域,用于控制装置的运行频率。以下装置 sample_fixture 使用默认作用域 function。这意味着 pytest 在每个使用该装置的测试函数之前运行该装置。该装置使用 yield声明将字符串 "Hello, World" 返回给测试函数。
def sample_fixture(): # Code before the test runs yield "Hello, World" # Code after the test runs
先决条件
在开始本教程之前,请完成以下步骤:
运行以下命令以在您的环境中安装
pytest:pip install -U pytest 找到您在上一步中复制的MongoDB连接字符串。运行以下命令,将连接字符串存储在
MDB_URI环境变量中:export MDB_URI="<your connection string>" 安装
build和twine软件包以包并发布您的库。build包会安装构建依赖项并打包您的项目,而twine包则会将您的包安全地上传到 PyPI。python -m pip install --upgrade build twine
创建和测试 pytest 装置
本部分教程包括以下任务:
为
MongoClient对象和回滚会话添加pytest固定装置编写使用这些装置的测试
添加 MongoClient 设备
以下代码示例显示了一个名为 mongodb 的装置。该装置使用 MDB_URI 环境变量中的连接字符串来创建 MongoClient对象,然后确保它可以连接到指定的MongoDB 部署。该装置具有 session 作用域,这意味着 pytest 在测试会话开始时运行该装置,并将其重复用于所有测试。
此固定装置通过将 mongodb 固定装置作为函数参数来使用。这指示 pytest 将 mongodb 作为参数传递给固定装置。
将以下代码添加到名为 conftest.py 的文件中:
import pytest import pymongo import os 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 ===============================
添加回滚会话固定装置
如果您的测试修改了MongoDB中的数据,但您不希望这些更改持续存在,则可以使用ACID 事务在每次测试后回滚这些更改。为此,请在装置中执行以下步骤:
创建会话
启动事务
让会话进行测试
测试运行后中止ACID 事务
以下代码示例中的装置实现了此模式:
def 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库
在本节中,您可以学习;了解如何通过执行以下操作来包示例Python库:
描述包
构建包
将包发布到 PyPI
描述包
在名为 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"
构建包
要从包构建版,请在项目目录中运行以下命令:
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
发布到 PyPI
构建后,您可以使用 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包和代码的更多信息,请参阅以下资源: