Python:出于测试目的而阻止网络连接? [英] Python: block network connections for testing purposes?

查看:60
本文介绍了Python:出于测试目的而阻止网络连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试为一些 Web 服务提供接口的包.它有一个测试套件,可以在 连接到互联网的情况下测试大多数功能.但是,有一些拖延的测试可能会尝试连接到 Internet/下载数据,我想阻止它们这样做有两个原因:首先,如果没有可用的网络连接,请确保我的测试套件可以正常工作;其次,这样我就不会向网络服务发送过多查询的垃圾邮件.

I'm trying to test a package that provides interfaces to a few web services. It has a test suite that is supposed to test most functions without connecting to the internet. However, there are some lingering tests that may attempt to connect to the internet / download data, and I'd like to prevent them from doing so for two reasons: first, to make sure my test suite works if no network connection is available; second, so that I'm not spamming the web services with excess queries.

一个明显的解决方案是拔掉我的机器/关闭无线网络,但是当我在远程机器上运行测试时,这显然不起作用.

An obvious solution is to unplug my machine / turn off wireless, but when I'm running tests on a remote machine that obviously doesn't work.

所以,我的问题是:我可以阻止单个 python 进程的网络/端口访问吗?(沙箱"它,但只是阻止网络连接)

So, my question: Can I block network / port access for a single python process? ("sandbox" it, but just blocking network connections)

(事实上,pysandbox 不会这样做)

(afaict, pysandbox doesn't do this)

我正在使用 py.test,所以我需要一个适用于 py.test 的解决方案,以防影响任何建议的答案.

I'm using py.test so I need a solution that will work with py.test, in case that affects any proposed answers.

推荐答案

Monkey patching socket 应该这样做:

Monkey patching socket ought to do it:

import socket
def guard(*args, **kwargs):
    raise Exception("I told you not to use the Internet!")
socket.socket = guard

确保在任何其他导入之前运行.

Make sure this runs before any other import.

这篇关于Python:出于测试目的而阻止网络连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆