0 为什么要使用mock?
测试接口时,需要有对应的接口可以测试才行,否则要等后端开发完,才能进行,
mock模块可以模拟后端接口返回数据,提前根据接口文档准备好后端的静态数据
1mock基础用法
下载:
- python2:
pip install mock
- python3,无须单独安装
from unittest import mock
1) add 函数, mock(return_value),模拟函数返回值
方式一:
from unittest import mock
import unittest
def add(a, b):
pass
class TestAdd(unittest.TestCase):
def test_add(self):
add = mock.Mock(return_value = 7)
self.assertEqual(7, add(3, 4))
方式二:
class SimpleCaculator():
def sum(num1:int, num2:int):
return num1 +num2
#c测试用例类
class SumTest(unittest.TestCase):
def test(self):
s = SimpleCaculator()
num1 =10
num2=30
sum_result =mock.Mock(return_value=40)
s.sum = sum_result
self.assertEqual(s.sum(), 40)
2) http请求, mock(return_value),模拟接口返回值
self.req.visit=Mock(return_value={"msg":test_info["expected"]})
res = self.req.visit(test_info["method"],
test_info['url'],
json=eval(test_info["data"]),
headers=eval(self.headers))
from unittest import mock
import unittest
import requests
import logging
def visit(url,
params=None,
data=None,
json=None,
method='get',
**kwargs):
"""
封装接口
:return:字典 res.json()
"""
url = url
res = requests.request(method,
url ,
params = params,
data=data,
json = json,
**kwargs)
try:
return res.json()
except Exception as e:
return None
class TestDemo(unittest.TestCase):
def test_demo(self):
visit = mock.Mock(return_value ={"msg":"ok"})
self.assertEqual({"msg":"ok"}, visit("url"))
3)对每个页面进行可行性测试,判断是否返回200状态码
""" demo_02_client.py"""
import requests
# 发出get请求
def send_request(url):
r = requests.get(url)
return r.status_code
# 访问百度
def visit_baidu():
return send_request("https://www.baidu.com")
import unittest
from unittest import mock
from . import demo_02_client
class TestClient(unittest.TestCase):
def test_success_request(self):
success_send = mock.Mock(return_value='200')
demo_02_client.send_request = success_send
self.assertEqual(demo_02_client.visit_baidu(), '200')
def test_fail_request(self):
forbidden_send = mock.Mock(return_value='403')
demo_02_client.send_request = forbidden_send
self.assertEqual(demo_02_client.visit_baidu(), '403')
if __name__ == '__main__':
unittest.main()
4) side_affect,数据库添加数据 mock(side_affect)
side_affect
from mock import Mock
def pay(money):
"""实际支付接口"""
pass
def request_pay(money):
"模拟支付接口"
if isinstance(money, float):
raise ValueError
return money