Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: block internet connection for testing purposes

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.

like image 434
Ivan Ivanov Avatar asked Mar 19 '23 18:03

Ivan Ivanov


2 Answers

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
like image 128
Ivan Ivanov Avatar answered Apr 05 '23 21:04

Ivan Ivanov


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
like image 23
MDB Avatar answered Apr 05 '23 23:04

MDB