Unit testing a python app that uses the requests library

后端 未结 5 2066
醉酒成梦
醉酒成梦 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:11

    Missing from these answers is requests-mock.

    From their page:

    >>> import requests
    >>> import requests_mock
    

    As a context manager:

    >>> with requests_mock.mock() as m:
    
    ...     m.get('http://test.com', text='data')
    ...     requests.get('http://test.com').text
    ...
    'data'
    

    Or as a decorator:

    >>> @requests_mock.mock()
    ... def test_func(m):
    ...     m.get('http://test.com', text='data')
    ...     return requests.get('http://test.com').text
    ...
    >>> test_func()
    'data'
    

提交回复
热议问题