需要为搁置很久的代码修改功能,你是选择在原有代码上重构,还是重新写一份代码?因为有时候重构的时间,可能要比重写一份的时间要长,各种差错要处理,重构完可能也比较乱。因此,大家对于去修改与重构是比较逃避和排斥的,对自己曾经写的代码也不够有信心。
- 通过单元测试能给自己信心,同时能在重构过程中快速验证。
- 很多开源项目都有单元测试,里面有各种功能的测试,通过它能加速项目代码的理解
本文只提供一个视角,详细的使用方法可以参考文档和其它博客。
1. unittest简单使用
通过继承重写TestCase的类,来编写测试代码。
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
2.doctest简单使用
通过在注释中写测试代码和结果,doctest会根据这个执行测试。不过testunit更常用,这个比较有趣。
"""
This is the "example" module.
The example module supplies one function, factorial(). For example,
>>> factorial(5)
120
"""
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
本文讨论了在修改旧代码时,如何通过单元测试(如unittest和doctest)提高重构的效率和信心。作者强调了单元测试在重构过程中的重要性,以及如何通过继承TestCase类和在注释中编写测试来实现测试功能。
937





