单元测试 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()
复制代码

 

posted @   乔小生1221  阅读(202)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-11-16 上下文管理器的使用
2021-11-16 上下文管理器
点击右上角即可分享
微信分享提示