Created
February 6, 2020 19:56
-
-
Save rileypeterson/1d29e888e35d1985c2ca1dd9ddc86fb8 to your computer and use it in GitHub Desktop.
Socket blocker decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on https://github.com/miketheman/pytest-socket/blob/master/pytest_socket.py | |
import socket | |
import requests | |
_true_socket = socket.socket | |
def _blank(*args, **kwargs): | |
raise ValueError('socket') | |
def block_socket(f): | |
def new_f(*args, **kwargs): | |
try: | |
socket.socket = _blank | |
f(*args, **kwargs) | |
finally: | |
socket.socket = _true_socket | |
return new_f | |
def my_req(): | |
print(requests.get('https://docs.python.org/3/library/socket.html')) | |
@block_socket | |
def my_req1(): | |
print(requests.get('https://docs.python.org/3/library/socket.html')) | |
if __name__ == '__main__': | |
my_req() | |
# <Response [200]> | |
try: | |
my_req1() | |
# Raises ValueError | |
except ValueError as e: | |
print("ValueError", e) | |
my_req() | |
# <Response [200]> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment