之前有介绍过 TestContainers 在 .NET 的使用方式 传送们,同样的 Python 也可以使用它;我将使用 WSL + Python 环境搭建起开发环境。
开发环境
- Windows 11 Home
- PyCharm
- Windows Terminal
- WSL2
- Ubuntu 24.04
- Python 3.12.3
安装 uv
sudo apt install pipx
pipx install uv
pipx ensurepath
重新启动,Ctrl+D 关闭 Terminal
再进入 Ubuntu 就可以使用 uv 了
用 WSL 建立专案
选择 IDE 版本以及专案路径
预设专案开起来就长这样,按下 F5,可以观察到执行结果
新增 Interpreter,选择 uv
安装 TestContainers
uv add testcontainers-postgres testcontainers-redis pytest
在 test.py 添加以下内容,下面的程式码很简单,
- 把 postgres container 挂起来。
- 塞资料进去。
- 验证资料有没有塞成功。
from testcontainers.postgres import PostgresContainer
import psycopg2
class TestDatabases:
def test_postgres_connection(self):
_image = "postgres:latest"
_user = "postgres"
_password = "postgres"
_dbname = "test_db"
# 启动 PostgresSQL 容器
postgres_container = PostgresContainer(
image=_image,
user=_user,
password=_password,
dbname=_dbname
)
try:
# 启动容器
postgres_container.start()
host = postgres_container.get_container_host_ip()
port = postgres_container.get_exposed_port(5432)
# 建立数据库连接
conn = psycopg2.connect(
host=host,
port=port,
user=_user,
password=_password,
dbname=_dbname
)
cursor = conn.cursor()
# 测试数据库操作
cursor.execute("CREATE TABLE test (id serial PRIMARY KEY, name VARCHAR);")
cursor.execute("INSERT INTO test (name) VALUES (%s)", ("test_name",))
conn.commit()
cursor.execute("SELECT * FROM test;")
result = cursor.fetchone()
assert result[1] == "test_name"
# 清理
cursor.close()
conn.close()
finally:
postgres_container.stop()
执行测试后观察结果
心得
这是一个简单的範例,不知道为什么 TestContainers 无法在 Windows 的环境下执行,它会卡在 postgres_container.start()就部会动作,postgres container 也顺利的长出来,但不知道为什么不会往下执行。
範例位置
https://github.com/yaochangyu/sample.dotblog/tree/master/Test/Lab.Py.TestContainer
若有谬误,烦请告知,新手发帖请多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET