import socket
from django.test import TestCase
[docs]class SocketAccessError(Exception):
"""Error raised when a test script accesses the network"""
[docs]class NoSocketsTestCase(TestCase):
"""Variation of Django's TestCase class that prevents any network use.
Example:
.. code-block:: python
class TestMyStuff(NoSocketsTestCase):
def test_should_do_what_i_need(self):
...
"""
@classmethod
def setUpClass(cls):
cls.socket_original = socket.socket
socket.socket = cls.guard
return super().setUpClass()
@classmethod
def tearDownClass(cls):
socket.socket = cls.socket_original
return super().tearDownClass()
@staticmethod
def guard(*args, **kwargs):
raise SocketAccessError("Attempted to access network")