固件与设置/拆卸
使用固件共享测试状态并设置资源。
固件与设置/拆卸 是 CoddyKit 上的免费 Python Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
什么是夹具?
夹具是使用 @pytest.fixture 修饰、用于提供测试依赖项的函数。pytest 会按名称注入这些依赖项。
import pytest
@pytest.fixture
def user():
return {"name": "Alice", "age": 30}
def test_name(user):
assert user["name"] == "Alice"使用 yield 进行设置与拆卸
在夹具内部生成夹具值,将设置(yield 之前)与拆卸(yield 之后)分开。
import pytest
@pytest.fixture
def db_connection():
conn = create_connection() # setup
yield conn
conn.close() # teardown
def test_query(db_connection):
result = db_connection.query("SELECT 1")
assert result is not None测试夹具作用域
使用 scope 控制测试夹具的创建频率:function(默认)、class、module、session。
import pytest
@pytest.fixture(scope="module")
def expensive_resource():
print("\nSetup once per module")
yield object()
print("\nTeardown once per module")通过 conftest.py 共享测试夹具
将测试夹具放入 conftest.py,即可在多个测试文件之间共享,而无需导入。
# conftest.py
import pytest
@pytest.fixture
def config():
return {"env": "test", "debug": True}
# test_app.py
def test_env(config):
assert config["env"] == "test"测试夹具依赖
测试夹具可以通过将其他测试夹具列为参数来依赖它们。
import pytest
@pytest.fixture
def base_url():
return "http://localhost:8000"
@pytest.fixture
def api_client(base_url):
return Client(base_url)
def test_get(api_client):
resp = api_client.get("/health")
assert resp.status_code == 200自动应用的测试夹具
设置 autouse=True,即可将测试夹具应用于作用域内的所有测试,而无需将其列为参数。
import pytest
@pytest.fixture(autouse=True)
def reset_env(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "test")
def test_env():
import os
assert os.environ["ENVIRONMENT"] == "test"tmp_path 测试夹具
pytest 提供内置测试夹具 tmp_path,为每个测试提供一个全新的临时目录。
def test_write_file(tmp_path):
f = tmp_path / "hello.txt"
f.write_text("hello")
assert f.read_text() == "hello"monkeypatch 测试夹具
monkeypatch 可让您在测试期间临时替换属性、环境变量或字典条目。
def get_env():
import os
return os.environ.get("MODE", "prod")
def test_mode(monkeypatch):
monkeypatch.setenv("MODE", "test")
assert get_env() == "test"capsys 测试夹具
capsys 会捕获测试期间 stdout 和 stderr 的输出。
def greet(name):
print(f"Hello, {name}!")
def test_greet(capsys):
greet("Alice")
out, err = capsys.readouterr()
assert out == "Hello, Alice!\n"使用 request.addfinalizer 注册测试夹具清理函数
这是 yield 的一种替代方式:使用 request.addfinalizer 注册清理操作。
import pytest
@pytest.fixture
def resource(request):
r = acquire_resource()
request.addfinalizer(r.release)
return r参数化测试夹具
在测试夹具中使用 params,即可针对每个参数值分别运行一次所有依赖它的测试。
import pytest
@pytest.fixture(params=["sqlite", "postgres"])
def db(request):
return create_db(request.param)
def test_insert(db):
db.insert({"id": 1})
assert db.count() == 1快速检查
哪种测试夹具作用域会在整个测试会话期间只创建一次测试夹具?
回顾
测试夹具通过 yield 提供可复用的设置和清理操作。使用 scope 控制生命周期,使用 conftest.py 实现共享,并使用 autouse=True 隐式应用测试夹具。
常见问题解答
「固件与设置/拆卸」课时是免费的吗?
是的 — 「固件与设置/拆卸」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「固件与设置/拆卸」这节课中我会学到什么?
使用固件共享测试状态并设置资源。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「固件与设置/拆卸」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。