我想确保我的单元测试不会尝试连接到Internet,有没有方法在连接到Internet时引发异常?
有一个类似的问题:AA>,但是提出的解决方案阻止了所有的套接字连接,包括数据库的连接,这对于Django测试来说是不可接受的。

最佳答案

找到了一个办法。你可以将此粘贴到你的设置中。

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

10-06 08:51