Skip to content

Instantly share code, notes, and snippets.

@rileypeterson
Created February 6, 2020 19:56
Show Gist options
  • Save rileypeterson/1d29e888e35d1985c2ca1dd9ddc86fb8 to your computer and use it in GitHub Desktop.
Save rileypeterson/1d29e888e35d1985c2ca1dd9ddc86fb8 to your computer and use it in GitHub Desktop.
Socket blocker decorator
# 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