跳转到主要内容

通过主机/端口阻止套接字创建。

项目描述

用法

预期用途是确保单元测试不会建立网络连接。使用如下谓词激活 sockfilter

# only allow http connections to localhost
def socket_address_allowed(address):
    return (address.host in ['localhost', '127.0.0.1'] and
            address.port == 80)

sockfilter.enable(socket_address_allowed)

如果后续尝试在地址不满足谓词的情况下打开连接,将引发 sockfilter.SockFilterError

with_sockfiltering 装饰器

from sockfilter import with_sockfiltering

@with_sockfiltering(socket_address_allowed)
def test_foo():
    foo()

sockfiltering 上下文管理器

from sockfilter import sockfiltering

def test_foo():
    with sockfiltering(socket_address_allowed):
        foo()

启用禁用

import sockfilter
from unittest import TestCase

class FooTest(TestCase):

    def setUp(self):
        sockfilter.enable(socket_address_allowed)

    def tearDown(self):
        sockfilter.disable()

    def test_foo(self):
        foo()

内部原理

Sockfilter通过猴子补丁Python的 socket 库工作,灵感来自 HTTPretty

项目详情


下载文件

下载适用于您平台的应用程序文件。如果您不确定要选择哪个,请了解更多关于 安装包 的信息。

源分发

sockfilter-1.4.tar.gz (5.5 kB 查看哈希值)

上传时间:

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面