单元测试 request_mock模拟网络调用
import unittest from unittest import mock from requests.exceptions import ConnectionError import requests_mock import requests class MyBugzilla: def __init__(self, account, server='https://bugzilla.mozilla.org'): self.account = account self.server = server self.session = requests.Session() def bug_link(self, bug): return '%s/show_bug.cgi?id=%s' % (self.server, bug['id']) def get_new_bugs(self): call = self.server + '/rest/bug' params = {'assigned_to': self.account, 'status': 'NEW', 'limit': 10} try: res = self.session.get(call, params=params).json() except requests.exceptions.ConnectionError as e: print('e:',e) res = {'bugs': []} def _add_link(bug): bug['link'] = self.bug_link(bug) return bug for bug in res['bugs']: yield _add_link(bug) class TestBugzilla(unittest.TestCase): def test_bug_id(self): zilla = MyBugzilla('tarek@mozilla.com', server='http://yeah') link = zilla.bug_link({'id':'23'}) self.assertEqual(link, 'http://yeah/show_bug.cgi?id=23') # @requests_mock.mock() def test_get_new_bugs(self, mocker): # mocking the requests call and send back two bugs bugs = [{'cust_id': 'okdeasdjj1343dadadadada'}] mocker.get(requests_mock.ANY, json={'bugs': bugs}) zilla = MyBugzilla('tarek@mozilla.com', server='http://yeah') bugs = list(zilla.get_new_bugs()) self.assertEqual(bugs[0]['link'], 'http://yeah/show_bug.cgi?id=1184528') @mock.patch.object(requests, 'get', side_effect=ConnectionError('No network')) def test_network_error(self, mocked): # faking a connection error in request if the web is down zilla = MyBugzilla('tarek@mozilla.com', server='http://yeah') bugs = list(zilla.get_new_bugs()) self.assertEqual(len(bugs), 0) if __name__ == '__main__': unittest.main()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-11-16 上下文管理器的使用
2021-11-16 上下文管理器