Django: block internet connection for testing

I want my unit tests not trying to connect to the Internet, is there any way to make an exception when they do?

There was a similar Python question : block network connections for testing purposes? but the solution offered there blocks all socket connections, including databases that are not acceptable for Django tests.

+4
source share
2 answers

Found 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
+4
source

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

. , . , .

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

, :

  • urllib2
  • urllib3
  • http.client(python3)
  • ( 1.x, 2.x )
  • httplib2
  • Tornados AsyncHTTPClient
+1

Source: https://habr.com/ru/post/1538483/


All Articles