SuperAPI AI 工具集

verify-with-inline-tests

测试与质量

查看项目

更新于 10-16 10:11

技能介绍

verify-with-inline-tests 是一种把测试直接放到被测试代码所在文件里的实践模式。它的出发点是测试应当靠近代码,同时让测试本身承担文档和示例的作用。

适用场景

根据资料,该模式适用于以下情况:测试应当靠近代码;测试要作为文档使用;单文件模块;以及开发过程中的快速验证。

不适用场景

资料同时指出,以下情况不适合使用该模式:大型测试套件;需要测试隔离;CI/CD 期望测试位于特定位置。

核心模式

该模式的做法是在模块中包含测试,并在模块被直接执行时运行它们,通常通过 if __name__ == '__main__': 实现。资料给出的基础示例如下:

def my_function(x): """Do something useful.""" return x * 2

def test(): """Run all tests.""" assert my_function(2) == 4 assert my_function(0) == 0 assert my_function(-1) == -2 print("All tests pass.")

if name == 'main': test()

示例

资料提供了来自 pytudes 的两个示例。

第一个是 sudoku.py 中的结构不变量测试:

sudoku.py - structural invariant tests

def test(): """A set of tests that must pass.""" assert len(squares) == 81 assert len(unitlist) == 27 assert all(len(units[s]) == 3 for s in squares) assert all(len(peers[s]) == 20 for s in squares) assert units['C2'] == [ ['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'], ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'] ] print('All tests pass.')

if name == 'main': test() solve_all(open("sudoku-easy50.txt"), "easy") solve_all(open("sudoku-top95.txt"), "hard")

第二个是 spell.py 中的综合单元测试:

spell.py - comprehensive unit tests

def unit_tests(): assert correction('speling') == 'spelling' assert correction('korrectud') == 'corrected' assert correction('bycycle') == 'bicycle' assert words('This is a TEST.') == ['this', 'is', 'a', 'test'] assert len(WORDS) == 32198 assert sum(WORDS.values()) == 1115585 assert 0.07 < P('the') < 0.08 return 'unit_tests pass'

if name == 'main': print(unit_tests()) spelltest(Testset(open('spell-testset1.txt')))

关键原则

资料列出以下关键原则:使用 if __name__ == '__main__':,仅在直接执行时运行测试;用断言编写测试,保持简单清晰;打印成功信息以确认测试确实运行;先测试结构,验证数据结构是否正确构建;让测试充当示例,展示函数如何使用。