pythonpytestsandbox

Python: block network connections for testing purposes?


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.

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

(AFAICT, pysandbox doesn't do this)

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


Solution

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