Skip to content

Instantly share code, notes, and snippets.

@kylemcc
Last active December 23, 2015 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylemcc/6690439 to your computer and use it in GitHub Desktop.
Save kylemcc/6690439 to your computer and use it in GitHub Desktop.
Place in project/__init__.py to patch the socket class during test runs to notify when a test attempts to connect to an external service
import sys
class TestTriedToAccessNetwork(BaseException):
pass
if 'test' in sys.argv:
import socket
class PatchedSocket(socket.socket):
def __init__(self, *args, **kwargs):
super(PatchedSocket, self).__init__(*args, **kwargs)
def connect(self, address):
addr, _ = address
if addr and addr != '127.0.0.1':
#print "FAIL: %s" % addr
#traceback.print_stack()
raise TestTriedToAccessNetwork("Tried connecting to external resource: %s" % addr)
super(PatchedSocket, self).connect(address)
socket.socket = PatchedSocket
@stantonk
Copy link

-            if addr and addr != '127.0.0.1':
+           if addr and addr not in ('127.0.0.1', 'localhost'):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment