First to a simple example:
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())
Using mock complete the test interface to third-party payment under the current situation can not be called: then again a practical example
Import Requests class Payment: "" " defined class party payment " "" DEF authe (Self, card_num, AMOUNT): "" " ask a third party payment interface, and returns a response code : param card_num: Card : param amount: Amount : return: return a status code 200 represents successful payment, payment on behalf of abnormality 500 "" " URL = " https://www.dd.com " # third 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== 500 status_code : Print ( " pay for failure " ) return " Fail "
Let's look at the test class:
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: """ = mock.Mock self.payment.authe (the return_value = 500) = self.payment.pay RES (user_id = 10002, card_num = "1,233,444", AMOUNT = 1000) self.assertEqual ( "Fail", RES) DEF test_retry_success (Self): "" " Test failed to pay retry success side_effect can sequence type exception type, the object if the type of each call sequence mock objects, will in turn return the elements side effcet : return: "" " self.payment.authe = mock.Mock (side_effect = [TimeoutError, 200 is]) self.payment.pay = RES (user_id = 10003, card_num = "1,234,444", AMOUNT = 1000) self.assertEqual ( "Success", RES) IF the __name__ == '__main__': unittest.main ()