首页 > 其他分享 >单元测试 request_mock模拟网络调用

单元测试 request_mock模拟网络调用

时间:2022-11-16 13:56:32浏览次数:54  
标签:单元测试 self request bugs link requests bug 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('[email protected]', 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('[email protected]', 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('[email protected]', server='http://yeah')
        bugs = list(zilla.get_new_bugs())
        self.assertEqual(len(bugs), 0)


if __name__ == '__main__':
    unittest.main()

 

标签:单元测试,self,request,bugs,link,requests,bug,mock
From: https://www.cnblogs.com/qxh-beijing2016/p/16895636.html

相关文章