defsquare(x): ''' 计算平方并返回结果 >>> square(2) 4 >>> square(3) 9 ''' return x * x
if __name__ == '__main__': import doctest, my_math doctest.testmod(my_math)
运行 python my_math.py -v 返回的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Trying: square(2) Expecting: 4 ok Trying: square(3) Expecting: 9 ok 1 items had no tests: my_math 1 items passed all tests: 2 tests in my_math.square 2 tests in2 items. 2 passed and0 failed. Test passed.
unittest
unittest 基于流行的 Java 测试框架 Junit 它更加灵活和强大。
使用模块 unitest 中的 TestCase 类编写一个测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import unittest, my_math
classProductTestCase(unittest.TestCase):
deftest_integers(self): for x inrange(-10, 10): for y inrange(-10, 10): p = my_math.product(x,y) self.assertEqual(p,x * y, 'Integer multiplication failed')
deftest_floats(self): for x inrange(-10, 10): for y inrange(-10, 10): x = x / 10 y = y / 10 p = my_math.product(x, y) self.assertEqual(p, x * y, 'Float multiplication failed')
if __name__ == '__main__': unittest.main()
运行结果:
1 2 3
Ran 2 tests in0.000s
OK
pytest
pytest 库是一组工具,可以帮助轻松的编写测试,而且能持续支持随项目增大而变得复杂的测试。
安装 pytest
Python 默认不包含 pytest ,需要通过第三方包进行安装:
1
pip3 install pytest
编写需要测试的代码
在 name_function.py 中编写 get_formatted_name 方法:
1 2 3 4 5 6 7 8 9
defget_formatted_name(first, last): """生成格式规范的名字 Args: first (string): 名字 last (string): 姓 """ full_name = f"{first}{last}" return full_name.title()
编写一个使用该方法的程序 names.py :
1 2 3 4 5 6 7 8 9 10 11
from name_function import get_formatted_name
print("Enter 'q' at any time to quit.") whileTrue: first = input("\nPlease give me a first name: ") if first == 'q': break last = input("\nPlease give me a last name: ") if last == 'q': break
评论· · · · · ·