091-Python单元测试(一)
今天我们来学习Python Unit Testing 单元测试
先来一个简单的例子
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError('Can not divide by zero.')
return x / y
我们写好了4个简单的算术方法,
现在我们想要用Unit Test来测试一下这4个方法
import unittest
import test01
class Test01(unittest.TestCase):
def test_add(self):
result = test01.add(10, 5)
self.assertEqual(result, 15)
def test_subtract(self):
result = test01.subtract(10, 5)
self.assertEqual(result, 5)
def test_multiply(self):
result = test01.multiply(10, 5)
self.assertEqual(result, 50)
def test_divide(self):
result = test01.divide(10, 5)
self.assertEqual(result, 2)
我们用assertEqual来验证每个方法的结果
测试运行的结果是
Ran 4 tests in 0.003s
OK
意思是运行了4个测试,通过了
那么如果测试失败了是什么样的呢,
比如我们把add结果改成0
0 != 15
Expected :15
Actual :0
<Click to see difference>
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2019.2.4\plugins\python\helpers\pycharm\teamcity\diff_tools.py", line 32, in _patched_equals
old(self, first, second, msg)
File "C:\Users\lich-howger\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 852, in assertEqual
assertion_func(first, second, msg=msg)
File "C:\Users\lich-howger\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 845, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 15 != 0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\lich-howger\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\Users\lich-howger\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 628, in run
testMethod()
File "C:\D\Project\PythonProject\PythonTest1119\test20200607\test01_test.py", line 8, in test_add
self.assertEqual(result, 0)
Ran 1 test in 0.005s
FAILED (failures=1)
Process finished with exit code 1
Assertion failed
Assertion failed
Assertion failed
这就显示了失败的结果
我继续修改一下add代码
试着测试一下负数相加的结果
import unittest
import test01
class Test01(unittest.TestCase):
def test_add(self):
self.assertEqual(test01.add(10, 5), 15)
self.assertEqual(test01.add(1, 1), 2)
self.assertEqual(test01.add(-5, 5), 0)
self.assertEqual(test01.add(-5, -10), -15)
结果为:
Ran 1 test in 0.002s
OK
来看一下所有的 assert方法
Method | Checks that | New in |
assertEqual(a, b) | a == b | |
assertNotEqual(a, b) | a != b | |
assertTrue(x) | bool(x) is True | |
assertFalse(x) | bool(x) is False | |
assertIs(a, b) | a is b | 3.1 |
assertIsNot(a, b) | a is not b | 3.1 |
assertIsNone(x) | x is None | 3.1 |
assertIsNotNone(x) | x is not None | 3.1 |
assertIn(a, b) | a in b | 3.1 |
assertNotIn(a, b) | a not in b | 3.1 |
assertIsInstance(a, b) | isinstance(a, b) | 3.2 |
assertNotIsInstance(a, b) | not isinstance(a, b) | 3.2 |
Method | Checks that | New in |
assertRaises(exc, fun, *args, **kwds) | fun(*args, **kwds) raises exc | |
assertRaisesRegex(exc, r, fun, *args, **kwds) | fun(*args, **kwds) raises exc and the message matches regex r | 3.1 |
assertWarns(warn, fun, *args, **kwds) | fun(*args, **kwds) raises warn | 3.2 |
assertWarnsRegex(warn, r, fun, *args, **kwds) | fun(*args, **kwds) raises warn and the message matches regex r | 3.2 |
assertLogs(logger, level) | The with block logs on logger with minimum level | 3.4 |
在之前的divide方法,我们对除数是0的情况进行了判断
现在我们用 assertRaises方法对此进行测试
也就是当除数是0的时候,需要有ValueError
import unittest
import test01
class Test01(unittest.TestCase):
def test_add(self):
self.assertEqual(test01.add(10, 5), 15)
self.assertEqual(test01.add(1, 1), 2)
self.assertEqual(test01.add(-5, 5), 0)
self.assertEqual(test01.add(-5, -10), -15)
def test_divide(self):
self.assertEqual(test01.divide(10, 5), 2)
self.assertRaises(ValueError, test01.divide, 10, 0)
结果是
Ran 1 test in 0.012s
OK
还有另外一种写法
可以测试多次Error
import unittest
import test01
class Test01(unittest.TestCase):
def test_add(self):
self.assertEqual(test01.add(10, 5), 15)
self.assertEqual(test01.add(1, 1), 2)
self.assertEqual(test01.add(-5, 5), 0)
self.assertEqual(test01.add(-5, -10), -15)
def test_divide(self):
self.assertEqual(test01.divide(10, 5), 2)
self.assertRaises(ValueError, test01.divide, 10, 0)
# error
with self.assertRaises(ValueError):
test01.divide(5, 0)
test01.divide(10, 0)