先来一个简单的例子:
import requests from unittest import mock def request_lemonfix(): """ :return: """ res = requests.get(‘http://www.lemonfix.com‘) return res.status_code.encode(‘utf-8‘) if __name__ == ‘__main__‘: request_lemonfix = mock.Mock(return_value="这里会显示论坛主页") print(request_lemonfix())
然后再来一个实用的例子:第三方支付接口目前不能调用情况下 使用mock完成测试
import requests class Payment: """ 定义第三方支付类 """ def authe(self, card_num, amount): """ 请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码200 代表支付成功,500 代表支付异常 """ url = "https://www.dd.com" # 第三方的url data = {"card_num": card_num, "amount": amount} response = requests.post(url, data=data) return response.status_code def pay(self, user_id, card_num, amount): """ 支付 :param user_id: 用户id :param card_num: 卡号 :param amount: 金额 :return: """ try: status_code = self.authe(card_num, amount) except TimeoutError: status_code = self.authe(card_num, amount) if status_code == 200: print("支付成功") return "success" if status_code == 500: print("支付失败") return "fail"
下面来看测试类:
import unittest from payment import Payment from unittest import mock class PaymentTest(unittest.TestCase): """ 测试支付接口 """ def setUp(self): self.payment = Payment() def test_success(self): """ 测试支付成功 :return: """ self.payment.authe = mock.Mock(return_value=200) res = self.payment.pay(user_id=10001, card_num="123444", amount=1000) self.assertEqual("success", res) def test_fail(self): """ 测试支付成功 :return: """ self.payment.authe = mock.Mock(return_value=500) res = self.payment.pay(user_id=10002, card_num="1233444", amount=1000) self.assertEqual("fail", res) def test_retry_success(self): """ 测试支付失败重试在成功 side_effect 可以为序列类型 异常类型,对象 如果为序列类型 每次调用mock对象,会依次将side effcet中的元素返回 :return: """ self.payment.authe = mock.Mock(side_effect=[TimeoutError, 200]) res = self.payment.pay(user_id=10003, card_num="1234444", amount=1000) self.assertEqual("success", res) if __name__ == ‘__main__‘: unittest.main()
原文地址:https://www.cnblogs.com/nuonuozhou/p/11533526.html
时间: 2024-10-09 16:54:14