Unit testing a python app that uses the requests library

后端 未结 5 2064
醉酒成梦
醉酒成梦 2020-12-07 09:12

I am writing an application that performs REST operations using Kenneth Reitz\'s requests library and I\'m struggling to find a nice way to unit test these applications, bec

5条回答
  •  眼角桃花
    2020-12-07 09:56

    You could use a mocking library such as Mocker to intercept the calls to the requests library and return specified results.

    As a very simple example, consider this class which uses the requests library:

    class MyReq(object):
        def doSomething(self):
            r = requests.get('https://api.github.com', auth=('user', 'pass'))
            return r.headers['content-type']
    

    Here's a unit test that intercepts the call to requests.get and returns a specified result for testing:

    import unittest
    import requests
    import myreq
    
    from mocker import Mocker, MockerTestCase
    
    class MyReqTests(MockerTestCase):
        def testSomething(self):
            # Create a mock result for the requests.get call
            result = self.mocker.mock()
            result.headers
            self.mocker.result({'content-type': 'mytest/pass'})
    
            # Use mocker to intercept the call to requests.get
            myget = self.mocker.replace("requests.get")
            myget('https://api.github.com', auth=('user', 'pass'))
            self.mocker.result(result)
    
            self.mocker.replay()
    
            # Now execute my code
            r = myreq.MyReq()
            v = r.doSomething()
    
            # and verify the results
            self.assertEqual(v, 'mytest/pass')
            self.mocker.verify()
    
    if __name__ == '__main__':
        unittest.main()
    

    When I run this unit test I get the following result:

    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.004s
    
    OK
    

提交回复
热议问题