mock 功效
完成功能测试
1 | # module.py |
解决测试依赖
例如,我们要测试A模块,然后A模块依赖于B模块的调用。但是,由于B模块的改变,导致了A模块返回结果的改变,从而使A模块的测试用例失败。其实,对于A模块,以及A模块的用例来说,并没有变化,不应该失败才对。这个时候就是mock发挥作用的时候了。通过mock模拟掉影响A模块的部分(B模块)。至于mock掉的部分(B模块)应该由其它用例来测试。
add_and_multiply()函数依赖了multiply()函数的返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 # function.py
def add_and_multiply(x, y):
addition = x + y
multiple = multiply(x, y)
return (addition, multiple)
def multiply(x, y):
return x * y
# test.py
import unittest
import function
class MyTestCase(unittest.TestCase):
def test_add_and_multiply(self):
x = 3
y = 5
addition, multiple = function.add_and_multiply(x, y)
self.assertEqual(8, addition)
self.assertEqual(15, multiple)
if __name__ == "__main__":
unittest.main()
修改multiply()函数的代码,这样测试会失败
1
2 def multiply(x, y):
return x * y + 3
把 multiply()函数mock掉,解决依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import unittest
from unittest.mock import patch
import function
class MyTestCase(unittest.TestCase):
# patch()装饰/上下文管理器可以很容易地模拟类或对象在模块测试。在测试过程中,您指定的对象将被替换为一个模拟(或其他对象),并在测试结束时还原。这里模拟function.py文件中multiply()函数。
def test_add_and_multiply2(self, mock_multiply):
# 在定义测试用例中,将mock的multiply()函数(对象)重命名为 mock_multiply对象。
x = 3
y = 5
mock_multiply.return_value = 15
# 设定mock_multiply对象的返回值为固定的15。
addition, multiple = function.add_and_multiply(x, y)
mock_multiply.assert_called_once_with(3, 5)
# 检查mock_multiply方法的参数是否正确。
self.assertEqual(8, addition)
self.assertEqual(15, multiple)
if __name__ == "__main__":
unittest.main()
Mock attributes in Python mock?
1 | with patch('requests.post') as patched_post: |
Mock session in requests library?
1 | # main.py |
assert 常用断言速查
项目 | 举例 |
---|---|
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertGreater(a, b) | a > b |
assertGreaterEqual(a, b) | a >= b |
assertLess(a, b) | a < b |
assertLessEqual(a, b) | a <= b |
assertTrue(x) | bool(x) is True |
assertFalse(x) | bool(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) |
干货:mock模板(requests)
1 | # common_test.py |