Block network access of a test/process on Travis?

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.

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
# ...