mock在Python3.3之前是第三方的库,在Pyhton3.3版本之后是标准库,只需要导入就可以使用了.
Pyhton3.3版本之前引入方式是:
import mock
Pyhton3.3版本之后引入方式是:现在已经被整合到unittest的标准库⾥⾯
from unittest import mock
Mock的意义:Mocks能够让我们模拟那些在单元测试中不可用或太笨重的资源
Mock是Python中一个用于支持单元测试的库,它的主要功能是使用mock对象替代掉指定的Python对象,
以达到模拟对象的行为。Mock它可以替换Python对象。
现实情况:
1、环境由于客观原因导致无法搭建
2、搭建的服务器需要的值需要大量的工作才可以
案例一、使⽤mock模拟类⾥⾯的⽅法
1 from unittest import mock
2 class MockObj:
3 def info(self):
4 return 'Hello Mock'
5
6 '''使⽤mock模拟类⾥⾯的⽅法'''
7 obj=mock.Mock()
8 obj.info.return_value='Hello Mock'
9
10 '''测试是否模拟成功'''
11 if MockObj().info()==obj.info():
12 print('模拟成功')
13 else:
14 print('请检查,mock模拟类的⽅法模拟失败')
案例二、模拟访问网站的方法是否正确(网站无搭建环境,使用mock模拟)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import requests
2
3 def send_url(url):
4 r=requests.get(url)
5 return r.status_code
6
7 def visit_url():
8 return send_url('http://www.ccccoooo.com')
url_dec.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import unittest
2 from unittest import mock
3 from mock_test import url_dec
4
5 class url_Test(unittest.TestCase):
6
7 def test_success_url(self):
8 success_url=mock.Mock(return_value='200')
9 url_dec.send_url=success_url
10 self.assertEqual(url_dec.visit_url(),'200')
11
12 def test_fail_url(self):
13 fail_url=mock.Mock(return_value='404')
14 url_dec.send_url=fail_url
15 self.assertEqual(url_dec.visit_url(),'404')
16
17 if __name__ == '__main__':
18 unittest.main(verbosity=2)
url_test.py
案例三、模拟一个函数(删除C盘下Windows的⽂件夹),测试此函数的准确性(只能使用模拟手段),
模拟不要运行删除C盘!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import os
2 import unittest
3 from unittest import mock
4
5 class OsRemove:
6 def delWindows(self,path='c:/Windows'):
7 obj=os.rmdir(path)
8 if obj==None:
9 return 'success'
10 else:
11 return 'fail'
12
13 def existsWindows(self):
14 return self.delWindows()
15
16
17 '''测试代码'''
18 class TestWin(unittest.TestCase):
19 def setUp(self) -> None:
20 self.r=OsRemove()
21
22 def test_delWindows_success(self):
23 '''删除⽬录成功'''
24 success_obj=mock.Mock(return_value='success')
25 self.r.delWindows=success_obj
26 self.assertEqual(self.r.existsWindows(),success_obj())
27
28 def test_delWindows_fail(self):
29 '''删除⽬录失败'''
30 fail_obj=mock.Mock(return_value='fail')
31 self.r.delWindows=fail_obj
32 self.assertEqual(self.r.existsWindows(),fail_obj())
33
34 if __name__ == '__main__':
35 unittest.main(verbosity=2)
mock_delWindows_test.py
mock中使用patch或者patch.object的目的是为了控制mock的范围,模拟的类或者模拟的函数,
使用with语句范围内mock一个对象。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python
2 #!coding:utf-8
3
4 from unittest import mock
5 import requests
6 import unittest
7 from types import SimpleNamespace
8
9 def send_request(url):
10 r=requests.get(url)
11 return r.status_code
12
13 '''使⽤mock替换request.get(),直接返回⼀个固定的值'''
14 class WebTest(unittest.TestCase):
15 def setUp(self) -> None:
16 self.obj=requests.get
17
18 def test_success_200(self):
19 datas=SimpleNamespace(url='http://www.ccccoooo.com',code=200)
20 with mock.patch('requests.get') as get:
21 get.return_value.status_code=datas.code
22 self.assertEqual(send_request(datas.url),datas.code)
23
24 def test_success_404(self):
25 datas=SimpleNamespace(url='http://www.ccccoooo.com',code=404)
26 with mock.patch('requests.get') as get:
27 get.return_value.status_code=datas.code
28 self.assertEqual(send_request(datas.url),datas.code)
29
30 if __name__ == '__main__':
31 unittest.main(verbosity=2)
案例二修改优化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python
2 #!coding:utf-8
3
4 import os
5 import unittest
6 from unittest import mock
7 from types import SimpleNamespace
8
9 class OsRemove:
10 def delWindows(self,path='c:/Windows'):
11 return os.rmdir(path)
12
13 '''测试代码'''
14 class TestWin(unittest.TestCase):
15 def setUp(self) -> None:
16 self.r=OsRemove()
17
18 def test_delWindows_success_patch(self):
19 datas=SimpleNamespace(status='success')
20 with mock.patch('os.rmdir') as get:
21 get.return_value=datas.status
22 self.assertEqual(self.r.delWindows(),datas.status)
23
24 def test_delWindows_fail_patch(self):
25 datas=SimpleNamespace(status='fail')
26 with mock.patch('os.rmdir') as get:
27 get.return_value=datas.status
28 self.assertEqual(self.r.delWindows(),datas.status)
29
30 if __name__ == '__main__':
31 unittest.main(verbosity=2)
案例三修改优化
2022-11-5笔记