Skip to content

Commit f45da17

Browse files
committed
add aiohttp support
1 parent 6867f6e commit f45da17

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

pytest_blockage.py

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,20 @@ class MockSmtpCall(Exception):
1818
pass
1919

2020

21-
def block_http(whitelist):
21+
def http_fail(host):
22+
logger.warning('Denied HTTP connection to: %s' % host)
23+
raise MockHttpCall(host)
24+
25+
def block_http_httplib(whitelist):
2226
def whitelisted(self, host, *args, **kwargs):
2327
try:
2428
string_type = basestring
2529
except NameError:
2630
# python3
2731
string_type = str
2832
if isinstance(host, string_type) and host not in whitelist:
29-
logger.warning('Denied HTTP connection to: %s' % host)
30-
raise MockHttpCall(host)
33+
http_fail(host)
34+
3135
logger.debug('Allowed HTTP connection to: %s' % host)
3236
return self.old(host, *args, **kwargs)
3337

@@ -39,6 +43,34 @@ def whitelisted(self, host, *args, **kwargs):
3943
httplib.HTTPConnection.__init__ = whitelisted
4044

4145

46+
def block_http_aiohttp(whitelist):
47+
try:
48+
from aiohttp.client import ClientSession
49+
except ImportError:
50+
# no aiohttp installed
51+
return
52+
53+
from yarl import URL
54+
55+
def patch(self, method, url, **kwargs):
56+
yurl = URL(url)
57+
58+
if yurl.host not in whitelist:
59+
http_fail(yurl.host)
60+
61+
return self.old_request(method, url, **kwargs)
62+
63+
if not getattr(ClientSession, 'blockage', False):
64+
logger.debug('Monkey patching httplib')
65+
ClientSession.old_request = ClientSession._request
66+
ClientSession._request = patch
67+
68+
69+
def block_http(whitelist):
70+
block_http_httplib(whitelist)
71+
block_http_aiohttp(whitelist)
72+
73+
4274
def block_smtp(whitelist):
4375
def whitelisted(self, host, *args, **kwargs):
4476
if isinstance(host, basestring) and host not in whitelist:

0 commit comments

Comments
 (0)