import os
import requests
from urllib3.poolmanager import PoolManager
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager, proxy_from_url
from mock import patch
import urllib3
ORIGINAL_METHOD = urllib3.connection.HTTPConnection.putrequest
def patched_method(self, *args, **kwargs):
return ORIGINAL_METHOD(self, *args, **kwargs)
class ProxyHeaderHttpAdapter(HTTPAdapter):
def proxy_headers(self, proxy):
headers = super(ProxyHeaderHttpAdapter, self).proxy_headers(proxy)
headers = {
'User-Agent': 'tunneling',
'Connection': 'Keep-Alive',
'Pragma': 'no-cache',
}
headers.update(headers)
return headers
def main():
session = requests.Session()
adapters = ProxyHeaderHttpAdapter(max_retries=3)
session.mount("http://", adapters)
session.mount("https://", adapters)
proxy = {"http":"127.0.0.1:8888", "https":"127.0.0.1:8888"}
if proxy != {}:
session.proxies = proxy
session.verify = None
url = 'https://www.google.com'
with patch.object(urllib3.connection.HTTPConnection, 'putrequest', side_effect=patched_method, autospec=True):
session.get(url)
if __name__ == "__main__":
os.chdir(os.path.dirname(os.path.abspath(__file__)))
main()
autospec と sideeffect を組み合わせるのが解決策だった。
コメント