Unit testing a python app that uses the requests library

后端 未结 5 2074
醉酒成梦
醉酒成梦 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 10:01

    If you use specifically requests try httmock. It's wonderfully simple and elegant:

    from httmock import urlmatch, HTTMock
    import requests
    
    # define matcher:
    @urlmatch(netloc=r'(.*\.)?google\.com$')
    def google_mock(url, request):
        return 'Feeling lucky, punk?'
    
    # open context to patch
    with HTTMock(google_mock):
        # call requests
        r = requests.get('http://google.com/')
    print r.content  # 'Feeling lucky, punk?'
    

    If you want something more generic (e.g. to mock any library making http calls) go for httpretty.

    Almost as elegant:

    import requests
    import httpretty
    
    @httpretty.activate
    def test_one():
        # define your patch:
        httpretty.register_uri(httpretty.GET, "http://yipit.com/",
                            body="Find the best daily deals")
        # use!
        response = requests.get('http://yipit.com')
        assert response.text == "Find the best daily deals"
    

    HTTPretty is far more feature-rich - it offers also mocking status code, streaming responses, rotating responses, dynamic responses (with a callback).

提交回复
热议问题