编写您的第一个 pytest 测试
了解测试发现、assert 语句和测试结构。
编写您的第一个 pytest 测试 是 CoddyKit 上的免费 Python Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
安装 pytest
使用 pip 安装 pytest。它不要求任何强制配置,会自动发现测试。
# pip install pytest
# Run all tests
# pytest
# Run a specific file
# pytest test_math.py简单的测试函数
pytest 会收集所有以 test_ 开头的函数。请使用普通的 assert 语句——pytest 会重写它们,以输出详细信息。
# test_math.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0测试文件与发现机制
pytest 会发现名为 test_*.py 或 *_test.py 的测试文件,并收集名为 test_* 的函数或名为 Test* 的类。
tests/
test_utils.py
test_models.py
conftest.py # shared fixtures在类中组织测试
将相关测试归类到以 Test 为前缀的类中。不要求使用 unittest.TestCase。
class TestCalculator:
def test_add(self):
assert 1 + 1 == 2
def test_multiply(self):
assert 3 * 4 == 12测试异常
使用 pytest.raises 作为上下文管理器,断言特定异常会被引发。
import pytest
def divide(a, b):
if b == 0:
raise ZeroDivisionError("cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError, match="cannot divide"):
divide(10, 0)-v 标志
使用 -v(详细模式)运行 pytest,以查看每个测试名称及其通过或失败的状态。
# pytest -v
# test_math.py::test_add PASSED
# test_math.py::test_add_negative PASSED
# Show print output too:
# pytest -v -s跳过测试
使用 @pytest.mark.skip 或 @pytest.mark.skipif 有条件地跳过测试。
import pytest, sys
@pytest.mark.skip(reason="not implemented yet")
def test_future_feature():
assert False
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_only():
assert True将测试标记为预期失败
@pytest.mark.xfail 用于标记您预期会失败的测试。测试失败时算作通过,意外通过时则发出警告。
import pytest
@pytest.mark.xfail(reason="known bug #42")
def test_buggy():
assert 1 == 2 # will fail, but that's expectedassert 重写
pytest 会重写 assert 语句,显示导致失败的值——这比单独的 AssertionError 有用得多。
def test_list_equal():
result = [1, 2, 4]
expected = [1, 2, 3]
assert result == expected
# AssertionError:
# assert [1, 2, 4] == [1, 2, 3]
# At index 2 diff: 4 != 3conftest.py
pytest 会自动加载 conftest.py。请将共享夹具和插件放在这里,无需显式导入。
# conftest.py
import pytest
@pytest.fixture
def sample_data():
return {"key": "value"}
# Any test file in the same dir can use sample_data as a parameter运行部分测试
使用 -k 运行与关键字表达式匹配的测试。
# Run tests containing "add"
# pytest -k "add"
# Run tests NOT containing "slow"
# pytest -k "not slow"
# Run a specific test
# pytest test_math.py::test_add快速检查
pytest 测试函数的名称必须以什么前缀开头,才能被自动发现?
回顾
pytest 不需要样板代码:将文件命名为 test_*.py,将函数命名为 test_*,并使用普通的 assert。使用 pytest.raises 测试异常,使用 -v 输出详细信息,并使用 conftest.py 存放共享夹具。
常见问题解答
「编写您的第一个 pytest 测试」课时是免费的吗?
是的 — 「编写您的第一个 pytest 测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「编写您的第一个 pytest 测试」这节课中我会学到什么?
了解测试发现、assert 语句和测试结构。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「编写您的第一个 pytest 测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 编写您的第一个 pytest 测试
- 固件与设置/拆卸
- 参数化与测试覆盖率
- 使用 unittest.mock 进行模拟