From 134bd890e0b65ab7386a65c9aedda8710366b478 Mon Sep 17 00:00:00 2001 From: Matthew Wardrop Date: Wed, 3 Feb 2021 11:27:44 -0800 Subject: [PATCH 1/2] Avoid changing the type of `socket.socket` to function. --- pytest_socket.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pytest_socket.py b/pytest_socket.py index 296f730..0c8dd63 100644 --- a/pytest_socket.py +++ b/pytest_socket.py @@ -74,10 +74,12 @@ def disable_socket(): """ disable socket.socket to disable the Internet. useful in testing. """ - def guarded(*args, **kwargs): - raise SocketBlockedError() + class GuardedSocket(socket.socket): + """ socket guard to disable socket creation (from pytest-socket) """ + def __new__(cls, *args, **kwargs): + raise SocketBlockedError() - socket.socket = guarded + socket.socket = GuardedSocket def enable_socket(): From c831c14c6397129a79ca83f4ce4ff99274cdbcda Mon Sep 17 00:00:00 2001 From: Matthew Wardrop Date: Tue, 9 Feb 2021 10:03:52 -0800 Subject: [PATCH 2/2] Add unit test to ensure that subclasses are still blocked. --- tests/test_socket.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_socket.py b/tests/test_socket.py index 9c13d4d..acccfce 100644 --- a/tests/test_socket.py +++ b/tests/test_socket.py @@ -210,3 +210,21 @@ def test_socket2(): """) result = testdir.runpytest("--verbose", "--disable-socket") result.assert_outcomes(1, 0, 2) + + +def test_socket_subclass_is_still_blocked(testdir): + testdir.makepyfile(""" + import pytest + import pytest_socket + import socket + + @pytest.mark.disable_socket + def test_subclass_is_still_blocked(): + + class MySocket(socket.socket): + pass + + MySocket(socket.AF_INET, socket.SOCK_STREAM) + """) + result = testdir.runpytest("--verbose") + assert_socket_blocked(result)