🐍Python 工程与虚拟环境
测试与 pytest
面试回答
常见问法
unittest和pytest有什么区别?pytest的 fixture 是什么?作用域有哪些?monkeypatch和mock有什么区别?- 怎么测异步代码?怎么测数据库相关的代码?
回答
待补充:主线是「pytest 用最少样板写清表达力最强的测试」,配合 fixture / 参数化 / 插件生态说明生产力来源。
追问
conftest.py是怎么发现的?- fixture 的
function / class / module / session作用域怎么选? - 参数化(
@pytest.mark.parametrize)和 fixture 参数化的区别? - 怎么组织单元测试、集成测试、e2e 测试?
原理展开
- 核心概念:test function、assert、fixture、marker
- Fixture 作用域:function(默认)→ class → module → session,粒度越大越共享
- Monkeypatch:
monkeypatch.setattr / setenv,测试结束自动恢复 - Mock:
unittest.mock.patch,精确 mock 方法/对象 - 参数化:
@pytest.mark.parametrize('x,expected', [(1,2), ...]) - 常用插件:
pytest-asyncio / pytest-cov / pytest-mock / pytest-xdist / pytest-freezegun
易错点
- fixture 作用域太大,测试之间状态串扰
- 用
print调试测试,忘了-s参数 - mock 路径错(mock 应该 patch「被使用的地方」而不是「定义的地方」)
- 集成测试连真数据库,CI 里没有 teardown
记忆技巧
- 三件套:fixture(准备)+ assert(断言)+ parametrize(批量)
- Mock 口诀:patch where it’s used, not where it’s defined
- 作用域口诀:能小就小,能复用才升级