Python 断言与测试断言
断言用于验证代码行为是否符合预期,是测试的核心机制。
assert 语句
Python
# 基本断言
assert 1 + 1 == 2
# 断言失败
# assert 1 + 1 == 3 # AssertionError
# 添加错误消息
assert 1 + 1 == 2, "计算结果不正确"
常用断言场景
Python
# 相等断言
assert value == expected
assert value != unexpected
# 类型断言
assert isinstance(obj, MyClass)
# 存在性断言
assert item in collection
assert item not in collection
# 真值断言
assert condition
assert not condition
# 空值断言
assert value is None
assert value is not None
unittest 断言方法
Python
import unittest
class TestAssertions(unittest.TestCase):
def test_equal(self):
self.assertEqual(1 + 1, 2)
self.assertNotEqual(1, 2)
def test_boolean(self):
self.assertTrue(1 == 1)
self.assertFalse(1 == 2)
def test_identity(self):
a = None
self.assertIsNone(a)
self.assertIsNotNone(1)
def test_in(self):
self.assertIn(1, [1, 2, 3])
self.assertNotIn(4, [1, 2, 3])
def test_type(self):
self.assertIsInstance(1, int)
self.assertNotIsInstance(1, str)
def test_comparison(self):
self.assertGreater(5, 3)
self.assertLess(3, 5)
def test_almost_equal(self):
# 浮点数近似相等
self.assertAlmostEqual(0.1 + 0.2, 0.3, places=7)
断言方法汇总
| 方法 | 说明 |
|---|---|
| assertEqual(a, b) | a == b |
| assertNotEqual(a, b) | a != b |
| assertTrue(x) | x is True |
| assertFalse(x) | x is False |
| assertIs(a, b) | a is b |
| assertIsNot(a, b) | a is not b |
| assertIsNone(x) | x is None |
| assertIsNotNone(x) | x is not None |
| assertIn(a, b) | a in b |
| assertNotIn(a, b) | a not in b |
| assertIsInstance(a, b) | isinstance(a, b) |
| assertNotIsInstance(a, b) | not isinstance(a, b) |
| assertGreater(a, b) | a > b |
| assertLess(a, b) | a < b |
| assertAlmostEqual(a, b) | 浮点近似相等 |
pytest 断言
Python
# pytest 直接使用 assert
def test_pytest_assertions():
assert 1 + 1 == 2
assert True
assert not False
assert 1 in [1, 2, 3]
assert isinstance(1, int)
assert len([1, 2, 3]) == 3
# 断言失败时的详细错误信息
# pytest 会自动显示变量值
浮点数断言
Python
import unittest
class FloatTest(unittest.TestCase):
def test_almost_equal(self):
# 指定精度比较
self.assertAlmostEqual(0.1 + 0.2, 0.3, places=7)
def test_with_delta(self):
# 指定允许误差
self.assertAlmostEqual(1.001, 1.0, delta=0.01)
# pytest 方式
def test_float():
assert abs(0.1 + 0.2 - 0.3) < 1e-7
异常断言
Python
import unittest
class ExceptionTest(unittest.TestCase):
def test_raises(self):
# unittest 方式
with self.assertRaises(ValueError):
int("invalid")
def test_exception_message(self):
with self.assertRaises(ValueError) as context:
raise ValueError("错误")
self.assertIn("错误", str(context.exception))
# pytest 方式
import pytest
def test_pytest_exception():
with pytest.raises(ValueError):
int("invalid")
with pytest.raises(ValueError, match="invalid"):
int("invalid")
断言失败处理
Python
# 断言失败后程序终止
def check_condition():
assert condition, "条件检查失败"
# 后续代码不会执行
# 测试中的断言
def test_example():
assert 1 == 1 # 通过继续
assert 2 == 2 # 通过继续
assert 3 == 4 # 失败,测试结束
要点总结
assert condition基本断言语法assert condition, "消息"添加失败信息- unittest 提供丰富的断言方法
- pytest 直接使用 assert 语句
assertAlmostEqual处理浮点数精度assertRaises测试异常抛出- 断言失败导致测试终止
- 断言是验证测试预期的核心手段
📝 发现内容有误?点击此处直接编辑