python - Django:出于测试目的阻止互联网连接

标签 python django unit-testing testing

我想确保我的单元测试不会尝试连接到 Internet,有没有办法在它们连接时引发异常?

有一个类似的问题Python: block network connections for testing purposes? ,但是那里提出的解决方案会阻止所有套接字连接,包括数据库连接,这对于 Django 测试来说是 Not Acceptable 。

最佳答案

找到了一种方法来做到这一点。您可以将其粘贴到您的设置中。

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

关于python - Django:出于测试目的阻止互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351796/

相关文章:

使用 django-nose 的 Django 负载测试装置

java - Testng : Assert using error code, 自定义异常实例的自定义属性

java - 类似的 jUnit 测试用例是否应该驻留在同一个测试中?

python - Django 自动转义在 render_to_string(template) 中不起作用?

java - 在Java Map内部执行python脚本reduce

python - 循环遍历Python字典总是产生不同的结果

python - 如何在 Django/Python 中减去两个日期?

django - 排除时如何在表单上设置默认值?

python - Django 从模板中带有 for 键值的字典中获取特定值

python - 如何删除使用 Python 中的 Mechanize 生成的链接中的重复项?