本文目录导读:

是的,Testcontainers 支持 Python!Python 版本的 Testcontainers 是一个独立的库,名为 testcontainers(注意是复数形式)。
安装
pip install testcontainers
或者安装特定模块的额外依赖:
# 例如支持 PostgreSQL pip install testcontainers[postgresql] # 或支持 Redis、MySQL 等 pip install testcontainers[redis] pip install testcontainers[mysql]
基本使用示例
from testcontainers.postgres import PostgresContainer
import psycopg2
def test_database_connection():
# 启动 PostgreSQL 容器
with PostgresContainer("postgres:13") as postgres:
# 获取连接信息
connection_url = postgres.get_connection_url()
# 连接数据库
conn = psycopg2.connect(connection_url)
cur = conn.cursor()
# 执行查询
cur.execute("SELECT version();")
print(cur.fetchone())
支持的模块
Testcontainers for Python 支持多种服务:
- 数据库:PostgreSQL、MySQL、MariaDB、MSSQL、Oracle、ClickHouse
- 消息队列:Redis、RabbitMQ、Kafka
- NoSQL:MongoDB、Cassandra、Neo4j
- Web 服务:Nginx、Httpbin
- 云服务:LocalStack(模拟 AWS)、Docker Compose
自定义容器
如果需要自定义配置:
from testcontainers.generic import DockerContainer
with DockerContainer("nginx:latest") as nginx:
nginx.with_env("NGINX_HOST", "localhost")
# 或者映射端口
nginx.with_bind_ports(80, 8080)
# 使用容器
集成测试框架
Testcontainers 可以很好地与 pytest、unittest 等 Python 测试框架配合使用:
import pytest
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="module")
def postgres_container():
with PostgresContainer("postgres:13") as postgres:
yield postgres
def test_something(postgres_container):
# 使用容器
pass
注意事项
- 需要 Docker 环境(Docker Desktop 或 Docker Engine)
- 版本兼容性:Python 3.7+
- 可以使用
testcontainers配置日志级别等
Testcontainers for Python 功能完善,支持主流服务,社区活跃,适合在 Python 测试中使用。