之前有介紹過 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