Mock库的应用
Mock在Python3.3之前是第三方库,需要安装 pip install Mock ;导入 import mock
Mock在Python3.3之后是Python标准库,导入方式为 from unittest import mock
Mock能够让我们模拟单元测试中不可用或繁重的资源;还可以模拟Python对象的行为
Mock 使用的原因:
一、环境由于客观原因由于无法搭建
二、搭建服务器的值需要大量工作才行
实现代码如下:
import requests
import shutil
def send_Mock(url):
r = requests.get(url)
return r.status_code
def visit_Mock():
return send_Mock("http://www.Teacherketang.com/")
class Remove(object):
def rmdir(self,path="E:/"):
re = shutil.rmtree(path)
if re == None:
return "seccess"
else:
return "fail"
def exists_get_rmdir(self):
return self.rmdir()
调用模块
from Mock_Test import Client_Mock
import unittest
from unittest import mock
class Mock_Test(unittest.TestCase):
def setUp(self):
self.r = Client_Mock.Remove()
def test_success_mock(self):
success_mock = mock.Mock(return_value="200")
Client_Mock.send_Mock = success_mock
self.assertEqual(Client_Mock.visit_Mock(),"200")
def test_fail_mock(self):
fail_mock = mock.Mock(return_value="404")
Client_Mock.send_Mock = fail_mock
self.assertEqual(Client_Mock.visit_Mock(), "404")
def test_remove_success(self):
remove_success = mock.Mock(return_value="success")
self.r.rmdir = remove_success
self.assertEqual(self.r.exists_get_rmdir(),remove_success())
def test_remove_fail(self):
remove_fail = mock.Mock(return_value="fail")
self.r.rmdir = remove_fail
self.assertEqual(self.r.exists_get_rmdir(),remove_fail())
if __name__ == '__main__':
unittest.main(verbosity=2)