test_networking.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import pytest
  6. from yt_dlp.networking.common import Features, DEFAULT_TIMEOUT
  7. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. import gzip
  9. import http.client
  10. import http.cookiejar
  11. import http.server
  12. import io
  13. import logging
  14. import pathlib
  15. import random
  16. import ssl
  17. import tempfile
  18. import threading
  19. import time
  20. import urllib.error
  21. import urllib.request
  22. import warnings
  23. import zlib
  24. from email.message import Message
  25. from http.cookiejar import CookieJar
  26. from test.helper import (
  27. FakeYDL,
  28. http_server_port,
  29. validate_and_send,
  30. verify_address_availability,
  31. )
  32. from yt_dlp.cookies import YoutubeDLCookieJar
  33. from yt_dlp.dependencies import brotli, curl_cffi, requests, urllib3
  34. from yt_dlp.networking import (
  35. HEADRequest,
  36. PUTRequest,
  37. Request,
  38. RequestDirector,
  39. RequestHandler,
  40. Response,
  41. )
  42. from yt_dlp.networking._urllib import UrllibRH
  43. from yt_dlp.networking.exceptions import (
  44. CertificateVerifyError,
  45. HTTPError,
  46. IncompleteRead,
  47. NoSupportingHandlers,
  48. ProxyError,
  49. RequestError,
  50. SSLError,
  51. TransportError,
  52. UnsupportedRequest,
  53. )
  54. from yt_dlp.networking.impersonate import (
  55. ImpersonateRequestHandler,
  56. ImpersonateTarget,
  57. )
  58. from yt_dlp.utils import YoutubeDLError
  59. from yt_dlp.utils._utils import _YDLLogger as FakeLogger
  60. from yt_dlp.utils.networking import HTTPHeaderDict, std_headers
  61. TEST_DIR = os.path.dirname(os.path.abspath(__file__))
  62. class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
  63. protocol_version = 'HTTP/1.1'
  64. default_request_version = 'HTTP/1.1'
  65. def log_message(self, format, *args):
  66. pass
  67. def _headers(self):
  68. payload = str(self.headers).encode()
  69. self.send_response(200)
  70. self.send_header('Content-Type', 'application/json')
  71. self.send_header('Content-Length', str(len(payload)))
  72. self.end_headers()
  73. self.wfile.write(payload)
  74. def _redirect(self):
  75. self.send_response(int(self.path[len('/redirect_'):]))
  76. self.send_header('Location', '/method')
  77. self.send_header('Content-Length', '0')
  78. self.end_headers()
  79. def _method(self, method, payload=None):
  80. self.send_response(200)
  81. self.send_header('Content-Length', str(len(payload or '')))
  82. self.send_header('Method', method)
  83. self.end_headers()
  84. if payload:
  85. self.wfile.write(payload)
  86. def _status(self, status):
  87. payload = f'<html>{status} NOT FOUND</html>'.encode()
  88. self.send_response(int(status))
  89. self.send_header('Content-Type', 'text/html; charset=utf-8')
  90. self.send_header('Content-Length', str(len(payload)))
  91. self.end_headers()
  92. self.wfile.write(payload)
  93. def _read_data(self):
  94. if 'Content-Length' in self.headers:
  95. return self.rfile.read(int(self.headers['Content-Length']))
  96. else:
  97. return b''
  98. def do_POST(self):
  99. data = self._read_data() + str(self.headers).encode()
  100. if self.path.startswith('/redirect_'):
  101. self._redirect()
  102. elif self.path.startswith('/method'):
  103. self._method('POST', data)
  104. elif self.path.startswith('/headers'):
  105. self._headers()
  106. else:
  107. self._status(404)
  108. def do_HEAD(self):
  109. if self.path.startswith('/redirect_'):
  110. self._redirect()
  111. elif self.path.startswith('/method'):
  112. self._method('HEAD')
  113. else:
  114. self._status(404)
  115. def do_PUT(self):
  116. data = self._read_data() + str(self.headers).encode()
  117. if self.path.startswith('/redirect_'):
  118. self._redirect()
  119. elif self.path.startswith('/method'):
  120. self._method('PUT', data)
  121. else:
  122. self._status(404)
  123. def do_GET(self):
  124. if self.path == '/video.html':
  125. payload = b'<html><video src="/vid.mp4" /></html>'
  126. self.send_response(200)
  127. self.send_header('Content-Type', 'text/html; charset=utf-8')
  128. self.send_header('Content-Length', str(len(payload)))
  129. self.end_headers()
  130. self.wfile.write(payload)
  131. elif self.path == '/vid.mp4':
  132. payload = b'\x00\x00\x00\x00\x20\x66\x74[video]'
  133. self.send_response(200)
  134. self.send_header('Content-Type', 'video/mp4')
  135. self.send_header('Content-Length', str(len(payload)))
  136. self.end_headers()
  137. self.wfile.write(payload)
  138. elif self.path == '/%E4%B8%AD%E6%96%87.html':
  139. payload = b'<html><video src="/vid.mp4" /></html>'
  140. self.send_response(200)
  141. self.send_header('Content-Type', 'text/html; charset=utf-8')
  142. self.send_header('Content-Length', str(len(payload)))
  143. self.end_headers()
  144. self.wfile.write(payload)
  145. elif self.path == '/%c7%9f':
  146. payload = b'<html><video src="/vid.mp4" /></html>'
  147. self.send_response(200)
  148. self.send_header('Content-Type', 'text/html; charset=utf-8')
  149. self.send_header('Content-Length', str(len(payload)))
  150. self.end_headers()
  151. self.wfile.write(payload)
  152. elif self.path.startswith('/redirect_loop'):
  153. self.send_response(301)
  154. self.send_header('Location', self.path)
  155. self.send_header('Content-Length', '0')
  156. self.end_headers()
  157. elif self.path == '/redirect_dotsegments':
  158. self.send_response(301)
  159. # redirect to /headers but with dot segments before
  160. self.send_header('Location', '/a/b/./../../headers')
  161. self.send_header('Content-Length', '0')
  162. self.end_headers()
  163. elif self.path == '/redirect_dotsegments_absolute':
  164. self.send_response(301)
  165. # redirect to /headers but with dot segments before - absolute url
  166. self.send_header('Location', f'http://127.0.0.1:{http_server_port(self.server)}/a/b/./../../headers')
  167. self.send_header('Content-Length', '0')
  168. self.end_headers()
  169. elif self.path.startswith('/redirect_'):
  170. self._redirect()
  171. elif self.path.startswith('/method'):
  172. self._method('GET', str(self.headers).encode())
  173. elif self.path.startswith('/headers'):
  174. self._headers()
  175. elif self.path.startswith('/308-to-headers'):
  176. self.send_response(308)
  177. # redirect to "localhost" for testing cookie redirection handling
  178. self.send_header('Location', f'http://localhost:{self.connection.getsockname()[1]}/headers')
  179. self.send_header('Content-Length', '0')
  180. self.end_headers()
  181. elif self.path == '/trailing_garbage':
  182. payload = b'<html><video src="/vid.mp4" /></html>'
  183. self.send_response(200)
  184. self.send_header('Content-Type', 'text/html; charset=utf-8')
  185. self.send_header('Content-Encoding', 'gzip')
  186. buf = io.BytesIO()
  187. with gzip.GzipFile(fileobj=buf, mode='wb') as f:
  188. f.write(payload)
  189. compressed = buf.getvalue() + b'trailing garbage'
  190. self.send_header('Content-Length', str(len(compressed)))
  191. self.end_headers()
  192. self.wfile.write(compressed)
  193. elif self.path == '/302-non-ascii-redirect':
  194. new_url = f'http://127.0.0.1:{http_server_port(self.server)}/中文.html'
  195. self.send_response(301)
  196. self.send_header('Location', new_url)
  197. self.send_header('Content-Length', '0')
  198. self.end_headers()
  199. elif self.path == '/content-encoding':
  200. encodings = self.headers.get('ytdl-encoding', '')
  201. payload = b'<html><video src="/vid.mp4" /></html>'
  202. for encoding in filter(None, (e.strip() for e in encodings.split(','))):
  203. if encoding == 'br' and brotli:
  204. payload = brotli.compress(payload)
  205. elif encoding == 'gzip':
  206. buf = io.BytesIO()
  207. with gzip.GzipFile(fileobj=buf, mode='wb') as f:
  208. f.write(payload)
  209. payload = buf.getvalue()
  210. elif encoding == 'deflate':
  211. payload = zlib.compress(payload)
  212. elif encoding == 'unsupported':
  213. payload = b'raw'
  214. break
  215. else:
  216. self._status(415)
  217. return
  218. self.send_response(200)
  219. self.send_header('Content-Encoding', encodings)
  220. self.send_header('Content-Length', str(len(payload)))
  221. self.end_headers()
  222. self.wfile.write(payload)
  223. elif self.path.startswith('/gen_'):
  224. payload = b'<html></html>'
  225. self.send_response(int(self.path[len('/gen_'):]))
  226. self.send_header('Content-Type', 'text/html; charset=utf-8')
  227. self.send_header('Content-Length', str(len(payload)))
  228. self.end_headers()
  229. self.wfile.write(payload)
  230. elif self.path.startswith('/incompleteread'):
  231. payload = b'<html></html>'
  232. self.send_response(200)
  233. self.send_header('Content-Type', 'text/html; charset=utf-8')
  234. self.send_header('Content-Length', '234234')
  235. self.end_headers()
  236. self.wfile.write(payload)
  237. self.finish()
  238. elif self.path.startswith('/timeout_'):
  239. time.sleep(int(self.path[len('/timeout_'):]))
  240. self._headers()
  241. elif self.path == '/source_address':
  242. payload = str(self.client_address[0]).encode()
  243. self.send_response(200)
  244. self.send_header('Content-Type', 'text/html; charset=utf-8')
  245. self.send_header('Content-Length', str(len(payload)))
  246. self.end_headers()
  247. self.wfile.write(payload)
  248. self.finish()
  249. elif self.path == '/get_cookie':
  250. self.send_response(200)
  251. self.send_header('Set-Cookie', 'test=ytdlp; path=/')
  252. self.end_headers()
  253. self.finish()
  254. else:
  255. self._status(404)
  256. def send_header(self, keyword, value):
  257. """
  258. Forcibly allow HTTP server to send non percent-encoded non-ASCII characters in headers.
  259. This is against what is defined in RFC 3986, however we need to test we support this
  260. since some sites incorrectly do this.
  261. """
  262. if keyword.lower() == 'connection':
  263. return super().send_header(keyword, value)
  264. if not hasattr(self, '_headers_buffer'):
  265. self._headers_buffer = []
  266. self._headers_buffer.append(f'{keyword}: {value}\r\n'.encode())
  267. class TestRequestHandlerBase:
  268. @classmethod
  269. def setup_class(cls):
  270. cls.http_httpd = http.server.ThreadingHTTPServer(
  271. ('127.0.0.1', 0), HTTPTestRequestHandler)
  272. cls.http_port = http_server_port(cls.http_httpd)
  273. cls.http_server_thread = threading.Thread(target=cls.http_httpd.serve_forever)
  274. # FIXME: we should probably stop the http server thread after each test
  275. # See: https://github.com/yt-dlp/yt-dlp/pull/7094#discussion_r1199746041
  276. cls.http_server_thread.daemon = True
  277. cls.http_server_thread.start()
  278. # HTTPS server
  279. certfn = os.path.join(TEST_DIR, 'testcert.pem')
  280. cls.https_httpd = http.server.ThreadingHTTPServer(
  281. ('127.0.0.1', 0), HTTPTestRequestHandler)
  282. sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  283. sslctx.load_cert_chain(certfn, None)
  284. cls.https_httpd.socket = sslctx.wrap_socket(cls.https_httpd.socket, server_side=True)
  285. cls.https_port = http_server_port(cls.https_httpd)
  286. cls.https_server_thread = threading.Thread(target=cls.https_httpd.serve_forever)
  287. cls.https_server_thread.daemon = True
  288. cls.https_server_thread.start()
  289. @pytest.mark.parametrize('handler', ['Urllib', 'Requests', 'CurlCFFI'], indirect=True)
  290. class TestHTTPRequestHandler(TestRequestHandlerBase):
  291. def test_verify_cert(self, handler):
  292. with handler() as rh:
  293. with pytest.raises(CertificateVerifyError):
  294. validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
  295. with handler(verify=False) as rh:
  296. r = validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
  297. assert r.status == 200
  298. r.close()
  299. def test_ssl_error(self, handler):
  300. # HTTPS server with too old TLS version
  301. # XXX: is there a better way to test this than to create a new server?
  302. https_httpd = http.server.ThreadingHTTPServer(
  303. ('127.0.0.1', 0), HTTPTestRequestHandler)
  304. sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  305. https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
  306. https_port = http_server_port(https_httpd)
  307. https_server_thread = threading.Thread(target=https_httpd.serve_forever)
  308. https_server_thread.daemon = True
  309. https_server_thread.start()
  310. with handler(verify=False) as rh:
  311. with pytest.raises(SSLError, match=r'(?i)ssl(?:v3|/tls).alert.handshake.failure') as exc_info:
  312. validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
  313. assert not issubclass(exc_info.type, CertificateVerifyError)
  314. @pytest.mark.skip_handler('CurlCFFI', 'legacy_ssl ignored by CurlCFFI')
  315. def test_legacy_ssl_extension(self, handler):
  316. # HTTPS server with old ciphers
  317. # XXX: is there a better way to test this than to create a new server?
  318. https_httpd = http.server.ThreadingHTTPServer(
  319. ('127.0.0.1', 0), HTTPTestRequestHandler)
  320. sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  321. sslctx.maximum_version = ssl.TLSVersion.TLSv1_2
  322. sslctx.set_ciphers('SHA1:AESCCM:aDSS:eNULL:aNULL')
  323. sslctx.load_cert_chain(os.path.join(TEST_DIR, 'testcert.pem'), None)
  324. https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
  325. https_port = http_server_port(https_httpd)
  326. https_server_thread = threading.Thread(target=https_httpd.serve_forever)
  327. https_server_thread.daemon = True
  328. https_server_thread.start()
  329. with handler(verify=False) as rh:
  330. res = validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers', extensions={'legacy_ssl': True}))
  331. assert res.status == 200
  332. res.close()
  333. # Ensure only applies to request extension
  334. with pytest.raises(SSLError):
  335. validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
  336. @pytest.mark.skip_handler('CurlCFFI', 'legacy_ssl ignored by CurlCFFI')
  337. def test_legacy_ssl_support(self, handler):
  338. # HTTPS server with old ciphers
  339. # XXX: is there a better way to test this than to create a new server?
  340. https_httpd = http.server.ThreadingHTTPServer(
  341. ('127.0.0.1', 0), HTTPTestRequestHandler)
  342. sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  343. sslctx.maximum_version = ssl.TLSVersion.TLSv1_2
  344. sslctx.set_ciphers('SHA1:AESCCM:aDSS:eNULL:aNULL')
  345. sslctx.load_cert_chain(os.path.join(TEST_DIR, 'testcert.pem'), None)
  346. https_httpd.socket = sslctx.wrap_socket(https_httpd.socket, server_side=True)
  347. https_port = http_server_port(https_httpd)
  348. https_server_thread = threading.Thread(target=https_httpd.serve_forever)
  349. https_server_thread.daemon = True
  350. https_server_thread.start()
  351. with handler(verify=False, legacy_ssl_support=True) as rh:
  352. res = validate_and_send(rh, Request(f'https://127.0.0.1:{https_port}/headers'))
  353. assert res.status == 200
  354. res.close()
  355. def test_percent_encode(self, handler):
  356. with handler() as rh:
  357. # Unicode characters should be encoded with uppercase percent-encoding
  358. res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/中文.html'))
  359. assert res.status == 200
  360. res.close()
  361. # don't normalize existing percent encodings
  362. res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/%c7%9f'))
  363. assert res.status == 200
  364. res.close()
  365. @pytest.mark.parametrize('path', [
  366. '/a/b/./../../headers',
  367. '/redirect_dotsegments',
  368. # https://github.com/yt-dlp/yt-dlp/issues/9020
  369. '/redirect_dotsegments_absolute',
  370. ])
  371. def test_remove_dot_segments(self, handler, path):
  372. with handler(verbose=True) as rh:
  373. # This isn't a comprehensive test,
  374. # but it should be enough to check whether the handler is removing dot segments in required scenarios
  375. res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}{path}'))
  376. assert res.status == 200
  377. assert res.url == f'http://127.0.0.1:{self.http_port}/headers'
  378. res.close()
  379. @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi (non-standard)')
  380. def test_unicode_path_redirection(self, handler):
  381. with handler() as rh:
  382. r = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/302-non-ascii-redirect'))
  383. assert r.url == f'http://127.0.0.1:{self.http_port}/%E4%B8%AD%E6%96%87.html'
  384. r.close()
  385. def test_raise_http_error(self, handler):
  386. with handler() as rh:
  387. for bad_status in (400, 500, 599, 302):
  388. with pytest.raises(HTTPError):
  389. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_{bad_status}'))
  390. # Should not raise an error
  391. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200')).close()
  392. def test_response_url(self, handler):
  393. with handler() as rh:
  394. # Response url should be that of the last url in redirect chain
  395. res = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_301'))
  396. assert res.url == f'http://127.0.0.1:{self.http_port}/method'
  397. res.close()
  398. res2 = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_200'))
  399. assert res2.url == f'http://127.0.0.1:{self.http_port}/gen_200'
  400. res2.close()
  401. # Covers some basic cases we expect some level of consistency between request handlers for
  402. @pytest.mark.parametrize('redirect_status,method,expected', [
  403. # A 303 must either use GET or HEAD for subsequent request
  404. (303, 'POST', ('', 'GET', False)),
  405. (303, 'HEAD', ('', 'HEAD', False)),
  406. # 301 and 302 turn POST only into a GET
  407. (301, 'POST', ('', 'GET', False)),
  408. (301, 'HEAD', ('', 'HEAD', False)),
  409. (302, 'POST', ('', 'GET', False)),
  410. (302, 'HEAD', ('', 'HEAD', False)),
  411. # 307 and 308 should not change method
  412. (307, 'POST', ('testdata', 'POST', True)),
  413. (308, 'POST', ('testdata', 'POST', True)),
  414. (307, 'HEAD', ('', 'HEAD', False)),
  415. (308, 'HEAD', ('', 'HEAD', False)),
  416. ])
  417. def test_redirect(self, handler, redirect_status, method, expected):
  418. with handler() as rh:
  419. data = b'testdata' if method == 'POST' else None
  420. headers = {}
  421. if data is not None:
  422. headers['Content-Type'] = 'application/test'
  423. res = validate_and_send(
  424. rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_{redirect_status}', method=method, data=data,
  425. headers=headers))
  426. headers = b''
  427. data_recv = b''
  428. if data is not None:
  429. data_recv += res.read(len(data))
  430. if data_recv != data:
  431. headers += data_recv
  432. data_recv = b''
  433. headers += res.read()
  434. assert expected[0] == data_recv.decode()
  435. assert expected[1] == res.headers.get('method')
  436. assert expected[2] == ('content-length' in headers.decode().lower())
  437. def test_request_cookie_header(self, handler):
  438. # We should accept a Cookie header being passed as in normal headers and handle it appropriately.
  439. with handler() as rh:
  440. # Specified Cookie header should be used
  441. res = validate_and_send(
  442. rh, Request(
  443. f'http://127.0.0.1:{self.http_port}/headers',
  444. headers={'Cookie': 'test=test'})).read().decode()
  445. assert 'cookie: test=test' in res.lower()
  446. # Specified Cookie header should be removed on any redirect
  447. res = validate_and_send(
  448. rh, Request(
  449. f'http://127.0.0.1:{self.http_port}/308-to-headers',
  450. headers={'Cookie': 'test=test2'})).read().decode()
  451. assert 'cookie: test=test2' not in res.lower()
  452. # Specified Cookie header should override global cookiejar for that request
  453. # Whether cookies from the cookiejar is applied on the redirect is considered undefined for now
  454. cookiejar = YoutubeDLCookieJar()
  455. cookiejar.set_cookie(http.cookiejar.Cookie(
  456. version=0, name='test', value='ytdlp', port=None, port_specified=False,
  457. domain='127.0.0.1', domain_specified=True, domain_initial_dot=False, path='/',
  458. path_specified=True, secure=False, expires=None, discard=False, comment=None,
  459. comment_url=None, rest={}))
  460. with handler(cookiejar=cookiejar) as rh:
  461. data = validate_and_send(
  462. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', headers={'cookie': 'test=test3'})).read()
  463. assert b'cookie: test=ytdlp' not in data.lower()
  464. assert b'cookie: test=test3' in data.lower()
  465. def test_redirect_loop(self, handler):
  466. with handler() as rh:
  467. with pytest.raises(HTTPError, match='redirect loop'):
  468. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/redirect_loop'))
  469. def test_incompleteread(self, handler):
  470. with handler(timeout=2) as rh:
  471. with pytest.raises(IncompleteRead, match='13 bytes read, 234221 more expected'):
  472. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/incompleteread')).read()
  473. def test_cookies(self, handler):
  474. cookiejar = YoutubeDLCookieJar()
  475. cookiejar.set_cookie(http.cookiejar.Cookie(
  476. 0, 'test', 'ytdlp', None, False, '127.0.0.1', True,
  477. False, '/headers', True, False, None, False, None, None, {}))
  478. with handler(cookiejar=cookiejar) as rh:
  479. data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
  480. assert b'cookie: test=ytdlp' in data.lower()
  481. # Per request
  482. with handler() as rh:
  483. data = validate_and_send(
  484. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={'cookiejar': cookiejar})).read()
  485. assert b'cookie: test=ytdlp' in data.lower()
  486. def test_cookie_sync_only_cookiejar(self, handler):
  487. # Ensure that cookies are ONLY being handled by the cookiejar
  488. with handler() as rh:
  489. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/get_cookie', extensions={'cookiejar': YoutubeDLCookieJar()}))
  490. data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={'cookiejar': YoutubeDLCookieJar()})).read()
  491. assert b'cookie: test=ytdlp' not in data.lower()
  492. def test_cookie_sync_delete_cookie(self, handler):
  493. # Ensure that cookies are ONLY being handled by the cookiejar
  494. cookiejar = YoutubeDLCookieJar()
  495. with handler(cookiejar=cookiejar) as rh:
  496. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/get_cookie'))
  497. data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
  498. assert b'cookie: test=ytdlp' in data.lower()
  499. cookiejar.clear_session_cookies()
  500. data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read()
  501. assert b'cookie: test=ytdlp' not in data.lower()
  502. def test_headers(self, handler):
  503. with handler(headers=HTTPHeaderDict({'test1': 'test', 'test2': 'test2'})) as rh:
  504. # Global Headers
  505. data = validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).read().lower()
  506. assert b'test1: test' in data
  507. # Per request headers, merged with global
  508. data = validate_and_send(rh, Request(
  509. f'http://127.0.0.1:{self.http_port}/headers', headers={'test2': 'changed', 'test3': 'test3'})).read().lower()
  510. assert b'test1: test' in data
  511. assert b'test2: changed' in data
  512. assert b'test2: test2' not in data
  513. assert b'test3: test3' in data
  514. def test_read_timeout(self, handler):
  515. with handler() as rh:
  516. # Default timeout is 20 seconds, so this should go through
  517. validate_and_send(
  518. rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_1'))
  519. with handler(timeout=0.1) as rh:
  520. with pytest.raises(TransportError):
  521. validate_and_send(
  522. rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_5'))
  523. # Per request timeout, should override handler timeout
  524. validate_and_send(
  525. rh, Request(f'http://127.0.0.1:{self.http_port}/timeout_1', extensions={'timeout': 4}))
  526. def test_connect_timeout(self, handler):
  527. # nothing should be listening on this port
  528. connect_timeout_url = 'http://10.255.255.255'
  529. with handler(timeout=0.01) as rh, pytest.raises(TransportError):
  530. now = time.time()
  531. validate_and_send(rh, Request(connect_timeout_url))
  532. assert time.time() - now < DEFAULT_TIMEOUT
  533. # Per request timeout, should override handler timeout
  534. request = Request(connect_timeout_url, extensions={'timeout': 0.01})
  535. with handler() as rh, pytest.raises(TransportError):
  536. now = time.time()
  537. validate_and_send(rh, request)
  538. assert time.time() - now < DEFAULT_TIMEOUT
  539. def test_source_address(self, handler):
  540. source_address = f'127.0.0.{random.randint(5, 255)}'
  541. # on some systems these loopback addresses we need for testing may not be available
  542. # see: https://github.com/yt-dlp/yt-dlp/issues/8890
  543. verify_address_availability(source_address)
  544. with handler(source_address=source_address) as rh:
  545. data = validate_and_send(
  546. rh, Request(f'http://127.0.0.1:{self.http_port}/source_address')).read().decode()
  547. assert source_address == data
  548. # Not supported by CurlCFFI
  549. @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi')
  550. def test_gzip_trailing_garbage(self, handler):
  551. with handler() as rh:
  552. data = validate_and_send(rh, Request(f'http://localhost:{self.http_port}/trailing_garbage')).read().decode()
  553. assert data == '<html><video src="/vid.mp4" /></html>'
  554. @pytest.mark.skip_handler('CurlCFFI', 'not applicable to curl-cffi')
  555. @pytest.mark.skipif(not brotli, reason='brotli support is not installed')
  556. def test_brotli(self, handler):
  557. with handler() as rh:
  558. res = validate_and_send(
  559. rh, Request(
  560. f'http://127.0.0.1:{self.http_port}/content-encoding',
  561. headers={'ytdl-encoding': 'br'}))
  562. assert res.headers.get('Content-Encoding') == 'br'
  563. assert res.read() == b'<html><video src="/vid.mp4" /></html>'
  564. def test_deflate(self, handler):
  565. with handler() as rh:
  566. res = validate_and_send(
  567. rh, Request(
  568. f'http://127.0.0.1:{self.http_port}/content-encoding',
  569. headers={'ytdl-encoding': 'deflate'}))
  570. assert res.headers.get('Content-Encoding') == 'deflate'
  571. assert res.read() == b'<html><video src="/vid.mp4" /></html>'
  572. def test_gzip(self, handler):
  573. with handler() as rh:
  574. res = validate_and_send(
  575. rh, Request(
  576. f'http://127.0.0.1:{self.http_port}/content-encoding',
  577. headers={'ytdl-encoding': 'gzip'}))
  578. assert res.headers.get('Content-Encoding') == 'gzip'
  579. assert res.read() == b'<html><video src="/vid.mp4" /></html>'
  580. def test_multiple_encodings(self, handler):
  581. with handler() as rh:
  582. for pair in ('gzip,deflate', 'deflate, gzip', 'gzip, gzip', 'deflate, deflate'):
  583. res = validate_and_send(
  584. rh, Request(
  585. f'http://127.0.0.1:{self.http_port}/content-encoding',
  586. headers={'ytdl-encoding': pair}))
  587. assert res.headers.get('Content-Encoding') == pair
  588. assert res.read() == b'<html><video src="/vid.mp4" /></html>'
  589. @pytest.mark.skip_handler('CurlCFFI', 'not supported by curl-cffi')
  590. def test_unsupported_encoding(self, handler):
  591. with handler() as rh:
  592. res = validate_and_send(
  593. rh, Request(
  594. f'http://127.0.0.1:{self.http_port}/content-encoding',
  595. headers={'ytdl-encoding': 'unsupported', 'Accept-Encoding': '*'}))
  596. assert res.headers.get('Content-Encoding') == 'unsupported'
  597. assert res.read() == b'raw'
  598. def test_read(self, handler):
  599. with handler() as rh:
  600. res = validate_and_send(
  601. rh, Request(f'http://127.0.0.1:{self.http_port}/headers'))
  602. assert res.readable()
  603. assert res.read(1) == b'H'
  604. assert res.read(3) == b'ost'
  605. assert res.read().decode().endswith('\n\n')
  606. assert res.read() == b''
  607. def test_request_disable_proxy(self, handler):
  608. for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['http']:
  609. # Given the handler is configured with a proxy
  610. with handler(proxies={'http': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
  611. # When a proxy is explicitly set to None for the request
  612. res = validate_and_send(
  613. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', proxies={'http': None}))
  614. # Then no proxy should be used
  615. res.close()
  616. assert res.status == 200
  617. @pytest.mark.skip_handlers_if(
  618. lambda _, handler: Features.NO_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support NO_PROXY')
  619. def test_noproxy(self, handler):
  620. for proxy_proto in handler._SUPPORTED_PROXY_SCHEMES or ['http']:
  621. # Given the handler is configured with a proxy
  622. with handler(proxies={'http': f'{proxy_proto}://10.255.255.255'}, timeout=5) as rh:
  623. for no_proxy in (f'127.0.0.1:{self.http_port}', '127.0.0.1', 'localhost'):
  624. # When request no proxy includes the request url host
  625. nop_response = validate_and_send(
  626. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', proxies={'no': no_proxy}))
  627. # Then the proxy should not be used
  628. assert nop_response.status == 200
  629. nop_response.close()
  630. @pytest.mark.skip_handlers_if(
  631. lambda _, handler: Features.ALL_PROXY not in handler._SUPPORTED_FEATURES, 'handler does not support ALL_PROXY')
  632. def test_allproxy(self, handler):
  633. # This is a bit of a hacky test, but it should be enough to check whether the handler is using the proxy.
  634. # 0.1s might not be enough of a timeout if proxy is not used in all cases, but should still get failures.
  635. with handler(proxies={'all': 'http://10.255.255.255'}, timeout=0.1) as rh:
  636. with pytest.raises(TransportError):
  637. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/headers')).close()
  638. with handler(timeout=0.1) as rh:
  639. with pytest.raises(TransportError):
  640. validate_and_send(
  641. rh, Request(
  642. f'http://127.0.0.1:{self.http_port}/headers', proxies={'all': 'http://10.255.255.255'})).close()
  643. @pytest.mark.parametrize('handler', ['Urllib', 'Requests', 'CurlCFFI'], indirect=True)
  644. class TestClientCertificate:
  645. @classmethod
  646. def setup_class(cls):
  647. certfn = os.path.join(TEST_DIR, 'testcert.pem')
  648. cls.certdir = os.path.join(TEST_DIR, 'testdata', 'certificate')
  649. cacertfn = os.path.join(cls.certdir, 'ca.crt')
  650. cls.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), HTTPTestRequestHandler)
  651. sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  652. sslctx.verify_mode = ssl.CERT_REQUIRED
  653. sslctx.load_verify_locations(cafile=cacertfn)
  654. sslctx.load_cert_chain(certfn, None)
  655. cls.httpd.socket = sslctx.wrap_socket(cls.httpd.socket, server_side=True)
  656. cls.port = http_server_port(cls.httpd)
  657. cls.server_thread = threading.Thread(target=cls.httpd.serve_forever)
  658. cls.server_thread.daemon = True
  659. cls.server_thread.start()
  660. def _run_test(self, handler, **handler_kwargs):
  661. with handler(
  662. # Disable client-side validation of unacceptable self-signed testcert.pem
  663. # The test is of a check on the server side, so unaffected
  664. verify=False,
  665. **handler_kwargs,
  666. ) as rh:
  667. validate_and_send(rh, Request(f'https://127.0.0.1:{self.port}/video.html')).read().decode()
  668. def test_certificate_combined_nopass(self, handler):
  669. self._run_test(handler, client_cert={
  670. 'client_certificate': os.path.join(self.certdir, 'clientwithkey.crt'),
  671. })
  672. def test_certificate_nocombined_nopass(self, handler):
  673. self._run_test(handler, client_cert={
  674. 'client_certificate': os.path.join(self.certdir, 'client.crt'),
  675. 'client_certificate_key': os.path.join(self.certdir, 'client.key'),
  676. })
  677. def test_certificate_combined_pass(self, handler):
  678. self._run_test(handler, client_cert={
  679. 'client_certificate': os.path.join(self.certdir, 'clientwithencryptedkey.crt'),
  680. 'client_certificate_password': 'foobar',
  681. })
  682. def test_certificate_nocombined_pass(self, handler):
  683. self._run_test(handler, client_cert={
  684. 'client_certificate': os.path.join(self.certdir, 'client.crt'),
  685. 'client_certificate_key': os.path.join(self.certdir, 'clientencrypted.key'),
  686. 'client_certificate_password': 'foobar',
  687. })
  688. @pytest.mark.parametrize('handler', ['CurlCFFI'], indirect=True)
  689. class TestHTTPImpersonateRequestHandler(TestRequestHandlerBase):
  690. def test_supported_impersonate_targets(self, handler):
  691. with handler(headers=std_headers) as rh:
  692. # note: this assumes the impersonate request handler supports the impersonate extension
  693. for target in rh.supported_targets:
  694. res = validate_and_send(rh, Request(
  695. f'http://127.0.0.1:{self.http_port}/headers', extensions={'impersonate': target}))
  696. assert res.status == 200
  697. assert std_headers['user-agent'].lower() not in res.read().decode().lower()
  698. def test_response_extensions(self, handler):
  699. with handler() as rh:
  700. for target in rh.supported_targets:
  701. request = Request(
  702. f'http://127.0.0.1:{self.http_port}/gen_200', extensions={'impersonate': target})
  703. res = validate_and_send(rh, request)
  704. assert res.extensions['impersonate'] == rh._get_request_target(request)
  705. def test_http_error_response_extensions(self, handler):
  706. with handler() as rh:
  707. for target in rh.supported_targets:
  708. request = Request(
  709. f'http://127.0.0.1:{self.http_port}/gen_404', extensions={'impersonate': target})
  710. try:
  711. validate_and_send(rh, request)
  712. except HTTPError as e:
  713. res = e.response
  714. assert res.extensions['impersonate'] == rh._get_request_target(request)
  715. class TestRequestHandlerMisc:
  716. """Misc generic tests for request handlers, not related to request or validation testing"""
  717. @pytest.mark.parametrize('handler,logger_name', [
  718. ('Requests', 'urllib3'),
  719. ('Websockets', 'websockets.client'),
  720. ('Websockets', 'websockets.server'),
  721. ], indirect=['handler'])
  722. def test_remove_logging_handler(self, handler, logger_name):
  723. # Ensure any logging handlers, which may contain a YoutubeDL instance,
  724. # are removed when we close the request handler
  725. # See: https://github.com/yt-dlp/yt-dlp/issues/8922
  726. logging_handlers = logging.getLogger(logger_name).handlers
  727. before_count = len(logging_handlers)
  728. rh = handler()
  729. assert len(logging_handlers) == before_count + 1
  730. rh.close()
  731. assert len(logging_handlers) == before_count
  732. def test_wrap_request_errors(self):
  733. class TestRequestHandler(RequestHandler):
  734. def _validate(self, request):
  735. if request.headers.get('x-fail'):
  736. raise UnsupportedRequest('test error')
  737. def _send(self, request: Request):
  738. raise RequestError('test error')
  739. with TestRequestHandler(logger=FakeLogger()) as rh:
  740. with pytest.raises(UnsupportedRequest, match='test error') as exc_info:
  741. rh.validate(Request('http://example.com', headers={'x-fail': '1'}))
  742. assert exc_info.value.handler is rh
  743. with pytest.raises(RequestError, match='test error') as exc_info:
  744. rh.send(Request('http://example.com'))
  745. assert exc_info.value.handler is rh
  746. @pytest.mark.parametrize('handler', ['Urllib'], indirect=True)
  747. class TestUrllibRequestHandler(TestRequestHandlerBase):
  748. def test_file_urls(self, handler):
  749. # See https://github.com/ytdl-org/youtube-dl/issues/8227
  750. tf = tempfile.NamedTemporaryFile(delete=False)
  751. tf.write(b'foobar')
  752. tf.close()
  753. req = Request(pathlib.Path(tf.name).as_uri())
  754. with handler() as rh:
  755. with pytest.raises(UnsupportedRequest):
  756. rh.validate(req)
  757. # Test that urllib never loaded FileHandler
  758. with pytest.raises(TransportError):
  759. rh.send(req)
  760. with handler(enable_file_urls=True) as rh:
  761. res = validate_and_send(rh, req)
  762. assert res.read() == b'foobar'
  763. res.close()
  764. os.unlink(tf.name)
  765. def test_http_error_returns_content(self, handler):
  766. # urllib HTTPError will try close the underlying response if reference to the HTTPError object is lost
  767. def get_response():
  768. with handler() as rh:
  769. # headers url
  770. try:
  771. validate_and_send(rh, Request(f'http://127.0.0.1:{self.http_port}/gen_404'))
  772. except HTTPError as e:
  773. return e.response
  774. assert get_response().read() == b'<html></html>'
  775. def test_verify_cert_error_text(self, handler):
  776. # Check the output of the error message
  777. with handler() as rh:
  778. with pytest.raises(
  779. CertificateVerifyError,
  780. match=r'\[SSL: CERTIFICATE_VERIFY_FAILED\] certificate verify failed: self.signed certificate',
  781. ):
  782. validate_and_send(rh, Request(f'https://127.0.0.1:{self.https_port}/headers'))
  783. @pytest.mark.parametrize('req,match,version_check', [
  784. # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1256
  785. # bpo-39603: Check implemented in 3.7.9+, 3.8.5+
  786. (
  787. Request('http://127.0.0.1', method='GET\n'),
  788. 'method can\'t contain control characters',
  789. lambda v: v < (3, 7, 9) or (3, 8, 0) <= v < (3, 8, 5),
  790. ),
  791. # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1265
  792. # bpo-38576: Check implemented in 3.7.8+, 3.8.3+
  793. (
  794. Request('http://127.0.0. 1', method='GET'),
  795. 'URL can\'t contain control characters',
  796. lambda v: v < (3, 7, 8) or (3, 8, 0) <= v < (3, 8, 3),
  797. ),
  798. # https://github.com/python/cpython/blob/987b712b4aeeece336eed24fcc87a950a756c3e2/Lib/http/client.py#L1288C31-L1288C50
  799. (Request('http://127.0.0.1', headers={'foo\n': 'bar'}), 'Invalid header name', None),
  800. ])
  801. def test_httplib_validation_errors(self, handler, req, match, version_check):
  802. if version_check and version_check(sys.version_info):
  803. pytest.skip(f'Python {sys.version} version does not have the required validation for this test.')
  804. with handler() as rh:
  805. with pytest.raises(RequestError, match=match) as exc_info:
  806. validate_and_send(rh, req)
  807. assert not isinstance(exc_info.value, TransportError)
  808. @pytest.mark.parametrize('handler', ['Requests'], indirect=True)
  809. class TestRequestsRequestHandler(TestRequestHandlerBase):
  810. @pytest.mark.parametrize('raised,expected', [
  811. (lambda: requests.exceptions.ConnectTimeout(), TransportError),
  812. (lambda: requests.exceptions.ReadTimeout(), TransportError),
  813. (lambda: requests.exceptions.Timeout(), TransportError),
  814. (lambda: requests.exceptions.ConnectionError(), TransportError),
  815. (lambda: requests.exceptions.ProxyError(), ProxyError),
  816. (lambda: requests.exceptions.SSLError('12[CERTIFICATE_VERIFY_FAILED]34'), CertificateVerifyError),
  817. (lambda: requests.exceptions.SSLError(), SSLError),
  818. (lambda: requests.exceptions.InvalidURL(), RequestError),
  819. (lambda: requests.exceptions.InvalidHeader(), RequestError),
  820. # catch-all: https://github.com/psf/requests/blob/main/src/requests/adapters.py#L535
  821. (lambda: urllib3.exceptions.HTTPError(), TransportError),
  822. (lambda: requests.exceptions.RequestException(), RequestError),
  823. # (lambda: requests.exceptions.TooManyRedirects(), HTTPError) - Needs a response object
  824. ])
  825. def test_request_error_mapping(self, handler, monkeypatch, raised, expected):
  826. with handler() as rh:
  827. def mock_get_instance(*args, **kwargs):
  828. class MockSession:
  829. def request(self, *args, **kwargs):
  830. raise raised()
  831. return MockSession()
  832. monkeypatch.setattr(rh, '_get_instance', mock_get_instance)
  833. with pytest.raises(expected) as exc_info:
  834. rh.send(Request('http://fake'))
  835. assert exc_info.type is expected
  836. @pytest.mark.parametrize('raised,expected,match', [
  837. (lambda: urllib3.exceptions.SSLError(), SSLError, None),
  838. (lambda: urllib3.exceptions.TimeoutError(), TransportError, None),
  839. (lambda: urllib3.exceptions.ReadTimeoutError(None, None, None), TransportError, None),
  840. (lambda: urllib3.exceptions.ProtocolError(), TransportError, None),
  841. (lambda: urllib3.exceptions.DecodeError(), TransportError, None),
  842. (lambda: urllib3.exceptions.HTTPError(), TransportError, None), # catch-all
  843. (
  844. lambda: urllib3.exceptions.ProtocolError('error', http.client.IncompleteRead(partial=b'abc', expected=4)),
  845. IncompleteRead,
  846. '3 bytes read, 4 more expected',
  847. ),
  848. (
  849. lambda: urllib3.exceptions.ProtocolError('error', urllib3.exceptions.IncompleteRead(partial=3, expected=5)),
  850. IncompleteRead,
  851. '3 bytes read, 5 more expected',
  852. ),
  853. ])
  854. def test_response_error_mapping(self, handler, monkeypatch, raised, expected, match):
  855. from requests.models import Response as RequestsResponse
  856. from urllib3.response import HTTPResponse as Urllib3Response
  857. from yt_dlp.networking._requests import RequestsResponseAdapter
  858. requests_res = RequestsResponse()
  859. requests_res.raw = Urllib3Response(body=b'', status=200)
  860. res = RequestsResponseAdapter(requests_res)
  861. def mock_read(*args, **kwargs):
  862. raise raised()
  863. monkeypatch.setattr(res.fp, 'read', mock_read)
  864. with pytest.raises(expected, match=match) as exc_info:
  865. res.read()
  866. assert exc_info.type is expected
  867. def test_close(self, handler, monkeypatch):
  868. rh = handler()
  869. session = rh._get_instance(cookiejar=rh.cookiejar)
  870. called = False
  871. original_close = session.close
  872. def mock_close(*args, **kwargs):
  873. nonlocal called
  874. called = True
  875. return original_close(*args, **kwargs)
  876. monkeypatch.setattr(session, 'close', mock_close)
  877. rh.close()
  878. assert called
  879. @pytest.mark.parametrize('handler', ['CurlCFFI'], indirect=True)
  880. class TestCurlCFFIRequestHandler(TestRequestHandlerBase):
  881. @pytest.mark.parametrize('params,extensions', [
  882. ({'impersonate': ImpersonateTarget('chrome', '110')}, {}),
  883. ({'impersonate': ImpersonateTarget('chrome', '99')}, {'impersonate': ImpersonateTarget('chrome', '110')}),
  884. ])
  885. def test_impersonate(self, handler, params, extensions):
  886. with handler(headers=std_headers, **params) as rh:
  887. res = validate_and_send(
  888. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions=extensions)).read().decode()
  889. assert 'sec-ch-ua: "Chromium";v="110"' in res
  890. # Check that user agent is added over ours
  891. assert 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' in res
  892. def test_headers(self, handler):
  893. with handler(headers=std_headers) as rh:
  894. # Ensure curl-impersonate overrides our standard headers (usually added
  895. res = validate_and_send(
  896. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', extensions={
  897. 'impersonate': ImpersonateTarget('safari')}, headers={'x-custom': 'test', 'sec-fetch-mode': 'custom'})).read().decode().lower()
  898. assert std_headers['user-agent'].lower() not in res
  899. assert std_headers['accept-language'].lower() not in res
  900. assert std_headers['sec-fetch-mode'].lower() not in res
  901. # other than UA, custom headers that differ from std_headers should be kept
  902. assert 'sec-fetch-mode: custom' in res
  903. assert 'x-custom: test' in res
  904. # but when not impersonating don't remove std_headers
  905. res = validate_and_send(
  906. rh, Request(f'http://127.0.0.1:{self.http_port}/headers', headers={'x-custom': 'test'})).read().decode().lower()
  907. # std_headers should be present
  908. for k, v in std_headers.items():
  909. assert f'{k}: {v}'.lower() in res
  910. @pytest.mark.parametrize('raised,expected,match', [
  911. (lambda: curl_cffi.requests.errors.RequestsError(
  912. '', code=curl_cffi.const.CurlECode.PARTIAL_FILE), IncompleteRead, None),
  913. (lambda: curl_cffi.requests.errors.RequestsError(
  914. '', code=curl_cffi.const.CurlECode.OPERATION_TIMEDOUT), TransportError, None),
  915. (lambda: curl_cffi.requests.errors.RequestsError(
  916. '', code=curl_cffi.const.CurlECode.RECV_ERROR), TransportError, None),
  917. ])
  918. def test_response_error_mapping(self, handler, monkeypatch, raised, expected, match):
  919. import curl_cffi.requests
  920. from yt_dlp.networking._curlcffi import CurlCFFIResponseAdapter
  921. curl_res = curl_cffi.requests.Response()
  922. res = CurlCFFIResponseAdapter(curl_res)
  923. def mock_read(*args, **kwargs):
  924. try:
  925. raise raised()
  926. except Exception as e:
  927. e.response = curl_res
  928. raise
  929. monkeypatch.setattr(res.fp, 'read', mock_read)
  930. with pytest.raises(expected, match=match) as exc_info:
  931. res.read()
  932. assert exc_info.type is expected
  933. @pytest.mark.parametrize('raised,expected,match', [
  934. (lambda: curl_cffi.requests.errors.RequestsError(
  935. '', code=curl_cffi.const.CurlECode.OPERATION_TIMEDOUT), TransportError, None),
  936. (lambda: curl_cffi.requests.errors.RequestsError(
  937. '', code=curl_cffi.const.CurlECode.PEER_FAILED_VERIFICATION), CertificateVerifyError, None),
  938. (lambda: curl_cffi.requests.errors.RequestsError(
  939. '', code=curl_cffi.const.CurlECode.SSL_CONNECT_ERROR), SSLError, None),
  940. (lambda: curl_cffi.requests.errors.RequestsError(
  941. '', code=curl_cffi.const.CurlECode.TOO_MANY_REDIRECTS), HTTPError, None),
  942. (lambda: curl_cffi.requests.errors.RequestsError(
  943. '', code=curl_cffi.const.CurlECode.PROXY), ProxyError, None),
  944. ])
  945. def test_request_error_mapping(self, handler, monkeypatch, raised, expected, match):
  946. import curl_cffi.requests
  947. curl_res = curl_cffi.requests.Response()
  948. curl_res.status_code = 301
  949. with handler() as rh:
  950. original_get_instance = rh._get_instance
  951. def mock_get_instance(*args, **kwargs):
  952. instance = original_get_instance(*args, **kwargs)
  953. def request(*_, **__):
  954. try:
  955. raise raised()
  956. except Exception as e:
  957. e.response = curl_res
  958. raise
  959. monkeypatch.setattr(instance, 'request', request)
  960. return instance
  961. monkeypatch.setattr(rh, '_get_instance', mock_get_instance)
  962. with pytest.raises(expected) as exc_info:
  963. rh.send(Request('http://fake'))
  964. assert exc_info.type is expected
  965. def test_response_reader(self, handler):
  966. class FakeResponse:
  967. def __init__(self, raise_error=False):
  968. self.raise_error = raise_error
  969. self.closed = False
  970. def iter_content(self):
  971. yield b'foo'
  972. yield b'bar'
  973. yield b'z'
  974. if self.raise_error:
  975. raise Exception('test')
  976. def close(self):
  977. self.closed = True
  978. from yt_dlp.networking._curlcffi import CurlCFFIResponseReader
  979. res = CurlCFFIResponseReader(FakeResponse())
  980. assert res.readable
  981. assert res.bytes_read == 0
  982. assert res.read(1) == b'f'
  983. assert res.bytes_read == 3
  984. assert res._buffer == b'oo'
  985. assert res.read(2) == b'oo'
  986. assert res.bytes_read == 3
  987. assert res._buffer == b''
  988. assert res.read(2) == b'ba'
  989. assert res.bytes_read == 6
  990. assert res._buffer == b'r'
  991. assert res.read(3) == b'rz'
  992. assert res.bytes_read == 7
  993. assert res._buffer == b''
  994. assert res.closed
  995. assert res._response.closed
  996. # should handle no size param
  997. res2 = CurlCFFIResponseReader(FakeResponse())
  998. assert res2.read() == b'foobarz'
  999. assert res2.bytes_read == 7
  1000. assert res2._buffer == b''
  1001. assert res2.closed
  1002. # should close on an exception
  1003. res3 = CurlCFFIResponseReader(FakeResponse(raise_error=True))
  1004. with pytest.raises(Exception, match='test'):
  1005. res3.read()
  1006. assert res3._buffer == b''
  1007. assert res3.bytes_read == 7
  1008. assert res3.closed
  1009. # buffer should be cleared on close
  1010. res4 = CurlCFFIResponseReader(FakeResponse())
  1011. res4.read(2)
  1012. assert res4._buffer == b'o'
  1013. res4.close()
  1014. assert res4.closed
  1015. assert res4._buffer == b''
  1016. def run_validation(handler, error, req, **handler_kwargs):
  1017. with handler(**handler_kwargs) as rh:
  1018. if error:
  1019. with pytest.raises(error):
  1020. rh.validate(req)
  1021. else:
  1022. rh.validate(req)
  1023. class TestRequestHandlerValidation:
  1024. class ValidationRH(RequestHandler):
  1025. def _send(self, request):
  1026. raise RequestError('test')
  1027. class NoCheckRH(ValidationRH):
  1028. _SUPPORTED_FEATURES = None
  1029. _SUPPORTED_PROXY_SCHEMES = None
  1030. _SUPPORTED_URL_SCHEMES = None
  1031. def _check_extensions(self, extensions):
  1032. extensions.clear()
  1033. class HTTPSupportedRH(ValidationRH):
  1034. _SUPPORTED_URL_SCHEMES = ('http',)
  1035. URL_SCHEME_TESTS = [
  1036. # scheme, expected to fail, handler kwargs
  1037. ('Urllib', [
  1038. ('http', False, {}),
  1039. ('https', False, {}),
  1040. ('data', False, {}),
  1041. ('ftp', False, {}),
  1042. ('file', UnsupportedRequest, {}),
  1043. ('file', False, {'enable_file_urls': True}),
  1044. ]),
  1045. ('Requests', [
  1046. ('http', False, {}),
  1047. ('https', False, {}),
  1048. ]),
  1049. ('Websockets', [
  1050. ('ws', False, {}),
  1051. ('wss', False, {}),
  1052. ]),
  1053. ('CurlCFFI', [
  1054. ('http', False, {}),
  1055. ('https', False, {}),
  1056. ]),
  1057. (NoCheckRH, [('http', False, {})]),
  1058. (ValidationRH, [('http', UnsupportedRequest, {})]),
  1059. ]
  1060. PROXY_SCHEME_TESTS = [
  1061. # proxy scheme, expected to fail
  1062. ('Urllib', 'http', [
  1063. ('http', False),
  1064. ('https', UnsupportedRequest),
  1065. ('socks4', False),
  1066. ('socks4a', False),
  1067. ('socks5', False),
  1068. ('socks5h', False),
  1069. ('socks', UnsupportedRequest),
  1070. ]),
  1071. ('Requests', 'http', [
  1072. ('http', False),
  1073. ('https', False),
  1074. ('socks4', False),
  1075. ('socks4a', False),
  1076. ('socks5', False),
  1077. ('socks5h', False),
  1078. ]),
  1079. ('CurlCFFI', 'http', [
  1080. ('http', False),
  1081. ('https', False),
  1082. ('socks4', False),
  1083. ('socks4a', False),
  1084. ('socks5', False),
  1085. ('socks5h', False),
  1086. ]),
  1087. ('Websockets', 'ws', [
  1088. ('http', UnsupportedRequest),
  1089. ('https', UnsupportedRequest),
  1090. ('socks4', False),
  1091. ('socks4a', False),
  1092. ('socks5', False),
  1093. ('socks5h', False),
  1094. ]),
  1095. (NoCheckRH, 'http', [('http', False)]),
  1096. (HTTPSupportedRH, 'http', [('http', UnsupportedRequest)]),
  1097. (NoCheckRH, 'http', [('http', False)]),
  1098. (HTTPSupportedRH, 'http', [('http', UnsupportedRequest)]),
  1099. ]
  1100. PROXY_KEY_TESTS = [
  1101. # proxy key, proxy scheme, expected to fail
  1102. ('Urllib', 'http', [
  1103. ('all', 'http', False),
  1104. ('unrelated', 'http', False),
  1105. ]),
  1106. ('Requests', 'http', [
  1107. ('all', 'http', False),
  1108. ('unrelated', 'http', False),
  1109. ]),
  1110. ('CurlCFFI', 'http', [
  1111. ('all', 'http', False),
  1112. ('unrelated', 'http', False),
  1113. ]),
  1114. ('Websockets', 'ws', [
  1115. ('all', 'socks5', False),
  1116. ('unrelated', 'socks5', False),
  1117. ]),
  1118. (NoCheckRH, 'http', [('all', 'http', False)]),
  1119. (HTTPSupportedRH, 'http', [('all', 'http', UnsupportedRequest)]),
  1120. (HTTPSupportedRH, 'http', [('no', 'http', UnsupportedRequest)]),
  1121. ]
  1122. EXTENSION_TESTS = [
  1123. ('Urllib', 'http', [
  1124. ({'cookiejar': 'notacookiejar'}, AssertionError),
  1125. ({'cookiejar': YoutubeDLCookieJar()}, False),
  1126. ({'cookiejar': CookieJar()}, AssertionError),
  1127. ({'timeout': 1}, False),
  1128. ({'timeout': 'notatimeout'}, AssertionError),
  1129. ({'unsupported': 'value'}, UnsupportedRequest),
  1130. ({'legacy_ssl': False}, False),
  1131. ({'legacy_ssl': True}, False),
  1132. ({'legacy_ssl': 'notabool'}, AssertionError),
  1133. ]),
  1134. ('Requests', 'http', [
  1135. ({'cookiejar': 'notacookiejar'}, AssertionError),
  1136. ({'cookiejar': YoutubeDLCookieJar()}, False),
  1137. ({'timeout': 1}, False),
  1138. ({'timeout': 'notatimeout'}, AssertionError),
  1139. ({'unsupported': 'value'}, UnsupportedRequest),
  1140. ({'legacy_ssl': False}, False),
  1141. ({'legacy_ssl': True}, False),
  1142. ({'legacy_ssl': 'notabool'}, AssertionError),
  1143. ]),
  1144. ('CurlCFFI', 'http', [
  1145. ({'cookiejar': 'notacookiejar'}, AssertionError),
  1146. ({'cookiejar': YoutubeDLCookieJar()}, False),
  1147. ({'timeout': 1}, False),
  1148. ({'timeout': 'notatimeout'}, AssertionError),
  1149. ({'unsupported': 'value'}, UnsupportedRequest),
  1150. ({'impersonate': ImpersonateTarget('badtarget', None, None, None)}, UnsupportedRequest),
  1151. ({'impersonate': 123}, AssertionError),
  1152. ({'impersonate': ImpersonateTarget('chrome', None, None, None)}, False),
  1153. ({'impersonate': ImpersonateTarget(None, None, None, None)}, False),
  1154. ({'impersonate': ImpersonateTarget()}, False),
  1155. ({'impersonate': 'chrome'}, AssertionError),
  1156. ({'legacy_ssl': False}, False),
  1157. ({'legacy_ssl': True}, False),
  1158. ({'legacy_ssl': 'notabool'}, AssertionError),
  1159. ]),
  1160. (NoCheckRH, 'http', [
  1161. ({'cookiejar': 'notacookiejar'}, False),
  1162. ({'somerandom': 'test'}, False), # but any extension is allowed through
  1163. ]),
  1164. ('Websockets', 'ws', [
  1165. ({'cookiejar': YoutubeDLCookieJar()}, False),
  1166. ({'timeout': 2}, False),
  1167. ({'legacy_ssl': False}, False),
  1168. ({'legacy_ssl': True}, False),
  1169. ({'legacy_ssl': 'notabool'}, AssertionError),
  1170. ]),
  1171. ]
  1172. @pytest.mark.parametrize('handler,fail,scheme', [
  1173. ('Urllib', False, 'http'),
  1174. ('Requests', False, 'http'),
  1175. ('CurlCFFI', False, 'http'),
  1176. ('Websockets', False, 'ws'),
  1177. ], indirect=['handler'])
  1178. def test_no_proxy(self, handler, fail, scheme):
  1179. run_validation(handler, fail, Request(f'{scheme}://', proxies={'no': '127.0.0.1,github.com'}))
  1180. run_validation(handler, fail, Request(f'{scheme}://'), proxies={'no': '127.0.0.1,github.com'})
  1181. @pytest.mark.parametrize('handler,scheme', [
  1182. ('Urllib', 'http'),
  1183. (HTTPSupportedRH, 'http'),
  1184. ('Requests', 'http'),
  1185. ('CurlCFFI', 'http'),
  1186. ('Websockets', 'ws'),
  1187. ], indirect=['handler'])
  1188. def test_empty_proxy(self, handler, scheme):
  1189. run_validation(handler, False, Request(f'{scheme}://', proxies={scheme: None}))
  1190. run_validation(handler, False, Request(f'{scheme}://'), proxies={scheme: None})
  1191. @pytest.mark.parametrize('proxy_url', ['//example.com', 'example.com', '127.0.0.1', '/a/b/c'])
  1192. @pytest.mark.parametrize('handler,scheme', [
  1193. ('Urllib', 'http'),
  1194. (HTTPSupportedRH, 'http'),
  1195. ('Requests', 'http'),
  1196. ('CurlCFFI', 'http'),
  1197. ('Websockets', 'ws'),
  1198. ], indirect=['handler'])
  1199. def test_invalid_proxy_url(self, handler, scheme, proxy_url):
  1200. run_validation(handler, UnsupportedRequest, Request(f'{scheme}://', proxies={scheme: proxy_url}))
  1201. @pytest.mark.parametrize('handler,scheme,fail,handler_kwargs', [
  1202. (handler_tests[0], scheme, fail, handler_kwargs)
  1203. for handler_tests in URL_SCHEME_TESTS
  1204. for scheme, fail, handler_kwargs in handler_tests[1]
  1205. ], indirect=['handler'])
  1206. def test_url_scheme(self, handler, scheme, fail, handler_kwargs):
  1207. run_validation(handler, fail, Request(f'{scheme}://'), **(handler_kwargs or {}))
  1208. @pytest.mark.parametrize('handler,scheme,proxy_key,proxy_scheme,fail', [
  1209. (handler_tests[0], handler_tests[1], proxy_key, proxy_scheme, fail)
  1210. for handler_tests in PROXY_KEY_TESTS
  1211. for proxy_key, proxy_scheme, fail in handler_tests[2]
  1212. ], indirect=['handler'])
  1213. def test_proxy_key(self, handler, scheme, proxy_key, proxy_scheme, fail):
  1214. run_validation(handler, fail, Request(f'{scheme}://', proxies={proxy_key: f'{proxy_scheme}://example.com'}))
  1215. run_validation(handler, fail, Request(f'{scheme}://'), proxies={proxy_key: f'{proxy_scheme}://example.com'})
  1216. @pytest.mark.parametrize('handler,req_scheme,scheme,fail', [
  1217. (handler_tests[0], handler_tests[1], scheme, fail)
  1218. for handler_tests in PROXY_SCHEME_TESTS
  1219. for scheme, fail in handler_tests[2]
  1220. ], indirect=['handler'])
  1221. def test_proxy_scheme(self, handler, req_scheme, scheme, fail):
  1222. run_validation(handler, fail, Request(f'{req_scheme}://', proxies={req_scheme: f'{scheme}://example.com'}))
  1223. run_validation(handler, fail, Request(f'{req_scheme}://'), proxies={req_scheme: f'{scheme}://example.com'})
  1224. @pytest.mark.parametrize('handler,scheme,extensions,fail', [
  1225. (handler_tests[0], handler_tests[1], extensions, fail)
  1226. for handler_tests in EXTENSION_TESTS
  1227. for extensions, fail in handler_tests[2]
  1228. ], indirect=['handler'])
  1229. def test_extension(self, handler, scheme, extensions, fail):
  1230. run_validation(
  1231. handler, fail, Request(f'{scheme}://', extensions=extensions))
  1232. def test_invalid_request_type(self):
  1233. rh = self.ValidationRH(logger=FakeLogger())
  1234. for method in (rh.validate, rh.send):
  1235. with pytest.raises(TypeError, match='Expected an instance of Request'):
  1236. method('not a request')
  1237. class FakeResponse(Response):
  1238. def __init__(self, request):
  1239. # XXX: we could make request part of standard response interface
  1240. self.request = request
  1241. super().__init__(fp=io.BytesIO(b''), headers={}, url=request.url)
  1242. class FakeRH(RequestHandler):
  1243. def __init__(self, *args, **params):
  1244. self.params = params
  1245. super().__init__(*args, **params)
  1246. def _validate(self, request):
  1247. return
  1248. def _send(self, request: Request):
  1249. if request.url.startswith('ssl://'):
  1250. raise SSLError(request.url[len('ssl://'):])
  1251. return FakeResponse(request)
  1252. class FakeRHYDL(FakeYDL):
  1253. def __init__(self, *args, **kwargs):
  1254. super().__init__(*args, **kwargs)
  1255. self._request_director = self.build_request_director([FakeRH])
  1256. class AllUnsupportedRHYDL(FakeYDL):
  1257. def __init__(self, *args, **kwargs):
  1258. class UnsupportedRH(RequestHandler):
  1259. def _send(self, request: Request):
  1260. pass
  1261. _SUPPORTED_FEATURES = ()
  1262. _SUPPORTED_PROXY_SCHEMES = ()
  1263. _SUPPORTED_URL_SCHEMES = ()
  1264. super().__init__(*args, **kwargs)
  1265. self._request_director = self.build_request_director([UnsupportedRH])
  1266. class TestRequestDirector:
  1267. def test_handler_operations(self):
  1268. director = RequestDirector(logger=FakeLogger())
  1269. handler = FakeRH(logger=FakeLogger())
  1270. director.add_handler(handler)
  1271. assert director.handlers.get(FakeRH.RH_KEY) is handler
  1272. # Handler should overwrite
  1273. handler2 = FakeRH(logger=FakeLogger())
  1274. director.add_handler(handler2)
  1275. assert director.handlers.get(FakeRH.RH_KEY) is not handler
  1276. assert director.handlers.get(FakeRH.RH_KEY) is handler2
  1277. assert len(director.handlers) == 1
  1278. class AnotherFakeRH(FakeRH):
  1279. pass
  1280. director.add_handler(AnotherFakeRH(logger=FakeLogger()))
  1281. assert len(director.handlers) == 2
  1282. assert director.handlers.get(AnotherFakeRH.RH_KEY).RH_KEY == AnotherFakeRH.RH_KEY
  1283. director.handlers.pop(FakeRH.RH_KEY, None)
  1284. assert director.handlers.get(FakeRH.RH_KEY) is None
  1285. assert len(director.handlers) == 1
  1286. # RequestErrors should passthrough
  1287. with pytest.raises(SSLError):
  1288. director.send(Request('ssl://something'))
  1289. def test_send(self):
  1290. director = RequestDirector(logger=FakeLogger())
  1291. with pytest.raises(RequestError):
  1292. director.send(Request('any://'))
  1293. director.add_handler(FakeRH(logger=FakeLogger()))
  1294. assert isinstance(director.send(Request('http://')), FakeResponse)
  1295. def test_unsupported_handlers(self):
  1296. class SupportedRH(RequestHandler):
  1297. _SUPPORTED_URL_SCHEMES = ['http']
  1298. def _send(self, request: Request):
  1299. return Response(fp=io.BytesIO(b'supported'), headers={}, url=request.url)
  1300. director = RequestDirector(logger=FakeLogger())
  1301. director.add_handler(SupportedRH(logger=FakeLogger()))
  1302. director.add_handler(FakeRH(logger=FakeLogger()))
  1303. # First should take preference
  1304. assert director.send(Request('http://')).read() == b'supported'
  1305. assert director.send(Request('any://')).read() == b''
  1306. director.handlers.pop(FakeRH.RH_KEY)
  1307. with pytest.raises(NoSupportingHandlers):
  1308. director.send(Request('any://'))
  1309. def test_unexpected_error(self):
  1310. director = RequestDirector(logger=FakeLogger())
  1311. class UnexpectedRH(FakeRH):
  1312. def _send(self, request: Request):
  1313. raise TypeError('something')
  1314. director.add_handler(UnexpectedRH(logger=FakeLogger))
  1315. with pytest.raises(NoSupportingHandlers, match=r'1 unexpected error'):
  1316. director.send(Request('any://'))
  1317. director.handlers.clear()
  1318. assert len(director.handlers) == 0
  1319. # Should not be fatal
  1320. director.add_handler(FakeRH(logger=FakeLogger()))
  1321. director.add_handler(UnexpectedRH(logger=FakeLogger))
  1322. assert director.send(Request('any://'))
  1323. def test_preference(self):
  1324. director = RequestDirector(logger=FakeLogger())
  1325. director.add_handler(FakeRH(logger=FakeLogger()))
  1326. class SomeRH(RequestHandler):
  1327. _SUPPORTED_URL_SCHEMES = ['http']
  1328. def _send(self, request: Request):
  1329. return Response(fp=io.BytesIO(b'supported'), headers={}, url=request.url)
  1330. def some_preference(rh, request):
  1331. return (0 if not isinstance(rh, SomeRH)
  1332. else 100 if 'prefer' in request.headers
  1333. else -1)
  1334. director.add_handler(SomeRH(logger=FakeLogger()))
  1335. director.preferences.add(some_preference)
  1336. assert director.send(Request('http://')).read() == b''
  1337. assert director.send(Request('http://', headers={'prefer': '1'})).read() == b'supported'
  1338. def test_close(self, monkeypatch):
  1339. director = RequestDirector(logger=FakeLogger())
  1340. director.add_handler(FakeRH(logger=FakeLogger()))
  1341. called = False
  1342. def mock_close(*args, **kwargs):
  1343. nonlocal called
  1344. called = True
  1345. monkeypatch.setattr(director.handlers[FakeRH.RH_KEY], 'close', mock_close)
  1346. director.close()
  1347. assert called
  1348. # XXX: do we want to move this to test_YoutubeDL.py?
  1349. class TestYoutubeDLNetworking:
  1350. @staticmethod
  1351. def build_handler(ydl, handler: RequestHandler = FakeRH):
  1352. return ydl.build_request_director([handler]).handlers.get(handler.RH_KEY)
  1353. def test_compat_opener(self):
  1354. with FakeYDL() as ydl:
  1355. with warnings.catch_warnings():
  1356. warnings.simplefilter('ignore', category=DeprecationWarning)
  1357. assert isinstance(ydl._opener, urllib.request.OpenerDirector)
  1358. @pytest.mark.parametrize('proxy,expected', [
  1359. ('http://127.0.0.1:8080', {'all': 'http://127.0.0.1:8080'}),
  1360. ('', {'all': '__noproxy__'}),
  1361. (None, {'http': 'http://127.0.0.1:8081', 'https': 'http://127.0.0.1:8081'}), # env, set https
  1362. ])
  1363. def test_proxy(self, proxy, expected, monkeypatch):
  1364. monkeypatch.setenv('HTTP_PROXY', 'http://127.0.0.1:8081')
  1365. with FakeYDL({'proxy': proxy}) as ydl:
  1366. assert ydl.proxies == expected
  1367. def test_compat_request(self):
  1368. with FakeRHYDL() as ydl:
  1369. assert ydl.urlopen('test://')
  1370. urllib_req = urllib.request.Request('http://foo.bar', data=b'test', method='PUT', headers={'X-Test': '1'})
  1371. urllib_req.add_unredirected_header('Cookie', 'bob=bob')
  1372. urllib_req.timeout = 2
  1373. with warnings.catch_warnings():
  1374. warnings.simplefilter('ignore', category=DeprecationWarning)
  1375. req = ydl.urlopen(urllib_req).request
  1376. assert req.url == urllib_req.get_full_url()
  1377. assert req.data == urllib_req.data
  1378. assert req.method == urllib_req.get_method()
  1379. assert 'X-Test' in req.headers
  1380. assert 'Cookie' in req.headers
  1381. assert req.extensions.get('timeout') == 2
  1382. with pytest.raises(AssertionError):
  1383. ydl.urlopen(None)
  1384. def test_extract_basic_auth(self):
  1385. with FakeRHYDL() as ydl:
  1386. res = ydl.urlopen(Request('http://user:pass@foo.bar'))
  1387. assert res.request.headers['Authorization'] == 'Basic dXNlcjpwYXNz'
  1388. def test_sanitize_url(self):
  1389. with FakeRHYDL() as ydl:
  1390. res = ydl.urlopen(Request('httpss://foo.bar'))
  1391. assert res.request.url == 'https://foo.bar'
  1392. def test_file_urls_error(self):
  1393. # use urllib handler
  1394. with FakeYDL() as ydl:
  1395. with pytest.raises(RequestError, match=r'file:// URLs are disabled by default'):
  1396. ydl.urlopen('file://')
  1397. @pytest.mark.parametrize('scheme', (['ws', 'wss']))
  1398. def test_websocket_unavailable_error(self, scheme):
  1399. with AllUnsupportedRHYDL() as ydl:
  1400. with pytest.raises(RequestError, match=r'This request requires WebSocket support'):
  1401. ydl.urlopen(f'{scheme}://')
  1402. def test_legacy_server_connect_error(self):
  1403. with FakeRHYDL() as ydl:
  1404. for error in ('UNSAFE_LEGACY_RENEGOTIATION_DISABLED', 'SSLV3_ALERT_HANDSHAKE_FAILURE'):
  1405. with pytest.raises(RequestError, match=r'Try using --legacy-server-connect'):
  1406. ydl.urlopen(f'ssl://{error}')
  1407. with pytest.raises(SSLError, match='testerror'):
  1408. ydl.urlopen('ssl://testerror')
  1409. def test_unsupported_impersonate_target(self):
  1410. class FakeImpersonationRHYDL(FakeYDL):
  1411. def __init__(self, *args, **kwargs):
  1412. class HTTPRH(RequestHandler):
  1413. def _send(self, request: Request):
  1414. pass
  1415. _SUPPORTED_URL_SCHEMES = ('http',)
  1416. _SUPPORTED_PROXY_SCHEMES = None
  1417. super().__init__(*args, **kwargs)
  1418. self._request_director = self.build_request_director([HTTPRH])
  1419. with FakeImpersonationRHYDL() as ydl:
  1420. with pytest.raises(
  1421. RequestError,
  1422. match=r'Impersonate target "test" is not available',
  1423. ):
  1424. ydl.urlopen(Request('http://', extensions={'impersonate': ImpersonateTarget('test', None, None, None)}))
  1425. def test_unsupported_impersonate_extension(self):
  1426. class FakeHTTPRHYDL(FakeYDL):
  1427. def __init__(self, *args, **kwargs):
  1428. class IRH(ImpersonateRequestHandler):
  1429. def _send(self, request: Request):
  1430. pass
  1431. _SUPPORTED_URL_SCHEMES = ('http',)
  1432. _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget('abc'): 'test'}
  1433. _SUPPORTED_PROXY_SCHEMES = None
  1434. super().__init__(*args, **kwargs)
  1435. self._request_director = self.build_request_director([IRH])
  1436. with FakeHTTPRHYDL() as ydl:
  1437. with pytest.raises(
  1438. RequestError,
  1439. match=r'Impersonate target "test" is not available',
  1440. ):
  1441. ydl.urlopen(Request('http://', extensions={'impersonate': ImpersonateTarget('test', None, None, None)}))
  1442. def test_raise_impersonate_error(self):
  1443. with pytest.raises(
  1444. YoutubeDLError,
  1445. match=r'Impersonate target "test" is not available',
  1446. ):
  1447. FakeYDL({'impersonate': ImpersonateTarget('test', None, None, None)})
  1448. def test_pass_impersonate_param(self, monkeypatch):
  1449. class IRH(ImpersonateRequestHandler):
  1450. def _send(self, request: Request):
  1451. pass
  1452. _SUPPORTED_URL_SCHEMES = ('http',)
  1453. _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget('abc'): 'test'}
  1454. # Bypass the check on initialize
  1455. brh = FakeYDL.build_request_director
  1456. monkeypatch.setattr(FakeYDL, 'build_request_director', lambda cls, handlers, preferences=None: brh(cls, handlers=[IRH]))
  1457. with FakeYDL({
  1458. 'impersonate': ImpersonateTarget('abc', None, None, None),
  1459. }) as ydl:
  1460. rh = self.build_handler(ydl, IRH)
  1461. assert rh.impersonate == ImpersonateTarget('abc', None, None, None)
  1462. def test_get_impersonate_targets(self):
  1463. handlers = []
  1464. for target_client in ('abc', 'xyz', 'asd'):
  1465. class TestRH(ImpersonateRequestHandler):
  1466. def _send(self, request: Request):
  1467. pass
  1468. _SUPPORTED_URL_SCHEMES = ('http',)
  1469. _SUPPORTED_IMPERSONATE_TARGET_MAP = {ImpersonateTarget(target_client): 'test'}
  1470. RH_KEY = target_client
  1471. RH_NAME = target_client
  1472. handlers.append(TestRH)
  1473. with FakeYDL() as ydl:
  1474. ydl._request_director = ydl.build_request_director(handlers)
  1475. assert set(ydl._get_available_impersonate_targets()) == {
  1476. (ImpersonateTarget('xyz'), 'xyz'),
  1477. (ImpersonateTarget('abc'), 'abc'),
  1478. (ImpersonateTarget('asd'), 'asd'),
  1479. }
  1480. assert ydl._impersonate_target_available(ImpersonateTarget('abc'))
  1481. assert ydl._impersonate_target_available(ImpersonateTarget())
  1482. assert not ydl._impersonate_target_available(ImpersonateTarget('zxy'))
  1483. @pytest.mark.parametrize('proxy_key,proxy_url,expected', [
  1484. ('http', '__noproxy__', None),
  1485. ('no', '127.0.0.1,foo.bar', '127.0.0.1,foo.bar'),
  1486. ('https', 'example.com', 'http://example.com'),
  1487. ('https', '//example.com', 'http://example.com'),
  1488. ('https', 'socks5://example.com', 'socks5h://example.com'),
  1489. ('http', 'socks://example.com', 'socks4://example.com'),
  1490. ('http', 'socks4://example.com', 'socks4://example.com'),
  1491. ('unrelated', '/bad/proxy', '/bad/proxy'), # clean_proxies should ignore bad proxies
  1492. ])
  1493. def test_clean_proxy(self, proxy_key, proxy_url, expected, monkeypatch):
  1494. # proxies should be cleaned in urlopen()
  1495. with FakeRHYDL() as ydl:
  1496. req = ydl.urlopen(Request('test://', proxies={proxy_key: proxy_url})).request
  1497. assert req.proxies[proxy_key] == expected
  1498. # and should also be cleaned when building the handler
  1499. monkeypatch.setenv(f'{proxy_key.upper()}_PROXY', proxy_url)
  1500. with FakeYDL() as ydl:
  1501. rh = self.build_handler(ydl)
  1502. assert rh.proxies[proxy_key] == expected
  1503. def test_clean_proxy_header(self):
  1504. with FakeRHYDL() as ydl:
  1505. req = ydl.urlopen(Request('test://', headers={'ytdl-request-proxy': '//foo.bar'})).request
  1506. assert 'ytdl-request-proxy' not in req.headers
  1507. assert req.proxies == {'all': 'http://foo.bar'}
  1508. with FakeYDL({'http_headers': {'ytdl-request-proxy': '//foo.bar'}}) as ydl:
  1509. rh = self.build_handler(ydl)
  1510. assert 'ytdl-request-proxy' not in rh.headers
  1511. assert rh.proxies == {'all': 'http://foo.bar'}
  1512. def test_clean_header(self):
  1513. with FakeRHYDL() as ydl:
  1514. res = ydl.urlopen(Request('test://', headers={'Youtubedl-no-compression': True}))
  1515. assert 'Youtubedl-no-compression' not in res.request.headers
  1516. assert res.request.headers.get('Accept-Encoding') == 'identity'
  1517. with FakeYDL({'http_headers': {'Youtubedl-no-compression': True}}) as ydl:
  1518. rh = self.build_handler(ydl)
  1519. assert 'Youtubedl-no-compression' not in rh.headers
  1520. assert rh.headers.get('Accept-Encoding') == 'identity'
  1521. with FakeYDL({'http_headers': {'Ytdl-socks-proxy': 'socks://localhost:1080'}}) as ydl:
  1522. rh = self.build_handler(ydl)
  1523. assert 'Ytdl-socks-proxy' not in rh.headers
  1524. def test_build_handler_params(self):
  1525. with FakeYDL({
  1526. 'http_headers': {'test': 'testtest'},
  1527. 'socket_timeout': 2,
  1528. 'proxy': 'http://127.0.0.1:8080',
  1529. 'source_address': '127.0.0.45',
  1530. 'debug_printtraffic': True,
  1531. 'compat_opts': ['no-certifi'],
  1532. 'nocheckcertificate': True,
  1533. 'legacyserverconnect': True,
  1534. }) as ydl:
  1535. rh = self.build_handler(ydl)
  1536. assert rh.headers.get('test') == 'testtest'
  1537. assert 'Accept' in rh.headers # ensure std_headers are still there
  1538. assert rh.timeout == 2
  1539. assert rh.proxies.get('all') == 'http://127.0.0.1:8080'
  1540. assert rh.source_address == '127.0.0.45'
  1541. assert rh.verbose is True
  1542. assert rh.prefer_system_certs is True
  1543. assert rh.verify is False
  1544. assert rh.legacy_ssl_support is True
  1545. @pytest.mark.parametrize('ydl_params', [
  1546. {'client_certificate': 'fakecert.crt'},
  1547. {'client_certificate': 'fakecert.crt', 'client_certificate_key': 'fakekey.key'},
  1548. {'client_certificate': 'fakecert.crt', 'client_certificate_key': 'fakekey.key', 'client_certificate_password': 'foobar'},
  1549. {'client_certificate_key': 'fakekey.key', 'client_certificate_password': 'foobar'},
  1550. ])
  1551. def test_client_certificate(self, ydl_params):
  1552. with FakeYDL(ydl_params) as ydl:
  1553. rh = self.build_handler(ydl)
  1554. assert rh._client_cert == ydl_params # XXX: Too bound to implementation
  1555. def test_urllib_file_urls(self):
  1556. with FakeYDL({'enable_file_urls': False}) as ydl:
  1557. rh = self.build_handler(ydl, UrllibRH)
  1558. assert rh.enable_file_urls is False
  1559. with FakeYDL({'enable_file_urls': True}) as ydl:
  1560. rh = self.build_handler(ydl, UrllibRH)
  1561. assert rh.enable_file_urls is True
  1562. def test_compat_opt_prefer_urllib(self):
  1563. # This assumes urllib only has a preference when this compat opt is given
  1564. with FakeYDL({'compat_opts': ['prefer-legacy-http-handler']}) as ydl:
  1565. director = ydl.build_request_director([UrllibRH])
  1566. assert len(director.preferences) == 1
  1567. assert director.preferences.pop()(UrllibRH, None)
  1568. class TestRequest:
  1569. def test_query(self):
  1570. req = Request('http://example.com?q=something', query={'v': 'xyz'})
  1571. assert req.url == 'http://example.com?q=something&v=xyz'
  1572. req.update(query={'v': '123'})
  1573. assert req.url == 'http://example.com?q=something&v=123'
  1574. req.update(url='http://example.com', query={'v': 'xyz'})
  1575. assert req.url == 'http://example.com?v=xyz'
  1576. def test_method(self):
  1577. req = Request('http://example.com')
  1578. assert req.method == 'GET'
  1579. req.data = b'test'
  1580. assert req.method == 'POST'
  1581. req.data = None
  1582. assert req.method == 'GET'
  1583. req.data = b'test2'
  1584. req.method = 'PUT'
  1585. assert req.method == 'PUT'
  1586. req.data = None
  1587. assert req.method == 'PUT'
  1588. with pytest.raises(TypeError):
  1589. req.method = 1
  1590. def test_request_helpers(self):
  1591. assert HEADRequest('http://example.com').method == 'HEAD'
  1592. assert PUTRequest('http://example.com').method == 'PUT'
  1593. def test_headers(self):
  1594. req = Request('http://example.com', headers={'tesT': 'test'})
  1595. assert req.headers == HTTPHeaderDict({'test': 'test'})
  1596. req.update(headers={'teSt2': 'test2'})
  1597. assert req.headers == HTTPHeaderDict({'test': 'test', 'test2': 'test2'})
  1598. req.headers = new_headers = HTTPHeaderDict({'test': 'test'})
  1599. assert req.headers == HTTPHeaderDict({'test': 'test'})
  1600. assert req.headers is new_headers
  1601. # test converts dict to case insensitive dict
  1602. req.headers = new_headers = {'test2': 'test2'}
  1603. assert isinstance(req.headers, HTTPHeaderDict)
  1604. assert req.headers is not new_headers
  1605. with pytest.raises(TypeError):
  1606. req.headers = None
  1607. def test_data_type(self):
  1608. req = Request('http://example.com')
  1609. assert req.data is None
  1610. # test bytes is allowed
  1611. req.data = b'test'
  1612. assert req.data == b'test'
  1613. # test iterable of bytes is allowed
  1614. i = [b'test', b'test2']
  1615. req.data = i
  1616. assert req.data == i
  1617. # test file-like object is allowed
  1618. f = io.BytesIO(b'test')
  1619. req.data = f
  1620. assert req.data == f
  1621. # common mistake: test str not allowed
  1622. with pytest.raises(TypeError):
  1623. req.data = 'test'
  1624. assert req.data != 'test'
  1625. # common mistake: test dict is not allowed
  1626. with pytest.raises(TypeError):
  1627. req.data = {'test': 'test'}
  1628. assert req.data != {'test': 'test'}
  1629. def test_content_length_header(self):
  1630. req = Request('http://example.com', headers={'Content-Length': '0'}, data=b'')
  1631. assert req.headers.get('Content-Length') == '0'
  1632. req.data = b'test'
  1633. assert 'Content-Length' not in req.headers
  1634. req = Request('http://example.com', headers={'Content-Length': '10'})
  1635. assert 'Content-Length' not in req.headers
  1636. def test_content_type_header(self):
  1637. req = Request('http://example.com', headers={'Content-Type': 'test'}, data=b'test')
  1638. assert req.headers.get('Content-Type') == 'test'
  1639. req.data = b'test2'
  1640. assert req.headers.get('Content-Type') == 'test'
  1641. req.data = None
  1642. assert 'Content-Type' not in req.headers
  1643. req.data = b'test3'
  1644. assert req.headers.get('Content-Type') == 'application/x-www-form-urlencoded'
  1645. def test_update_req(self):
  1646. req = Request('http://example.com')
  1647. assert req.data is None
  1648. assert req.method == 'GET'
  1649. assert 'Content-Type' not in req.headers
  1650. # Test that zero-byte payloads will be sent
  1651. req.update(data=b'')
  1652. assert req.data == b''
  1653. assert req.method == 'POST'
  1654. assert req.headers.get('Content-Type') == 'application/x-www-form-urlencoded'
  1655. def test_proxies(self):
  1656. req = Request(url='http://example.com', proxies={'http': 'http://127.0.0.1:8080'})
  1657. assert req.proxies == {'http': 'http://127.0.0.1:8080'}
  1658. def test_extensions(self):
  1659. req = Request(url='http://example.com', extensions={'timeout': 2})
  1660. assert req.extensions == {'timeout': 2}
  1661. def test_copy(self):
  1662. req = Request(
  1663. url='http://example.com',
  1664. extensions={'cookiejar': CookieJar()},
  1665. headers={'Accept-Encoding': 'br'},
  1666. proxies={'http': 'http://127.0.0.1'},
  1667. data=[b'123'],
  1668. )
  1669. req_copy = req.copy()
  1670. assert req_copy is not req
  1671. assert req_copy.url == req.url
  1672. assert req_copy.headers == req.headers
  1673. assert req_copy.headers is not req.headers
  1674. assert req_copy.proxies == req.proxies
  1675. assert req_copy.proxies is not req.proxies
  1676. # Data is not able to be copied
  1677. assert req_copy.data == req.data
  1678. assert req_copy.data is req.data
  1679. # Shallow copy extensions
  1680. assert req_copy.extensions is not req.extensions
  1681. assert req_copy.extensions['cookiejar'] == req.extensions['cookiejar']
  1682. # Subclasses are copied by default
  1683. class AnotherRequest(Request):
  1684. pass
  1685. req = AnotherRequest(url='http://127.0.0.1')
  1686. assert isinstance(req.copy(), AnotherRequest)
  1687. def test_url(self):
  1688. req = Request(url='https://фtest.example.com/ some spaceв?ä=c')
  1689. assert req.url == 'https://xn--test-z6d.example.com/%20some%20space%D0%B2?%C3%A4=c'
  1690. assert Request(url='//example.com').url == 'http://example.com'
  1691. with pytest.raises(TypeError):
  1692. Request(url='https://').url = None
  1693. class TestResponse:
  1694. @pytest.mark.parametrize('reason,status,expected', [
  1695. ('custom', 200, 'custom'),
  1696. (None, 404, 'Not Found'), # fallback status
  1697. ('', 403, 'Forbidden'),
  1698. (None, 999, None),
  1699. ])
  1700. def test_reason(self, reason, status, expected):
  1701. res = Response(io.BytesIO(b''), url='test://', headers={}, status=status, reason=reason)
  1702. assert res.reason == expected
  1703. def test_headers(self):
  1704. headers = Message()
  1705. headers.add_header('Test', 'test')
  1706. headers.add_header('Test', 'test2')
  1707. headers.add_header('content-encoding', 'br')
  1708. res = Response(io.BytesIO(b''), headers=headers, url='test://')
  1709. assert res.headers.get_all('test') == ['test', 'test2']
  1710. assert 'Content-Encoding' in res.headers
  1711. def test_get_header(self):
  1712. headers = Message()
  1713. headers.add_header('Set-Cookie', 'cookie1')
  1714. headers.add_header('Set-cookie', 'cookie2')
  1715. headers.add_header('Test', 'test')
  1716. headers.add_header('Test', 'test2')
  1717. res = Response(io.BytesIO(b''), headers=headers, url='test://')
  1718. assert res.get_header('test') == 'test, test2'
  1719. assert res.get_header('set-Cookie') == 'cookie1'
  1720. assert res.get_header('notexist', 'default') == 'default'
  1721. def test_compat(self):
  1722. res = Response(io.BytesIO(b''), url='test://', status=404, headers={'test': 'test'})
  1723. with warnings.catch_warnings():
  1724. warnings.simplefilter('ignore', category=DeprecationWarning)
  1725. assert res.code == res.getcode() == res.status
  1726. assert res.geturl() == res.url
  1727. assert res.info() is res.headers
  1728. assert res.getheader('test') == res.get_header('test')
  1729. class TestImpersonateTarget:
  1730. @pytest.mark.parametrize('target_str,expected', [
  1731. ('abc', ImpersonateTarget('abc', None, None, None)),
  1732. ('abc-120_esr', ImpersonateTarget('abc', '120_esr', None, None)),
  1733. ('abc-120:xyz', ImpersonateTarget('abc', '120', 'xyz', None)),
  1734. ('abc-120:xyz-5.6', ImpersonateTarget('abc', '120', 'xyz', '5.6')),
  1735. ('abc:xyz', ImpersonateTarget('abc', None, 'xyz', None)),
  1736. ('abc:', ImpersonateTarget('abc', None, None, None)),
  1737. ('abc-120:', ImpersonateTarget('abc', '120', None, None)),
  1738. (':xyz', ImpersonateTarget(None, None, 'xyz', None)),
  1739. (':xyz-6.5', ImpersonateTarget(None, None, 'xyz', '6.5')),
  1740. (':', ImpersonateTarget(None, None, None, None)),
  1741. ('', ImpersonateTarget(None, None, None, None)),
  1742. ])
  1743. def test_target_from_str(self, target_str, expected):
  1744. assert ImpersonateTarget.from_str(target_str) == expected
  1745. @pytest.mark.parametrize('target_str', [
  1746. '-120', ':-12.0', '-12:-12', '-:-',
  1747. '::', 'a-c-d:', 'a-c-d:e-f-g', 'a:b:',
  1748. ])
  1749. def test_target_from_invalid_str(self, target_str):
  1750. with pytest.raises(ValueError):
  1751. ImpersonateTarget.from_str(target_str)
  1752. @pytest.mark.parametrize('target,expected', [
  1753. (ImpersonateTarget('abc', None, None, None), 'abc'),
  1754. (ImpersonateTarget('abc', '120', None, None), 'abc-120'),
  1755. (ImpersonateTarget('abc', '120', 'xyz', None), 'abc-120:xyz'),
  1756. (ImpersonateTarget('abc', '120', 'xyz', '5'), 'abc-120:xyz-5'),
  1757. (ImpersonateTarget('abc', None, 'xyz', None), 'abc:xyz'),
  1758. (ImpersonateTarget('abc', '120', None, None), 'abc-120'),
  1759. (ImpersonateTarget('abc', '120', 'xyz', None), 'abc-120:xyz'),
  1760. (ImpersonateTarget('abc', None, 'xyz'), 'abc:xyz'),
  1761. (ImpersonateTarget(None, None, 'xyz', '6.5'), ':xyz-6.5'),
  1762. (ImpersonateTarget('abc'), 'abc'),
  1763. (ImpersonateTarget(None, None, None, None), ''),
  1764. ])
  1765. def test_str(self, target, expected):
  1766. assert str(target) == expected
  1767. @pytest.mark.parametrize('args', [
  1768. ('abc', None, None, '5'),
  1769. ('abc', '120', None, '5'),
  1770. (None, '120', None, None),
  1771. (None, '120', None, '5'),
  1772. (None, None, None, '5'),
  1773. (None, '120', 'xyz', '5'),
  1774. ])
  1775. def test_invalid_impersonate_target(self, args):
  1776. with pytest.raises(ValueError):
  1777. ImpersonateTarget(*args)
  1778. @pytest.mark.parametrize('target1,target2,is_in,is_eq', [
  1779. (ImpersonateTarget('abc', None, None, None), ImpersonateTarget('abc', None, None, None), True, True),
  1780. (ImpersonateTarget('abc', None, None, None), ImpersonateTarget('abc', '120', None, None), True, False),
  1781. (ImpersonateTarget('abc', None, 'xyz', 'test'), ImpersonateTarget('abc', '120', 'xyz', None), True, False),
  1782. (ImpersonateTarget('abc', '121', 'xyz', 'test'), ImpersonateTarget('abc', '120', 'xyz', 'test'), False, False),
  1783. (ImpersonateTarget('abc'), ImpersonateTarget('abc', '120', 'xyz', 'test'), True, False),
  1784. (ImpersonateTarget('abc', '120', 'xyz', 'test'), ImpersonateTarget('abc'), True, False),
  1785. (ImpersonateTarget(), ImpersonateTarget('abc', '120', 'xyz'), True, False),
  1786. (ImpersonateTarget(), ImpersonateTarget(), True, True),
  1787. ])
  1788. def test_impersonate_target_in(self, target1, target2, is_in, is_eq):
  1789. assert (target1 in target2) is is_in
  1790. assert (target1 == target2) is is_eq