gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:45:45 25 4
gpt4 key购买 nike

我想确保我的单元测试不会尝试连接到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com