在 Travis 上阻止测试/进程的网络访问?

s-m*_*m-e 7 python pytest travis-ci

基于此问题及其答案:在 Travis CI 上阻止测试或进程的网络访问的适用方法是什么(如果有的话)?


背景:我想测试离线功能,即缓存,从而能够在没有互联网/网络访问的情况下使用库。该过程中涉及的依赖项(第三方软件)尝试连接到 Internet/网络。目前,我正在设法禁止其互联网/网络访问(通过“拔掉插头”在本地确认),但我想找到一种方法来实施适当的 CI 测试以进行长期维护。大多数测试基础设施都是用 Python 编写的,并基于 pytest。

lar*_*sks 5

您的 Travis 作业在功能齐全的 Linux 环境中运行,其中包括使用iptables命令创建防火墙规则的能力。考虑这个非常简单的.travis.yml文件:

---
script:
  - curl http://icanhazip.com
Run Code Online (Sandbox Code Playgroud)

把它放在一个存储库中并运行它,它会工作得很好:

$ curl http://icanhazip.com
104.196.57.92
The command "curl http://icanhazip.com" exited with 0.
Run Code Online (Sandbox Code Playgroud)

为了模拟离线行为,我们只需添加一个防火墙规则来阻止端口 80 上的出站访问:

---
script:
  - sudo iptables -A OUTPUT -p tcp --dport 80 -j REJECT
  - curl http://icanhazip.com
Run Code Online (Sandbox Code Playgroud)

这将失败:

$ curl http://icanhazip.com
curl: (7) Failed to connect to icanhazip.com port 80: Connection refused
The command "curl http://icanhazip.com" exited with 7.
Run Code Online (Sandbox Code Playgroud)