Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block network access of a test/process on Travis?

Based on this question and its answers: What is an applicable approach (if there is any) of blocking network access of a test or process on Travis CI?


Background: I want to test offline functionality, i.e. a cache, enabling to use a library without internet/network access. A dependency (a third-party piece of software) involved in the process tries to connect to the internet/network. Currently, I am managing to prohibit its internet/network access (confirmed locally by "pulling the plug"), though I want to find a way to implement a proper CI test for long-term maintenance. Most of the testing infrastructure is written in Python and based on pytest.

like image 730
s-m-e Avatar asked Dec 16 '19 16:12

s-m-e


2 Answers

Your Travis jobs run in a fully functional Linux environment, which includes the ability to create firewall rules using the iptables command. Consider this very simple .travis.yml file:

---
script:
  - curl http://icanhazip.com

Stick this in a repository and run it and it will work just fine:

$ curl http://icanhazip.com
104.196.57.92
The command "curl http://icanhazip.com" exited with 0.

In order to simulate offline behavior, we just add a firewall rules that blocks outbound access on port 80:

---
script:
  - sudo iptables -A OUTPUT -p tcp --dport 80 -j REJECT
  - curl http://icanhazip.com

This will fail:

$ 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.
like image 158
larsks Avatar answered Nov 06 '22 06:11

larsks


One way I've done this with travis-ci is to utilize docker and the --net=none functionality

From an old example of mine

I build a docker image and invoke that via .travis.yaml

Here's the Makefile component:

.PHONY: test-docker_%
test-docker_%:
    docker build -t tox-virtualenv-no-download_$* --build-arg PYTHON=$* .
    docker run --rm --net=none tox-virtualenv-no-download_$*

the Dockerfile in question (which is parametrized based on the python version)

FROM ubuntu:bionic

ARG PYTHON=python2.7
RUN : \
    && apt-get update \
    && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        dumb-init $PYTHON virtualenv \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

ENV PATH=/venv/bin:$PATH
ADD . /code/
RUN virtualenv /venv -p $PYTHON && pip install /code

WORKDIR /example
ADD example /example
CMD ["dumb-init", "tox"]

And the associated .travis.yml which uses the matrix functionality to test those:

language: python
services: docker
env:
    - PYTHON=python2.7
    - PYTHON=python3.6
    - PYTHON=pypy
# ...
script: make test-docker_$PYTHON
# ...
like image 23
Anthony Sottile Avatar answered Nov 06 '22 06:11

Anthony Sottile