Django: block internet connection for testing purposes

风流意气都作罢 提交于 2019-12-21 17:36:18

问题


I'd like to make sure my unit tests do not try to connect to Internet, is there a way to raise an exception when they do?

There was a similar question Python: block network connections for testing purposes?, but the solution proposed there blocks all socket connections, including the database ones, which is not acceptable for Django tests.


回答1:


Found out a way to do this. You can paste this into your settings.

if 'test' in sys.argv:

    # Block Internet access during tests
    import urllib2
    import httplib
    import httplib2

    def _raise_http_error(*args, **kwargs):
        raise urllib2.URLError("I told you not to use the Internet!")

    class AngryHandler(urllib2.BaseHandler):
        handler_order = 1

        def default_open(self, req):
            _raise_http_error()

    opener = urllib2.build_opener(AngryHandler)
    urllib2.install_opener(opener)

    _HTTPHandler = urllib2.HTTPHandler
    urllib2.HTTPHandler = AngryHandler

    httplib.HTTPConnection.connect = lambda self: None
    httplib.HTTPSConnection.connect = lambda self: None
    httplib.HTTPConnection.request = _raise_http_error
    httplib.HTTPSConnection.request = _raise_http_error
    httplib2.Http.request = _raise_http_error



回答2:


Take a look at vcrpy: https://github.com/kevin1024/vcrpy

The first time you run the test it'll make the external request. Every time after that it'll use a fixture that it stored from the first call. The external requests never get made again, which is what you're trying to accomplish.

Usage is dead simple using a decorator on your unit test:

@vcr.use_cassette('fixtures/vcr_cassettes/synopsis.yaml')
def test_iana():
    response = urllib2.urlopen('http://www.iana.org/domains/reserved').read()
    assert 'Example domains' in response

Supports any request made using the following libraries:

  • urllib2
  • urllib3
  • http.client (python3)
  • requests (both 1.x and 2.x versions)
  • httplib2
  • boto
  • Tornado’s AsyncHTTPClient


来源:https://stackoverflow.com/questions/23351796/django-block-internet-connection-for-testing-purposes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!