virusdefender's blog ʕ•ᴥ•ʔ

使用Python的mock模拟测试

最近写的项目里面有一个创建预约成功后就给客户发一条短信或者邮件的功能,但是怎么去自动化的测试这个功能呢,难道每次都要发送一遍,然后去看么。这时候我们就可以引入Python的mock测试,我们首先来看一个网上流传的比较广的教程里面的例子。

1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5
6def rm(filename):
7    os.remove(filename)

然后测试是这样的

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import rm
 5
 6import os.path
 7import tempfile
 8import unittest
 9
10class RmTestCase(unittest.TestCase):
11
12    tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-testfile")
13
14    def setUp(self):
15        with open(self.tmpfilepath, "wb") as f:
16            f.write("Delete me!")
17        
18    def test_rm(self):
19        # remove the file
20        rm(self.tmpfilepath)
21        # test that it was actually removed
22        self.assertFalse(os.path.isfile(self.tmpfilepath), "Failed to remove the file.")

使用mock改写后的测试是这样的

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import rm
 5
 6import mock
 7import unittest
 8
 9class RmTestCase(unittest.TestCase):
10    
11    @mock.patch('mymodule.os')
12    def test_rm(self, mock_os):
13        rm("any path")
14        # test that rm called os.remove with the right parameters
15        mock_os.remove.assert_called_with("any path")

上面用到了assert_called_with(*args, **kwargs)按照官方文档,这就是assert这个方法被调用的一个简介的方法(翻译好别扭) This method is a convenient way of asserting that calls are made in a particular way:

1mock = Mock()
2mock.method(1, 2, 3, test='wow')
3<Mock name='mock.method()' id='...'>
4mock.method.assert_called_with(1, 2, 3, test='wow')

然后修改了一下删除文件的代码,删除之前先去判断一下文件是否存在

1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5import os.path
6
7def rm(filename):
8    if os.path.isfile(filename):
9        os.remove(filename)

相应的单元测试是这样的

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import rm
 5
 6import mock
 7import unittest
 8
 9class RmTestCase(unittest.TestCase):
10    
11    @mock.patch('mymodule.os.path')
12    @mock.patch('mymodule.os')
13    def test_rm(self, mock_os, mock_path):
14        # set up the mock
15        mock_path.isfile.return_value = False
16        
17        rm("any path")
18        
19        # test that the remove call was NOT called.
20        self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
21        
22        # make the file 'exist'
23        mock_path.isfile.return_value = True
24        
25        rm("any path")
26        
27        mock_os.remove.assert_called_with("any path")

里面用到了return_value这个方法,这个就是设置mock的返回值的,比如

1mock = Mock()
2mock.return_value = 'fish'
3mock()
4>>>'fish'

is_called方法就是看这个方法是否被调用,前面的assert_called_with就是在这个的基础上来的。

然后上面的那些都是mock的一些函数,下面我们将测试去mock一下类和实例。 我们将上面删除文件的函数改写成这样的

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4import os
 5import os.path
 6
 7class RemovalService(object):
 8    """A service for removing objects from the filesystem."""
 9    
10    #这个self貌似是原作者笔误漏掉了
11    def rm(self, filename):
12        if os.path.isfile(filename):
13            os.remove(filename)

然后单元测试是这样的

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import RemovalService
 5
 6import mock
 7import unittest
 8
 9class RemovalServiceTestCase(unittest.TestCase):
10    
11    @mock.patch('mymodule.os.path')
12    @mock.patch('mymodule.os')
13    def test_rm(self, mock_os, mock_path):
14        # instantiate our service
15        reference = RemovalService()
16        
17        # set up the mock
18        mock_path.isfile.return_value = False
19        
20        reference.rm("any path")
21        
22        # test that the remove call was NOT called.
23        self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
24        
25        # make the file 'exist'
26        mock_path.isfile.return_value = True
27        
28        reference.rm("any path")
29        
30        mock_os.remove.assert_called_with("any path")

我们现在想知道RemovalService是否正常工作,我们先声明它为一个实例。在另外的一个类里面调用它。

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4import os
 5import os.path
 6
 7class RemovalService(object):
 8    """A service for removing objects from the filesystem."""
 9
10    def rm(self, filename):
11        if os.path.isfile(filename):
12            os.remove(filename)
13            
14
15class UploadService(object):
16
17    def __init__(self, removal_service):
18        self.removal_service = removal_service
19        
20    def upload_complete(self, filename):
21        self.removal_service.rm(filename)

到目前为止,我们的测试已经覆盖了RemovalService, 我们就不用对我们测试用例中UploadService的内部函数rm进行验证了。相反,我们将调用UploadService的RemovalService.rm方法来进行简单的测试(为了不产生其他副作用),我们通过之前的测试用例可以知道它可以正确地工作。 有两种方法可以实现以上需求:

模拟实例方法 该模拟库有一个特殊的方法用来装饰模拟对象实例的方法和参数。使用@mock.patch.object 进行装饰

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import RemovalService, UploadService
 5
 6import mock
 7import unittest
 8
 9class RemovalServiceTestCase(unittest.TestCase):
10    
11    @mock.patch('mymodule.os.path')
12    @mock.patch('mymodule.os')
13    def test_rm(self, mock_os, mock_path):
14        # instantiate our service
15        reference = RemovalService()
16        
17        # set up the mock
18        mock_path.isfile.return_value = False
19        
20        reference.rm("any path")
21        
22        # test that the remove call was NOT called.
23        self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
24        
25        # make the file 'exist'
26        mock_path.isfile.return_value = True
27        
28        reference.rm("any path")
29        
30        mock_os.remove.assert_called_with("any path")
31      
32      
33class UploadServiceTestCase(unittest.TestCase):
34
35    @mock.patch.object(RemovalService, 'rm')
36    def test_upload_complete(self, mock_rm):
37        # build our dependencies
38        removal_service = RemovalService()
39        reference = UploadService(removal_service)
40        
41        # call upload_complete, which should, in turn, call `rm`:
42        reference.upload_complete("my uploaded file")
43        
44        # check that it called the rm method of any RemovalService
45        mock_rm.assert_called_with("my uploaded file")
46        
47        # check that it called the rm method of _our_ removal_service
48        removal_service.rm.assert_called_with("my uploaded file")

这里有一个使用修饰符的陷阱,就是使用修饰符的顺序和参数的顺序 比如说

1@mock.patch('mymodule.sys')
2    @mock.patch('mymodule.os')
3    @mock.patch('mymodule.os.path')
4    def test_something(self, mock_os_path, mock_os, mock_sys):
5        pass

然后实际情况是这样调用的 patch_sys(patch_os(patch_os_path(test_something))) 也就是说是相反的 由于这个关于sys的在最外层,因此会在最后被执行,使得它成为实际测试方法的最后一个参数。请特别注意这一点,并且在做测试使用调试器来保证正确的参数按照正确的顺序被注入。

创建一个mock实例 我们可以在UploadService的构造函数中提供一个模拟测试实例,而不是模拟创建具体的模拟测试方法。

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4from mymodule import RemovalService, UploadService
 5
 6import mock
 7import unittest
 8
 9class RemovalServiceTestCase(unittest.TestCase):
10    
11    @mock.patch('mymodule.os.path')
12    @mock.patch('mymodule.os')
13    def test_rm(self, mock_os, mock_path):
14        # instantiate our service
15        reference = RemovalService()
16        
17        # set up the mock
18        mock_path.isfile.return_value = False
19        
20        reference.rm("any path")
21        
22        # test that the remove call was NOT called.
23        self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
24        
25        # make the file 'exist'
26        mock_path.isfile.return_value = True
27        
28        reference.rm("any path")
29        
30        mock_os.remove.assert_called_with("any path")
31      
32      
33class UploadServiceTestCase(unittest.TestCase):
34
35    #原作者这里还有一个参数是mock_rm,没用吧?
36    def test_upload_complete(self):
37        # build our dependencies
38        mock_removal_service = mock.create_autospec(RemovalService)
39        reference = UploadService(mock_removal_service)
40        
41        # call upload_complete, which should, in turn, call `rm`:
42        reference.upload_complete("my uploaded file")
43        
44        # test that it called the rm method
45        mock_removal_service.rm.assert_called_with("my uploaded file")

mock库包含两个重要的类mock.Mock和mock.MagicMock,大多数内部函数都是建立在这两个类之上的。在选择使用mock.Mock实例,mock.MagicMock实例或auto-spec方法的时候,通常倾向于选择使用 auto-spec方法,因为它能够对未来的变化保持测试的合理性。这是因为mock.Mock和mock.MagicMock会无视底层的API,接受所有的方法调用和参数赋值。比如下面这个用例:

1class Target(object):
2    def apply(value):
3        return value
4
5def method(target, value):
6    return target.apply(value)

We can test this with a mock.Mock instance like this:

1class MethodTestCase(unittest.TestCase):
2
3    def test_method(self):
4        target = mock.Mock()
5
6        method(target, "value")
7
8        target.apply.assert_called_with("value")

This logic seems sane, but let’s modify the Target.apply method to take more parameters:

1class Target(object):
2    def apply(value, are_you_sure):
3        if are_you_sure:
4            return value
5        else:
6            return None

重新运行你的测试,然后你会发现它仍然能够通过。这是因为它不是针对你的API创建的。这就是为什么你总是应该使用create_autospec方法,并且在使用@patch和@patch.object装饰方法时使用autospec参数。

提交评论 | 微信打赏 | 转载必须注明原文链接

#Python