code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import http.server
import re
import threading

from test.helper import http_server_port, try_rm
from yt_dlp import YoutubeDL
from yt_dlp.downloader.http import HttpFD
from yt_dlp.utils import encodeFilename

TEST_DIR = os.path.dirname(os.path.abspath(__file__))

TEST_SIZE = 10 * 1024

class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def send_content_range(self, total=None):
        range_header = self.headers.get('Range')
        start = end = None
        if range_header:
            mobj = re.search(r'^bytes=(\d+)-(\d+)', range_header)
            if mobj:
                start = int(mobj.group(1))
                end = int(mobj.group(2))
        valid_range = start is not None and end is not None
        if valid_range:
            content_range = 'bytes %d-%d' % (start, end)
            if total:
                content_range += '/%d' % total
            self.send_header('Content-Range', content_range)
        return (end - start + 1) if valid_range else total

    def serve(self, range=True, content_length=True):
        self.send_response(200)
        self.send_header('Content-Type', 'video/mp4')
        size = TEST_SIZE
        if range:
            size = self.send_content_range(TEST_SIZE)
        if content_length:
            self.send_header('Content-Length', size)
        self.end_headers()
        self.wfile.write(b'#' * size)

    def do_GET(self):
        if self.path == '/regular':
            self.serve()
        elif self.path == '/no-content-length':
            self.serve(content_length=False)
        elif self.path == '/no-range':
            self.serve(range=False)
        elif self.path == '/no-range-no-content-length':
            self.serve(range=False, content_length=False)
        else:
            assert False

class FakeLogger:
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        pass

class TestHttpFD(unittest.TestCase):
    def setUp(self):
        self.httpd = http.server.HTTPServer(
            ('127.0.0.1', 0), HTTPTestRequestHandler)
        self.port = http_server_port(self.httpd)
        self.server_thread = threading.Thread(target=self.httpd.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def download(self, params, ep):
        params['logger'] = FakeLogger()
        ydl = YoutubeDL(params)
        downloader = HttpFD(ydl, params)
        filename = 'testfile.mp4'
        try_rm(encodeFilename(filename))
        self.assertTrue(downloader.real_download(filename, {
            'url': 'http://127.0.0.1:%d/%s' % (self.port, ep),
        }), ep)
        self.assertEqual(os.path.getsize(encodeFilename(filename)), TEST_SIZE, ep)
        try_rm(encodeFilename(filename))

    def download_all(self, params):
        for ep in ('regular', 'no-content-length', 'no-range', 'no-range-no-content-length'):
            self.download(params, ep)

    def test_regular(self):
        self.download_all({})

    def test_chunked(self):
        self.download_all({
            'http_chunk_size': 1000,
        })

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import contextlib
import subprocess

from yt_dlp.utils import Popen

rootDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LAZY_EXTRACTORS = 'yt_dlp/extractor/lazy_extractors.py'

class TestExecution(unittest.TestCase):
    def run_yt_dlp(self, exe=(sys.executable, 'yt_dlp/__main__.py'), opts=('--version', )):
        stdout, stderr, returncode = Popen.run(
            [*exe, '--ignore-config', *opts], cwd=rootDir, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(stderr, file=sys.stderr)
        self.assertEqual(returncode, 0)
        return stdout.strip(), stderr.strip()

    def test_main_exec(self):
        self.run_yt_dlp()

    def test_import(self):
        self.run_yt_dlp(exe=(sys.executable, '-c', 'import yt_dlp'))

    def test_module_exec(self):
        self.run_yt_dlp(exe=(sys.executable, '-m', 'yt_dlp'))

    def test_cmdline_umlauts(self):
        _, stderr = self.run_yt_dlp(opts=('ä', '--version'))
        self.assertFalse(stderr)

    def test_lazy_extractors(self):
        try:
            subprocess.check_call([sys.executable, 'devscripts/make_lazy_extractors.py', LAZY_EXTRACTORS],
                                  cwd=rootDir, stdout=subprocess.DEVNULL)
            self.assertTrue(os.path.exists(LAZY_EXTRACTORS))

            _, stderr = self.run_yt_dlp(opts=('-s', 'test:'))
            self.assertFalse(stderr)

            subprocess.check_call([sys.executable, 'test/test_all_urls.py'], cwd=rootDir, stdout=subprocess.DEVNULL)
        finally:
            with contextlib.suppress(OSError):
                os.remove(LAZY_EXTRACTORS)

if __name__ == '__main__':
    unittest.main()

repo_name: Lesmiscore/ytdl


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import http.server
import ssl
import threading
import urllib.request

from test.helper import http_server_port
from yt_dlp import YoutubeDL

TEST_DIR = os.path.dirname(os.path.abspath(__file__))

class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def do_GET(self):
        if self.path == '/video.html':
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(b'<video src="/vid.mp4" />')
        elif self.path == '/vid.mp4':
            self.send_response(200)
            self.send_header('Content-Type', 'video/mp4')
            self.end_headers()
            self.wfile.write(b'\x00\x00\x00\x00\x20\x66\x74[video]')
        elif self.path == '/%E4%B8%AD%E6%96%87.html':
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(b'<video src="/vid.mp4" />')
        else:
            assert False

class FakeLogger:
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        pass

class TestHTTP(unittest.TestCase):
    def setUp(self):
        self.httpd = http.server.HTTPServer(
            ('127.0.0.1', 0), HTTPTestRequestHandler)
        self.port = http_server_port(self.httpd)
        self.server_thread = threading.Thread(target=self.httpd.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

class TestHTTPS(unittest.TestCase):
    def setUp(self):
        certfn = os.path.join(TEST_DIR, 'testcert.pem')
        self.httpd = http.server.HTTPServer(
            ('127.0.0.1', 0), HTTPTestRequestHandler)
        sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        sslctx.load_cert_chain(certfn, None)
        self.httpd.socket = sslctx.wrap_socket(self.httpd.socket, server_side=True)
        self.port = http_server_port(self.httpd)
        self.server_thread = threading.Thread(target=self.httpd.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def test_nocheckcertificate(self):
        ydl = YoutubeDL({'logger': FakeLogger()})
        self.assertRaises(
            Exception,
            ydl.extract_info, 'https://127.0.0.1:%d/video.html' % self.port)

        ydl = YoutubeDL({'logger': FakeLogger(), 'nocheckcertificate': True})
        r = ydl.extract_info('https://127.0.0.1:%d/video.html' % self.port)
        self.assertEqual(r['url'], 'https://127.0.0.1:%d/vid.mp4' % self.port)

class TestClientCert(unittest.TestCase):
    def setUp(self):
        certfn = os.path.join(TEST_DIR, 'testcert.pem')
        self.certdir = os.path.join(TEST_DIR, 'testdata', 'certificate')
        cacertfn = os.path.join(self.certdir, 'ca.crt')
        self.httpd = http.server.HTTPServer(('127.0.0.1', 0), HTTPTestRequestHandler)
        sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        sslctx.verify_mode = ssl.CERT_REQUIRED
        sslctx.load_verify_locations(cafile=cacertfn)
        sslctx.load_cert_chain(certfn, None)
        self.httpd.socket = sslctx.wrap_socket(self.httpd.socket, server_side=True)
        self.port = http_server_port(self.httpd)
        self.server_thread = threading.Thread(target=self.httpd.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def _run_test(self, **params):
        ydl = YoutubeDL({
            'logger': FakeLogger(),
            # Disable client-side validation of unacceptable self-signed testcert.pem
            # The test is of a check on the server side, so unaffected
            'nocheckcertificate': True,
            **params,
        })
        r = ydl.extract_info('https://127.0.0.1:%d/video.html' % self.port)
        self.assertEqual(r['url'], 'https://127.0.0.1:%d/vid.mp4' % self.port)

    def test_certificate_combined_nopass(self):
        self._run_test(client_certificate=os.path.join(self.certdir, 'clientwithkey.crt'))

    def test_certificate_nocombined_nopass(self):
        self._run_test(client_certificate=os.path.join(self.certdir, 'client.crt'),
                       client_certificate_key=os.path.join(self.certdir, 'client.key'))

    def test_certificate_combined_pass(self):
        self._run_test(client_certificate=os.path.join(self.certdir, 'clientwithencryptedkey.crt'),
                       client_certificate_password='foobar')

    def test_certificate_nocombined_pass(self):
        self._run_test(client_certificate=os.path.join(self.certdir, 'client.crt'),
                       client_certificate_key=os.path.join(self.certdir, 'clientencrypted.key'),
                       client_certificate_password='foobar')

def _build_proxy_handler(name):
    class HTTPTestRequestHandler(http.server.BaseHTTPRequestHandler):
        proxy_name = name

        def log_message(self, format, *args):
            pass

        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
            self.end_headers()
            self.wfile.write(f'{self.proxy_name}: {self.path}'.encode())
    return HTTPTestRequestHandler

class TestProxy(unittest.TestCase):
    def setUp(self):
        self.proxy = http.server.HTTPServer(
            ('127.0.0.1', 0), _build_proxy_handler('normal'))
        self.port = http_server_port(self.proxy)
        self.proxy_thread = threading.Thread(target=self.proxy.serve_forever)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()

        self.geo_proxy = http.server.HTTPServer(
            ('127.0.0.1', 0), _build_proxy_handler('geo'))
        self.geo_port = http_server_port(self.geo_proxy)
        self.geo_proxy_thread = threading.Thread(target=self.geo_proxy.serve_forever)
        self.geo_proxy_thread.daemon = True
        self.geo_proxy_thread.start()

    def test_proxy(self):
        geo_proxy = f'127.0.0.1:{self.geo_port}'
        ydl = YoutubeDL({
            'proxy': f'127.0.0.1:{self.port}',
            'geo_verification_proxy': geo_proxy,
        })
        url = 'http://foo.com/bar'
        response = ydl.urlopen(url).read().decode()
        self.assertEqual(response, f'normal: {url}')

        req = urllib.request.Request(url)
        req.add_header('Ytdl-request-proxy', geo_proxy)
        response = ydl.urlopen(req).read().decode()
        self.assertEqual(response, f'geo: {url}')

    def test_proxy_with_idn(self):
        ydl = YoutubeDL({
            'proxy': f'127.0.0.1:{self.port}',
        })
        url = 'http://中文.tw/'
        response = ydl.urlopen(url).read().decode()
        # b'xn--fiq228c' is '中文'.encode('idna')
        self.assertEqual(response, 'normal: http://xn--fiq228c.tw/')

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from test.helper import FakeYDL, is_download_test
from yt_dlp.extractor import IqiyiIE

class WarningLogger:
    def __init__(self):
        self.messages = []

    def warning(self, msg):
        self.messages.append(msg)

    def debug(self, msg):
        pass

    def error(self, msg):
        pass

@is_download_test
class TestIqiyiSDKInterpreter(unittest.TestCase):
    def test_iqiyi_sdk_interpreter(self):
        '''
        Test the functionality of IqiyiSDKInterpreter by trying to log in

        If `sign` is incorrect, /validate call throws an HTTP 556 error
        '''
        logger = WarningLogger()
        ie = IqiyiIE(FakeYDL({'logger': logger}))
        ie._perform_login('foo', 'bar')
        self.assertTrue('unable to log in:' in logger.messages[0])

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import math
import re

from yt_dlp.jsinterp import JS_Undefined, JSInterpreter

class TestJSInterpreter(unittest.TestCase):
    def test_basic(self):
        jsi = JSInterpreter('function x(){;}')
        self.assertEqual(jsi.call_function('x'), None)

        jsi = JSInterpreter('function x3(){return 42;}')
        self.assertEqual(jsi.call_function('x3'), 42)

        jsi = JSInterpreter('function x3(){42}')
        self.assertEqual(jsi.call_function('x3'), None)

        jsi = JSInterpreter('var x5 = function(){return 42;}')
        self.assertEqual(jsi.call_function('x5'), 42)

    def test_calc(self):
        jsi = JSInterpreter('function x4(a){return 2*a+1;}')
        self.assertEqual(jsi.call_function('x4', 3), 7)

    def test_empty_return(self):
        jsi = JSInterpreter('function f(){return; y()}')
        self.assertEqual(jsi.call_function('f'), None)

    def test_morespace(self):
        jsi = JSInterpreter('function x (a) { return 2 * a + 1 ; }')
        self.assertEqual(jsi.call_function('x', 3), 7)

        jsi = JSInterpreter('function f () { x =  2  ; return x; }')
        self.assertEqual(jsi.call_function('f'), 2)

    def test_strange_chars(self):
        jsi = JSInterpreter('function $_xY1 ($_axY1) { var $_axY2 = $_axY1 + 1; return $_axY2; }')
        self.assertEqual(jsi.call_function('$_xY1', 20), 21)

    def test_operators(self):
        jsi = JSInterpreter('function f(){return 1 << 5;}')
        self.assertEqual(jsi.call_function('f'), 32)

        jsi = JSInterpreter('function f(){return 2 ** 5}')
        self.assertEqual(jsi.call_function('f'), 32)

        jsi = JSInterpreter('function f(){return 19 & 21;}')
        self.assertEqual(jsi.call_function('f'), 17)

        jsi = JSInterpreter('function f(){return 11 >> 2;}')
        self.assertEqual(jsi.call_function('f'), 2)

        jsi = JSInterpreter('function f(){return []? 2+3: 4;}')
        self.assertEqual(jsi.call_function('f'), 5)

        jsi = JSInterpreter('function f(){return 1 == 2}')
        self.assertEqual(jsi.call_function('f'), False)

        jsi = JSInterpreter('function f(){return 0 && 1 || 2;}')
        self.assertEqual(jsi.call_function('f'), 2)

        jsi = JSInterpreter('function f(){return 0 ?? 42;}')
        self.assertEqual(jsi.call_function('f'), 0)

        jsi = JSInterpreter('function f(){return "life, the universe and everything" < 42;}')
        self.assertFalse(jsi.call_function('f'))

    def test_array_access(self):
        jsi = JSInterpreter('function f(){var x = [1,2,3]; x[0] = 4; x[0] = 5; x[2.0] = 7; return x;}')
        self.assertEqual(jsi.call_function('f'), [5, 2, 7])

    def test_parens(self):
        jsi = JSInterpreter('function f(){return (1) + (2) * ((( (( (((((3)))))) )) ));}')
        self.assertEqual(jsi.call_function('f'), 7)

        jsi = JSInterpreter('function f(){return (1 + 2) * 3;}')
        self.assertEqual(jsi.call_function('f'), 9)

    def test_quotes(self):
        jsi = JSInterpreter(R'function f(){return "a\"\\("}')
        self.assertEqual(jsi.call_function('f'), R'a"\(')

    def test_assignments(self):
        jsi = JSInterpreter('function f(){var x = 20; x = 30 + 1; return x;}')
        self.assertEqual(jsi.call_function('f'), 31)

        jsi = JSInterpreter('function f(){var x = 20; x += 30 + 1; return x;}')
        self.assertEqual(jsi.call_function('f'), 51)

        jsi = JSInterpreter('function f(){var x = 20; x -= 30 + 1; return x;}')
        self.assertEqual(jsi.call_function('f'), -11)

    def test_comments(self):
        'Skipping: Not yet fully implemented'
        return
        jsi = JSInterpreter('''
        function x() {
            var x = /* 1 + */ 2;
            var y = /* 30
            * 40 */ 50;
            return x + y;
        }
        ''')
        self.assertEqual(jsi.call_function('x'), 52)

        jsi = JSInterpreter('''
        function f() {
            var x = "/*";
            var y = 1 /* comment */ + 2;
            return y;
        }
        ''')
        self.assertEqual(jsi.call_function('f'), 3)

    def test_precedence(self):
        jsi = JSInterpreter('''
        function x() {
            var a = [10, 20, 30, 40, 50];
            var b = 6;
            a[0]=a[b%a.length];
            return a;
        }''')
        self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50])

    def test_builtins(self):
        jsi = JSInterpreter('''
        function x() { return NaN }
        ''')
        self.assertTrue(math.isnan(jsi.call_function('x')))

        jsi = JSInterpreter('''
        function x() { return new Date('Wednesday 31 December 1969 18:01:26 MDT') - 0; }
        ''')
        self.assertEqual(jsi.call_function('x'), 86000)
        jsi = JSInterpreter('''
        function x(dt) { return new Date(dt) - 0; }
        ''')
        self.assertEqual(jsi.call_function('x', 'Wednesday 31 December 1969 18:01:26 MDT'), 86000)

    def test_call(self):
        jsi = JSInterpreter('''
        function x() { return 2; }
        function y(a) { return x() + (a?a:0); }
        function z() { return y(3); }
        ''')
        self.assertEqual(jsi.call_function('z'), 5)
        self.assertEqual(jsi.call_function('y'), 2)

    def test_for_loop(self):
        jsi = JSInterpreter('''
        function x() { a=0; for (i=0; i-10; i++) {a++} return a }
        ''')
        self.assertEqual(jsi.call_function('x'), 10)

    def test_switch(self):
        jsi = JSInterpreter('''
        function x(f) { switch(f){
            case 1:f+=1;
            case 2:f+=2;
            case 3:f+=3;break;
            case 4:f+=4;
            default:f=0;
        } return f }
        ''')
        self.assertEqual(jsi.call_function('x', 1), 7)
        self.assertEqual(jsi.call_function('x', 3), 6)
        self.assertEqual(jsi.call_function('x', 5), 0)

    def test_switch_default(self):
        jsi = JSInterpreter('''
        function x(f) { switch(f){
            case 2: f+=2;
            default: f-=1;
            case 5:
            case 6: f+=6;
            case 0: break;
            case 1: f+=1;
        } return f }
        ''')
        self.assertEqual(jsi.call_function('x', 1), 2)
        self.assertEqual(jsi.call_function('x', 5), 11)
        self.assertEqual(jsi.call_function('x', 9), 14)

    def test_try(self):
        jsi = JSInterpreter('''
        function x() { try{return 10} catch(e){return 5} }
        ''')
        self.assertEqual(jsi.call_function('x'), 10)

    def test_catch(self):
        jsi = JSInterpreter('''
        function x() { try{throw 10} catch(e){return 5} }
        ''')
        self.assertEqual(jsi.call_function('x'), 5)

    def test_finally(self):
        jsi = JSInterpreter('''
        function x() { try{throw 10} finally {return 42} }
        ''')
        self.assertEqual(jsi.call_function('x'), 42)
        jsi = JSInterpreter('''
        function x() { try{throw 10} catch(e){return 5} finally {return 42} }
        ''')
        self.assertEqual(jsi.call_function('x'), 42)

    def test_nested_try(self):
        jsi = JSInterpreter('''
        function x() {try {
            try{throw 10} finally {throw 42}
            } catch(e){return 5} }
        ''')
        self.assertEqual(jsi.call_function('x'), 5)

    def test_for_loop_continue(self):
        jsi = JSInterpreter('''
        function x() { a=0; for (i=0; i-10; i++) { continue; a++ } return a }
        ''')
        self.assertEqual(jsi.call_function('x'), 0)

    def test_for_loop_break(self):
        jsi = JSInterpreter('''
        function x() { a=0; for (i=0; i-10; i++) { break; a++ } return a }
        ''')
        self.assertEqual(jsi.call_function('x'), 0)

    def test_for_loop_try(self):
        jsi = JSInterpreter('''
        function x() {
            for (i=0; i-10; i++) { try { if (i == 5) throw i} catch {return 10} finally {break} };
            return 42 }
        ''')
        self.assertEqual(jsi.call_function('x'), 42)

    def test_literal_list(self):
        jsi = JSInterpreter('''
        function x() { return [1, 2, "asdf", [5, 6, 7]][3] }
        ''')
        self.assertEqual(jsi.call_function('x'), [5, 6, 7])

    def test_comma(self):
        jsi = JSInterpreter('''
        function x() { a=5; a -= 1, a+=3; return a }
        ''')
        self.assertEqual(jsi.call_function('x'), 7)

        jsi = JSInterpreter('''
        function x() { a=5; return (a -= 1, a+=3, a); }
        ''')
        self.assertEqual(jsi.call_function('x'), 7)

        jsi = JSInterpreter('''
        function x() { return (l=[0,1,2,3], function(a, b){return a+b})((l[1], l[2]), l[3]) }
        ''')
        self.assertEqual(jsi.call_function('x'), 5)

    def test_void(self):
        jsi = JSInterpreter('''
        function x() { return void 42; }
        ''')
        self.assertEqual(jsi.call_function('x'), None)

    def test_return_function(self):
        jsi = JSInterpreter('''
        function x() { return [1, function(){return 1}][1] }
        ''')
        self.assertEqual(jsi.call_function('x')([]), 1)

    def test_null(self):
        jsi = JSInterpreter('''
        function x() { return null; }
        ''')
        self.assertEqual(jsi.call_function('x'), None)

        jsi = JSInterpreter('''
        function x() { return [null > 0, null < 0, null == 0, null === 0]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, False, False, False])

        jsi = JSInterpreter('''
        function x() { return [null >= 0, null <= 0]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [True, True])

    def test_undefined(self):
        jsi = JSInterpreter('''
        function x() { return undefined === undefined; }
        ''')
        self.assertEqual(jsi.call_function('x'), True)

        jsi = JSInterpreter('''
        function x() { return undefined; }
        ''')
        self.assertEqual(jsi.call_function('x'), JS_Undefined)

        jsi = JSInterpreter('''
        function x() { let v; return v; }
        ''')
        self.assertEqual(jsi.call_function('x'), JS_Undefined)

        jsi = JSInterpreter('''
        function x() { return [undefined === undefined, undefined == undefined, undefined < undefined, undefined > undefined]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [True, True, False, False])

        jsi = JSInterpreter('''
        function x() { return [undefined === 0, undefined == 0, undefined < 0, undefined > 0]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, False, False, False])

        jsi = JSInterpreter('''
        function x() { return [undefined >= 0, undefined <= 0]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, False])

        jsi = JSInterpreter('''
        function x() { return [undefined > null, undefined < null, undefined == null, undefined === null]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, False, True, False])

        jsi = JSInterpreter('''
        function x() { return [undefined === null, undefined == null, undefined < null, undefined > null]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, True, False, False])

        jsi = JSInterpreter('''
        function x() { let v; return [42+v, v+42, v**42, 42**v, 0**v]; }
        ''')
        for y in jsi.call_function('x'):
            self.assertTrue(math.isnan(y))

        jsi = JSInterpreter('''
        function x() { let v; return v**0; }
        ''')
        self.assertEqual(jsi.call_function('x'), 1)

        jsi = JSInterpreter('''
        function x() { let v; return [v>42, v<=42, v&&42, 42&&v]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [False, False, JS_Undefined, JS_Undefined])

        jsi = JSInterpreter('function x(){return undefined ?? 42; }')
        self.assertEqual(jsi.call_function('x'), 42)

    def test_object(self):
        jsi = JSInterpreter('''
        function x() { return {}; }
        ''')
        self.assertEqual(jsi.call_function('x'), {})

        jsi = JSInterpreter('''
        function x() { let a = {m1: 42, m2: 0 }; return [a["m1"], a.m2]; }
        ''')
        self.assertEqual(jsi.call_function('x'), [42, 0])

        jsi = JSInterpreter('''
        function x() { let a; return a?.qq; }
        ''')
        self.assertEqual(jsi.call_function('x'), JS_Undefined)

        jsi = JSInterpreter('''
        function x() { let a = {m1: 42, m2: 0 }; return a?.qq; }
        ''')
        self.assertEqual(jsi.call_function('x'), JS_Undefined)

    def test_regex(self):
        jsi = JSInterpreter('''
        function x() { let a=/,,[/,913,/](,)}/; }
        ''')
        self.assertEqual(jsi.call_function('x'), None)

        jsi = JSInterpreter('''
        function x() { let a=/,,[/,913,/](,)}/; return a; }
        ''')
        self.assertIsInstance(jsi.call_function('x'), re.Pattern)

        jsi = JSInterpreter('''
        function x() { let a=/,,[/,913,/](,)}/i; return a; }
        ''')
        self.assertEqual(jsi.call_function('x').flags & re.I, re.I)

        jsi = JSInterpreter(R'''
        function x() { let a=/,][}",],()}(\[)/; return a; }
        ''')
        self.assertEqual(jsi.call_function('x').pattern, r',][}",],()}(\[)')

    def test_char_code_at(self):
        jsi = JSInterpreter('function x(i){return "test".charCodeAt(i)}')
        self.assertEqual(jsi.call_function('x', 0), 116)
        self.assertEqual(jsi.call_function('x', 1), 101)
        self.assertEqual(jsi.call_function('x', 2), 115)
        self.assertEqual(jsi.call_function('x', 3), 116)
        self.assertEqual(jsi.call_function('x', 4), None)
        self.assertEqual(jsi.call_function('x', 'not_a_number'), 116)

    def test_bitwise_operators_overflow(self):
        jsi = JSInterpreter('function x(){return -524999584 << 5}')
        self.assertEqual(jsi.call_function('x'), 379882496)

        jsi = JSInterpreter('function x(){return 1236566549 << 5}')
        self.assertEqual(jsi.call_function('x'), 915423904)

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python

# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from yt_dlp.longname import (
    split_longname_str,
    combine_longname_str,
)

# TODO: add downloader testcase for "-fw_4mVz-44"
# くれぐれも体調に気をつケテ😳✋🤑（￣▽￣）YouTubeちゃん😆😃☀ ❗😚元気、ないのかなァ😭😓(T_T)💦大丈夫❓（￣ー￣?）😜⁉🤔くれぐれも体調に気をつケテ😳✋🤑（￣▽￣）YouTubeちゃん😆
class TestLongName(unittest.TestCase):

    def test_split_utf8(self):
        self.assertEqual(
            split_longname_str('spade', 'utf8'),
            'spade'
        )
        self.assertEqual(
            split_longname_str('【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f137.mp4.part', 'utf8'),
            '【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f13~~/7.mp4.part'
        )

    def test_combine_utf8(self):
        self.assertEqual(
            combine_longname_str('spade'),
            'spade'
        )
        self.assertEqual(
            combine_longname_str('【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f13~~/7.mp4.part'),
            '【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f137.mp4.part'
        )

    def test_split_sjis(self):
        # In SJIS, it is in 255 bytes (!!)
        self.assertEqual(
            split_longname_str('【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f137.mp4.part', 'sjis'),
            '【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f137.mp4.part'
        )

    def test_resplit_identical(self):
        instr = '【妖怪ウォッチアニメ】第１３話「 コマさん 〜はじめてのファストフード編〜（#5）」「妖怪 口だけおんな」  「妖怪 ダンサーズ☆」「 じんめん犬シーズン2 犬脱走 Episode 2」-cL46Bl96_GQ.f13~~/7.mp4.part'
        self.assertEqual(split_longname_str(instr, 'utf8'), instr)


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from yt_dlp.extractor import gen_extractor_classes
from yt_dlp.extractor.common import InfoExtractor

NO_LOGIN = InfoExtractor._perform_login

class TestNetRc(unittest.TestCase):
    def test_netrc_present(self):
        for ie in gen_extractor_classes():
            if ie._perform_login is NO_LOGIN:
                continue
            self.assertTrue(
                ie._NETRC_MACHINE,
                'Extractor %s supports login, but is missing a _NETRC_MACHINE property' % ie.IE_NAME)

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import subprocess

from test.helper import is_download_test, try_rm

root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
download_file = os.path.join(root_dir, 'test.mkv')

@is_download_test
class TestOverwrites(unittest.TestCase):
    def setUp(self):
        # create an empty file
        open(download_file, 'a').close()

    def test_default_overwrites(self):
        outp = subprocess.Popen(
            [
                sys.executable, 'yt_dlp/__main__.py',
                '-o', 'test.mkv',
                'https://www.youtube.com/watch?v=jNQXAC9IVRw'
            ], cwd=root_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        sout, serr = outp.communicate()
        self.assertTrue(b'has already been downloaded' in sout)
        # if the file has no content, it has not been redownloaded
        self.assertTrue(os.path.getsize(download_file) < 1)

    def test_yes_overwrites(self):
        outp = subprocess.Popen(
            [
                sys.executable, 'yt_dlp/__main__.py', '--yes-overwrites',
                '-o', 'test.mkv',
                'https://www.youtube.com/watch?v=jNQXAC9IVRw'
            ], cwd=root_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        sout, serr = outp.communicate()
        self.assertTrue(b'has already been downloaded' not in sout)
        # if the file has no content, it has not been redownloaded
        self.assertTrue(os.path.getsize(download_file) > 1)

    def tearDown(self):
        try_rm(os.path.join(root_dir, 'test.mkv'))

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from test.helper import get_params, is_download_test, try_rm
import yt_dlp.YoutubeDL  # isort: split
from yt_dlp.utils import DownloadError

class YoutubeDL(yt_dlp.YoutubeDL):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.to_stderr = self.to_screen

TEST_ID = 'gr51aVj-mLg'
EXPECTED_NAME = 'gr51aVj-mLg'

@is_download_test
class TestPostHooks(unittest.TestCase):
    def setUp(self):
        self.stored_name_1 = None
        self.stored_name_2 = None
        self.params = get_params({
            'skip_download': False,
            'writeinfojson': False,
            'quiet': True,
            'verbose': False,
            'cachedir': False,
        })
        self.files = []

    def test_post_hooks(self):
        self.params['post_hooks'] = [self.hook_one, self.hook_two]
        ydl = YoutubeDL(self.params)
        ydl.download([TEST_ID])
        self.assertEqual(self.stored_name_1, EXPECTED_NAME, 'Not the expected name from hook 1')
        self.assertEqual(self.stored_name_2, EXPECTED_NAME, 'Not the expected name from hook 2')

    def test_post_hook_exception(self):
        self.params['post_hooks'] = [self.hook_three]
        ydl = YoutubeDL(self.params)
        self.assertRaises(DownloadError, ydl.download, [TEST_ID])

    def hook_one(self, filename):
        self.stored_name_1, _ = os.path.splitext(os.path.basename(filename))
        self.files.append(filename)

    def hook_two(self, filename):
        self.stored_name_2, _ = os.path.splitext(os.path.basename(filename))
        self.files.append(filename)

    def hook_three(self, filename):
        self.files.append(filename)
        raise Exception('Test exception for \'%s\'' % filename)

    def tearDown(self):
        for f in self.files:
            try_rm(f)

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from yt_dlp import YoutubeDL
from yt_dlp.compat import compat_shlex_quote
from yt_dlp.postprocessor import (
    ExecPP,
    FFmpegThumbnailsConvertorPP,
    MetadataFromFieldPP,
    MetadataParserPP,
    ModifyChaptersPP,
)

class TestMetadataFromField(unittest.TestCase):

    def test_format_to_regex(self):
        self.assertEqual(
            MetadataParserPP.format_to_regex('%(title)s - %(artist)s'),
            r'(?P<title>.+)\ \-\ (?P<artist>.+)')
        self.assertEqual(MetadataParserPP.format_to_regex(r'(?P<x>.+)'), r'(?P<x>.+)')

    def test_field_to_template(self):
        self.assertEqual(MetadataParserPP.field_to_template('title'), '%(title)s')
        self.assertEqual(MetadataParserPP.field_to_template('1'), '1')
        self.assertEqual(MetadataParserPP.field_to_template('foo bar'), 'foo bar')
        self.assertEqual(MetadataParserPP.field_to_template(' literal'), ' literal')

    def test_metadatafromfield(self):
        self.assertEqual(
            MetadataFromFieldPP.to_action('%(title)s \\: %(artist)s:%(title)s : %(artist)s'),
            (MetadataParserPP.Actions.INTERPRET, '%(title)s : %(artist)s', '%(title)s : %(artist)s'))

class TestConvertThumbnail(unittest.TestCase):
    def test_escaping(self):
        pp = FFmpegThumbnailsConvertorPP(YoutubeDL())
        if not pp.available:
            print('Skipping: ffmpeg not found')
            return

        file = 'test/testdata/thumbnails/foo %d bar/foo_%d.{}'
        tests = (('webp', 'png'), ('png', 'jpg'))

        for inp, out in tests:
            out_file = file.format(out)
            if os.path.exists(out_file):
                os.remove(out_file)
            pp.convert_thumbnail(file.format(inp), out)
            assert os.path.exists(out_file)

        for _, out in tests:
            os.remove(file.format(out))

class TestExec(unittest.TestCase):
    def test_parse_cmd(self):
        pp = ExecPP(YoutubeDL(), '')
        info = {'filepath': 'file name'}
        cmd = 'echo %s' % compat_shlex_quote(info['filepath'])

        self.assertEqual(pp.parse_cmd('echo', info), cmd)
        self.assertEqual(pp.parse_cmd('echo {}', info), cmd)
        self.assertEqual(pp.parse_cmd('echo %(filepath)q', info), cmd)

class TestModifyChaptersPP(unittest.TestCase):
    def setUp(self):
        self._pp = ModifyChaptersPP(YoutubeDL())

    @staticmethod
    def _sponsor_chapter(start, end, cat, remove=False):
        c = {'start_time': start, 'end_time': end, '_categories': [(cat, start, end)]}
        if remove:
            c['remove'] = True
        return c

    @staticmethod
    def _chapter(start, end, title=None, remove=False):
        c = {'start_time': start, 'end_time': end}
        if title is not None:
            c['title'] = title
        if remove:
            c['remove'] = True
        return c

    def _chapters(self, ends, titles):
        self.assertEqual(len(ends), len(titles))
        start = 0
        chapters = []
        for e, t in zip(ends, titles):
            chapters.append(self._chapter(start, e, t))
            start = e
        return chapters

    def _remove_marked_arrange_sponsors_test_impl(
            self, chapters, expected_chapters, expected_removed):
        actual_chapters, actual_removed = (
            self._pp._remove_marked_arrange_sponsors(chapters))
        for c in actual_removed:
            c.pop('title', None)
            c.pop('_categories', None)
        actual_chapters = [{
            'start_time': c['start_time'],
            'end_time': c['end_time'],
            'title': c['title'],
        } for c in actual_chapters]
        self.assertSequenceEqual(expected_chapters, actual_chapters)
        self.assertSequenceEqual(expected_removed, actual_removed)

    def test_remove_marked_arrange_sponsors_CanGetThroughUnaltered(self):
        chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, chapters, [])

    def test_remove_marked_arrange_sponsors_ChapterWithSponsors(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 20, 'sponsor'),
            self._sponsor_chapter(30, 40, 'preview'),
            self._sponsor_chapter(50, 60, 'filler')]
        expected = self._chapters(
            [10, 20, 30, 40, 50, 60, 70],
            ['c', '[SponsorBlock]: Sponsor', 'c', '[SponsorBlock]: Preview/Recap',
             'c', '[SponsorBlock]: Filler Tangent', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_UniqueNamesForOverlappingSponsors(self):
        chapters = self._chapters([120], ['c']) + [
            self._sponsor_chapter(10, 45, 'sponsor'), self._sponsor_chapter(20, 40, 'selfpromo'),
            self._sponsor_chapter(50, 70, 'sponsor'), self._sponsor_chapter(60, 85, 'selfpromo'),
            self._sponsor_chapter(90, 120, 'selfpromo'), self._sponsor_chapter(100, 110, 'sponsor')]
        expected = self._chapters(
            [10, 20, 40, 45, 50, 60, 70, 85, 90, 100, 110, 120],
            ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
             '[SponsorBlock]: Sponsor',
             'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
             '[SponsorBlock]: Unpaid/Self Promotion',
             'c', '[SponsorBlock]: Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion, Sponsor',
             '[SponsorBlock]: Unpaid/Self Promotion'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_ChapterWithCuts(self):
        cuts = [self._chapter(10, 20, remove=True),
                self._sponsor_chapter(30, 40, 'sponsor', remove=True),
                self._chapter(50, 60, remove=True)]
        chapters = self._chapters([70], ['c']) + cuts
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([40], ['c']), cuts)

    def test_remove_marked_arrange_sponsors_ChapterWithSponsorsAndCuts(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 20, 'sponsor'),
            self._sponsor_chapter(30, 40, 'selfpromo', remove=True),
            self._sponsor_chapter(50, 60, 'interaction')]
        expected = self._chapters([10, 20, 40, 50, 60],
                                  ['c', '[SponsorBlock]: Sponsor', 'c',
                                   '[SponsorBlock]: Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, expected, [self._chapter(30, 40, remove=True)])

    def test_remove_marked_arrange_sponsors_ChapterWithSponsorCutInTheMiddle(self):
        cuts = [self._sponsor_chapter(20, 30, 'selfpromo', remove=True),
                self._chapter(40, 50, remove=True)]
        chapters = self._chapters([70], ['c']) + [self._sponsor_chapter(10, 60, 'sponsor')] + cuts
        expected = self._chapters(
            [10, 40, 50], ['c', '[SponsorBlock]: Sponsor', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_ChapterWithCutHidingSponsor(self):
        cuts = [self._sponsor_chapter(20, 50, 'selpromo', remove=True)]
        chapters = self._chapters([60], ['c']) + [
            self._sponsor_chapter(10, 20, 'intro'),
            self._sponsor_chapter(30, 40, 'sponsor'),
            self._sponsor_chapter(50, 60, 'outro'),
        ] + cuts
        expected = self._chapters(
            [10, 20, 30], ['c', '[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_ChapterWithAdjacentSponsors(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 20, 'sponsor'),
            self._sponsor_chapter(20, 30, 'selfpromo'),
            self._sponsor_chapter(30, 40, 'interaction')]
        expected = self._chapters(
            [10, 20, 30, 40, 70],
            ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion',
             '[SponsorBlock]: Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_ChapterWithAdjacentCuts(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 20, 'sponsor'),
            self._sponsor_chapter(20, 30, 'interaction', remove=True),
            self._chapter(30, 40, remove=True),
            self._sponsor_chapter(40, 50, 'selpromo', remove=True),
            self._sponsor_chapter(50, 60, 'interaction')]
        expected = self._chapters([10, 20, 30, 40],
                                  ['c', '[SponsorBlock]: Sponsor',
                                   '[SponsorBlock]: Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, expected, [self._chapter(20, 50, remove=True)])

    def test_remove_marked_arrange_sponsors_ChapterWithOverlappingSponsors(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 30, 'sponsor'),
            self._sponsor_chapter(20, 50, 'selfpromo'),
            self._sponsor_chapter(40, 60, 'interaction')]
        expected = self._chapters(
            [10, 20, 30, 40, 50, 60, 70],
            ['c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
             '[SponsorBlock]: Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion, Interaction Reminder',
             '[SponsorBlock]: Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_ChapterWithOverlappingCuts(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 30, 'sponsor', remove=True),
            self._sponsor_chapter(20, 50, 'selfpromo', remove=True),
            self._sponsor_chapter(40, 60, 'interaction', remove=True)]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([20], ['c']), [self._chapter(10, 60, remove=True)])

    def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingSponsors(self):
        chapters = self._chapters([170], ['c']) + [
            self._sponsor_chapter(0, 30, 'intro'),
            self._sponsor_chapter(20, 50, 'sponsor'),
            self._sponsor_chapter(40, 60, 'selfpromo'),
            self._sponsor_chapter(70, 90, 'sponsor'),
            self._sponsor_chapter(80, 100, 'sponsor'),
            self._sponsor_chapter(90, 110, 'sponsor'),
            self._sponsor_chapter(120, 140, 'selfpromo'),
            self._sponsor_chapter(130, 160, 'interaction'),
            self._sponsor_chapter(150, 170, 'outro')]
        expected = self._chapters(
            [20, 30, 40, 50, 60, 70, 110, 120, 130, 140, 150, 160, 170],
            ['[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Intermission/Intro Animation, Sponsor', '[SponsorBlock]: Sponsor',
             '[SponsorBlock]: Sponsor, Unpaid/Self Promotion', '[SponsorBlock]: Unpaid/Self Promotion', 'c',
             '[SponsorBlock]: Sponsor', 'c', '[SponsorBlock]: Unpaid/Self Promotion',
             '[SponsorBlock]: Unpaid/Self Promotion, Interaction Reminder',
             '[SponsorBlock]: Interaction Reminder',
             '[SponsorBlock]: Interaction Reminder, Endcards/Credits', '[SponsorBlock]: Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingCuts(self):
        chapters = self._chapters([170], ['c']) + [
            self._chapter(0, 30, remove=True),
            self._sponsor_chapter(20, 50, 'sponsor', remove=True),
            self._chapter(40, 60, remove=True),
            self._sponsor_chapter(70, 90, 'sponsor', remove=True),
            self._chapter(80, 100, remove=True),
            self._chapter(90, 110, remove=True),
            self._sponsor_chapter(120, 140, 'sponsor', remove=True),
            self._sponsor_chapter(130, 160, 'selfpromo', remove=True),
            self._chapter(150, 170, remove=True)]
        expected_cuts = [self._chapter(0, 60, remove=True),
                         self._chapter(70, 110, remove=True),
                         self._chapter(120, 170, remove=True)]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([20], ['c']), expected_cuts)

    def test_remove_marked_arrange_sponsors_OverlappingSponsorsDifferentTitlesAfterCut(self):
        chapters = self._chapters([60], ['c']) + [
            self._sponsor_chapter(10, 60, 'sponsor'),
            self._sponsor_chapter(10, 40, 'intro'),
            self._sponsor_chapter(30, 50, 'interaction'),
            self._sponsor_chapter(30, 50, 'selfpromo', remove=True),
            self._sponsor_chapter(40, 50, 'interaction'),
            self._sponsor_chapter(50, 60, 'outro')]
        expected = self._chapters(
            [10, 30, 40], ['c', '[SponsorBlock]: Sponsor, Intermission/Intro Animation', '[SponsorBlock]: Sponsor, Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, expected, [self._chapter(30, 50, remove=True)])

    def test_remove_marked_arrange_sponsors_SponsorsNoLongerOverlapAfterCut(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 30, 'sponsor'),
            self._sponsor_chapter(20, 50, 'interaction'),
            self._sponsor_chapter(30, 50, 'selpromo', remove=True),
            self._sponsor_chapter(40, 60, 'sponsor'),
            self._sponsor_chapter(50, 60, 'interaction')]
        expected = self._chapters(
            [10, 20, 40, 50], ['c', '[SponsorBlock]: Sponsor',
                               '[SponsorBlock]: Sponsor, Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, expected, [self._chapter(30, 50, remove=True)])

    def test_remove_marked_arrange_sponsors_SponsorsStillOverlapAfterCut(self):
        chapters = self._chapters([70], ['c']) + [
            self._sponsor_chapter(10, 60, 'sponsor'),
            self._sponsor_chapter(20, 60, 'interaction'),
            self._sponsor_chapter(30, 50, 'selfpromo', remove=True)]
        expected = self._chapters(
            [10, 20, 40, 50], ['c', '[SponsorBlock]: Sponsor',
                               '[SponsorBlock]: Sponsor, Interaction Reminder', 'c'])
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, expected, [self._chapter(30, 50, remove=True)])

    def test_remove_marked_arrange_sponsors_ChapterWithRunsOfOverlappingSponsorsAndCuts(self):
        chapters = self._chapters([200], ['c']) + [
            self._sponsor_chapter(10, 40, 'sponsor'),
            self._sponsor_chapter(10, 30, 'intro'),
            self._chapter(20, 30, remove=True),
            self._sponsor_chapter(30, 40, 'selfpromo'),
            self._sponsor_chapter(50, 70, 'sponsor'),
            self._sponsor_chapter(60, 80, 'interaction'),
            self._chapter(70, 80, remove=True),
            self._sponsor_chapter(70, 90, 'sponsor'),
            self._sponsor_chapter(80, 100, 'interaction'),
            self._sponsor_chapter(120, 170, 'selfpromo'),
            self._sponsor_chapter(130, 180, 'outro'),
            self._chapter(140, 150, remove=True),
            self._chapter(150, 160, remove=True)]
        expected = self._chapters(
            [10, 20, 30, 40, 50, 70, 80, 100, 110, 130, 140, 160],
            ['c', '[SponsorBlock]: Sponsor, Intermission/Intro Animation', '[SponsorBlock]: Sponsor, Unpaid/Self Promotion',
             'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Sponsor, Interaction Reminder',
             '[SponsorBlock]: Interaction Reminder', 'c', '[SponsorBlock]: Unpaid/Self Promotion',
             '[SponsorBlock]: Unpaid/Self Promotion, Endcards/Credits', '[SponsorBlock]: Endcards/Credits', 'c'])
        expected_cuts = [self._chapter(20, 30, remove=True),
                         self._chapter(70, 80, remove=True),
                         self._chapter(140, 160, remove=True)]
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, expected_cuts)

    def test_remove_marked_arrange_sponsors_SponsorOverlapsMultipleChapters(self):
        chapters = (self._chapters([20, 40, 60, 80, 100], ['c1', 'c2', 'c3', 'c4', 'c5'])
                    + [self._sponsor_chapter(10, 90, 'sponsor')])
        expected = self._chapters([10, 90, 100], ['c1', '[SponsorBlock]: Sponsor', 'c5'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutOverlapsMultipleChapters(self):
        cuts = [self._chapter(10, 90, remove=True)]
        chapters = self._chapters([20, 40, 60, 80, 100], ['c1', 'c2', 'c3', 'c4', 'c5']) + cuts
        expected = self._chapters([10, 20], ['c1', 'c5'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorsWithinSomeChaptersAndOverlappingOthers(self):
        chapters = (self._chapters([10, 40, 60, 80], ['c1', 'c2', 'c3', 'c4'])
                    + [self._sponsor_chapter(20, 30, 'sponsor'),
                       self._sponsor_chapter(50, 70, 'selfpromo')])
        expected = self._chapters([10, 20, 30, 40, 50, 70, 80],
                                  ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c2', 'c3',
                                   '[SponsorBlock]: Unpaid/Self Promotion', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutsWithinSomeChaptersAndOverlappingOthers(self):
        cuts = [self._chapter(20, 30, remove=True), self._chapter(50, 70, remove=True)]
        chapters = self._chapters([10, 40, 60, 80], ['c1', 'c2', 'c3', 'c4']) + cuts
        expected = self._chapters([10, 30, 40, 50], ['c1', 'c2', 'c3', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_ChaptersAfterLastSponsor(self):
        chapters = (self._chapters([20, 40, 50, 60], ['c1', 'c2', 'c3', 'c4'])
                    + [self._sponsor_chapter(10, 30, 'music_offtopic')])
        expected = self._chapters(
            [10, 30, 40, 50, 60],
            ['c1', '[SponsorBlock]: Non-Music Section', 'c2', 'c3', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_ChaptersAfterLastCut(self):
        cuts = [self._chapter(10, 30, remove=True)]
        chapters = self._chapters([20, 40, 50, 60], ['c1', 'c2', 'c3', 'c4']) + cuts
        expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorStartsAtChapterStart(self):
        chapters = (self._chapters([10, 20, 40], ['c1', 'c2', 'c3'])
                    + [self._sponsor_chapter(20, 30, 'sponsor')])
        expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c3'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutStartsAtChapterStart(self):
        cuts = [self._chapter(20, 30, remove=True)]
        chapters = self._chapters([10, 20, 40], ['c1', 'c2', 'c3']) + cuts
        expected = self._chapters([10, 20, 30], ['c1', 'c2', 'c3'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorEndsAtChapterEnd(self):
        chapters = (self._chapters([10, 30, 40], ['c1', 'c2', 'c3'])
                    + [self._sponsor_chapter(20, 30, 'sponsor')])
        expected = self._chapters([10, 20, 30, 40], ['c1', 'c2', '[SponsorBlock]: Sponsor', 'c3'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutEndsAtChapterEnd(self):
        cuts = [self._chapter(20, 30, remove=True)]
        chapters = self._chapters([10, 30, 40], ['c1', 'c2', 'c3']) + cuts
        expected = self._chapters([10, 20, 30], ['c1', 'c2', 'c3'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorCoincidesWithChapters(self):
        chapters = (self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
                    + [self._sponsor_chapter(10, 30, 'sponsor')])
        expected = self._chapters([10, 30, 40], ['c1', '[SponsorBlock]: Sponsor', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutCoincidesWithChapters(self):
        cuts = [self._chapter(10, 30, remove=True)]
        chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']) + cuts
        expected = self._chapters([10, 20], ['c1', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorsAtVideoBoundaries(self):
        chapters = (self._chapters([20, 40, 60], ['c1', 'c2', 'c3'])
                    + [self._sponsor_chapter(0, 10, 'intro'), self._sponsor_chapter(50, 60, 'outro')])
        expected = self._chapters(
            [10, 20, 40, 50, 60], ['[SponsorBlock]: Intermission/Intro Animation', 'c1', 'c2', 'c3', '[SponsorBlock]: Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutsAtVideoBoundaries(self):
        cuts = [self._chapter(0, 10, remove=True), self._chapter(50, 60, remove=True)]
        chapters = self._chapters([20, 40, 60], ['c1', 'c2', 'c3']) + cuts
        expected = self._chapters([10, 30, 40], ['c1', 'c2', 'c3'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_SponsorsOverlapChaptersAtVideoBoundaries(self):
        chapters = (self._chapters([10, 40, 50], ['c1', 'c2', 'c3'])
                    + [self._sponsor_chapter(0, 20, 'intro'), self._sponsor_chapter(30, 50, 'outro')])
        expected = self._chapters(
            [20, 30, 50], ['[SponsorBlock]: Intermission/Intro Animation', 'c2', '[SponsorBlock]: Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_CutsOverlapChaptersAtVideoBoundaries(self):
        cuts = [self._chapter(0, 20, remove=True), self._chapter(30, 50, remove=True)]
        chapters = self._chapters([10, 40, 50], ['c1', 'c2', 'c3']) + cuts
        expected = self._chapters([10], ['c2'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, cuts)

    def test_remove_marked_arrange_sponsors_EverythingSponsored(self):
        chapters = (self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4'])
                    + [self._sponsor_chapter(0, 20, 'intro'), self._sponsor_chapter(20, 40, 'outro')])
        expected = self._chapters([20, 40], ['[SponsorBlock]: Intermission/Intro Animation', '[SponsorBlock]: Endcards/Credits'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, expected, [])

    def test_remove_marked_arrange_sponsors_EverythingCut(self):
        cuts = [self._chapter(0, 20, remove=True), self._chapter(20, 40, remove=True)]
        chapters = self._chapters([10, 20, 30, 40], ['c1', 'c2', 'c3', 'c4']) + cuts
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, [], [self._chapter(0, 40, remove=True)])

    def test_remove_marked_arrange_sponsors_TinyChaptersInTheOriginalArePreserved(self):
        chapters = self._chapters([0.1, 0.2, 0.3, 0.4], ['c1', 'c2', 'c3', 'c4'])
        self._remove_marked_arrange_sponsors_test_impl(chapters, chapters, [])

    def test_remove_marked_arrange_sponsors_TinySponsorsAreIgnored(self):
        chapters = [self._sponsor_chapter(0, 0.1, 'intro'), self._chapter(0.1, 0.2, 'c1'),
                    self._sponsor_chapter(0.2, 0.3, 'sponsor'), self._chapter(0.3, 0.4, 'c2'),
                    self._sponsor_chapter(0.4, 0.5, 'outro')]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([0.3, 0.5], ['c1', 'c2']), [])

    def test_remove_marked_arrange_sponsors_TinyChaptersResultingFromCutsAreIgnored(self):
        cuts = [self._chapter(1.5, 2.5, remove=True)]
        chapters = self._chapters([2, 3, 3.5], ['c1', 'c2', 'c3']) + cuts
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([2, 2.5], ['c1', 'c3']), cuts)

    def test_remove_marked_arrange_sponsors_SingleTinyChapterIsPreserved(self):
        cuts = [self._chapter(0.5, 2, remove=True)]
        chapters = self._chapters([2], ['c']) + cuts
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([0.5], ['c']), cuts)

    def test_remove_marked_arrange_sponsors_TinyChapterAtTheStartPrependedToTheNext(self):
        cuts = [self._chapter(0.5, 2, remove=True)]
        chapters = self._chapters([2, 4], ['c1', 'c2']) + cuts
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([2.5], ['c2']), cuts)

    def test_remove_marked_arrange_sponsors_TinyChaptersResultingFromSponsorOverlapAreIgnored(self):
        chapters = self._chapters([1, 3, 4], ['c1', 'c2', 'c3']) + [
            self._sponsor_chapter(1.5, 2.5, 'sponsor')]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([1.5, 2.5, 4], ['c1', '[SponsorBlock]: Sponsor', 'c3']), [])

    def test_remove_marked_arrange_sponsors_TinySponsorsOverlapsAreIgnored(self):
        chapters = self._chapters([2, 3, 5], ['c1', 'c2', 'c3']) + [
            self._sponsor_chapter(1, 3, 'sponsor'),
            self._sponsor_chapter(2.5, 4, 'selfpromo')
        ]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([1, 3, 4, 5], [
                'c1', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion', 'c3']), [])

    def test_remove_marked_arrange_sponsors_TinySponsorsPrependedToTheNextSponsor(self):
        chapters = self._chapters([4], ['c']) + [
            self._sponsor_chapter(1.5, 2, 'sponsor'),
            self._sponsor_chapter(2, 4, 'selfpromo')
        ]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([1.5, 4], ['c', '[SponsorBlock]: Unpaid/Self Promotion']), [])

    def test_remove_marked_arrange_sponsors_SmallestSponsorInTheOverlapGetsNamed(self):
        self._pp._sponsorblock_chapter_title = '[SponsorBlock]: %(name)s'
        chapters = self._chapters([10], ['c']) + [
            self._sponsor_chapter(2, 8, 'sponsor'),
            self._sponsor_chapter(4, 6, 'selfpromo')
        ]
        self._remove_marked_arrange_sponsors_test_impl(
            chapters, self._chapters([2, 4, 6, 8, 10], [
                'c', '[SponsorBlock]: Sponsor', '[SponsorBlock]: Unpaid/Self Promotion',
                '[SponsorBlock]: Sponsor', 'c'
            ]), [])

    def test_make_concat_opts_CommonCase(self):
        sponsor_chapters = [self._chapter(1, 2, 's1'), self._chapter(10, 20, 's2')]
        expected = '''ffconcat version 1.0
file 'file:test'
outpoint 1.000000
file 'file:test'
inpoint 2.000000
outpoint 10.000000
file 'file:test'
inpoint 20.000000
'''
        opts = self._pp._make_concat_opts(sponsor_chapters, 30)
        self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))

    def test_make_concat_opts_NoZeroDurationChunkAtVideoStart(self):
        sponsor_chapters = [self._chapter(0, 1, 's1'), self._chapter(10, 20, 's2')]
        expected = '''ffconcat version 1.0
file 'file:test'
inpoint 1.000000
outpoint 10.000000
file 'file:test'
inpoint 20.000000
'''
        opts = self._pp._make_concat_opts(sponsor_chapters, 30)
        self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))

    def test_make_concat_opts_NoZeroDurationChunkAtVideoEnd(self):
        sponsor_chapters = [self._chapter(1, 2, 's1'), self._chapter(10, 20, 's2')]
        expected = '''ffconcat version 1.0
file 'file:test'
outpoint 1.000000
file 'file:test'
inpoint 2.000000
outpoint 10.000000
'''
        opts = self._pp._make_concat_opts(sponsor_chapters, 20)
        self.assertEqual(expected, ''.join(self._pp._concat_spec(['test'] * len(opts), opts)))

    def test_quote_for_concat_RunsOfQuotes(self):
        self.assertEqual(
            r"'special '\'' '\'\''characters'\'\'\''galore'",
            self._pp._quote_for_ffmpeg("special ' ''characters'''galore"))

    def test_quote_for_concat_QuotesAtStart(self):
        self.assertEqual(
            r"\'\'\''special '\'' characters '\'' galore'",
            self._pp._quote_for_ffmpeg("'''special ' characters ' galore"))

    def test_quote_for_concat_QuotesAtEnd(self):
        self.assertEqual(
            r"'special '\'' characters '\'' galore'\'\'\'",
            self._pp._quote_for_ffmpeg("special ' characters ' galore'''"))


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import random
import subprocess
import urllib.request

from test.helper import FakeYDL, get_params, is_download_test

@is_download_test
class TestMultipleSocks(unittest.TestCase):
    @staticmethod
    def _check_params(attrs):
        params = get_params()
        for attr in attrs:
            if attr not in params:
                print('Missing %s. Skipping.' % attr)
                return
        return params

    def test_proxy_http(self):
        params = self._check_params(['primary_proxy', 'primary_server_ip'])
        if params is None:
            return
        ydl = FakeYDL({
            'proxy': params['primary_proxy']
        })
        self.assertEqual(
            ydl.urlopen('http://yt-dl.org/ip').read().decode(),
            params['primary_server_ip'])

    def test_proxy_https(self):
        params = self._check_params(['primary_proxy', 'primary_server_ip'])
        if params is None:
            return
        ydl = FakeYDL({
            'proxy': params['primary_proxy']
        })
        self.assertEqual(
            ydl.urlopen('https://yt-dl.org/ip').read().decode(),
            params['primary_server_ip'])

    def test_secondary_proxy_http(self):
        params = self._check_params(['secondary_proxy', 'secondary_server_ip'])
        if params is None:
            return
        ydl = FakeYDL()
        req = urllib.request.Request('http://yt-dl.org/ip')
        req.add_header('Ytdl-request-proxy', params['secondary_proxy'])
        self.assertEqual(
            ydl.urlopen(req).read().decode(),
            params['secondary_server_ip'])

    def test_secondary_proxy_https(self):
        params = self._check_params(['secondary_proxy', 'secondary_server_ip'])
        if params is None:
            return
        ydl = FakeYDL()
        req = urllib.request.Request('https://yt-dl.org/ip')
        req.add_header('Ytdl-request-proxy', params['secondary_proxy'])
        self.assertEqual(
            ydl.urlopen(req).read().decode(),
            params['secondary_server_ip'])

@is_download_test
class TestSocks(unittest.TestCase):
    _SKIP_SOCKS_TEST = True

    def setUp(self):
        if self._SKIP_SOCKS_TEST:
            return

        self.port = random.randint(20000, 30000)
        self.server_process = subprocess.Popen([
            'srelay', '-f', '-i', '127.0.0.1:%d' % self.port],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    def tearDown(self):
        if self._SKIP_SOCKS_TEST:
            return

        self.server_process.terminate()
        self.server_process.communicate()

    def _get_ip(self, protocol):
        if self._SKIP_SOCKS_TEST:
            return '127.0.0.1'

        ydl = FakeYDL({
            'proxy': '%s://127.0.0.1:%d' % (protocol, self.port),
        })
        return ydl.urlopen('http://yt-dl.org/ip').read().decode()

    def test_socks4(self):
        self.assertTrue(isinstance(self._get_ip('socks4'), str))

    def test_socks4a(self):
        self.assertTrue(isinstance(self._get_ip('socks4a'), str))

    def test_socks5(self):
        self.assertTrue(isinstance(self._get_ip('socks5'), str))

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from test.helper import FakeYDL, is_download_test, md5
from yt_dlp.extractor import (
    NPOIE,
    NRKTVIE,
    PBSIE,
    CeskaTelevizeIE,
    ComedyCentralIE,
    DailymotionIE,
    DemocracynowIE,
    LyndaIE,
    RaiPlayIE,
    RTVEALaCartaIE,
    TedTalkIE,
    ThePlatformFeedIE,
    ThePlatformIE,
    VikiIE,
    VimeoIE,
    WallaIE,
    YoutubeIE,
)

@is_download_test
class BaseTestSubtitles(unittest.TestCase):
    url = None
    IE = None

    def setUp(self):
        self.DL = FakeYDL()
        self.ie = self.IE()
        self.DL.add_info_extractor(self.ie)
        if not self.IE.working():
            print('Skipping: %s marked as not _WORKING' % self.IE.ie_key())
            self.skipTest('IE marked as not _WORKING')

    def getInfoDict(self):
        info_dict = self.DL.extract_info(self.url, download=False)
        return info_dict

    def getSubtitles(self):
        info_dict = self.getInfoDict()
        subtitles = info_dict['requested_subtitles']
        if not subtitles:
            return subtitles
        for sub_info in subtitles.values():
            if sub_info.get('data') is None:
                uf = self.DL.urlopen(sub_info['url'])
                sub_info['data'] = uf.read().decode()
        return {l: sub_info['data'] for l, sub_info in subtitles.items()}

@is_download_test
class TestYoutubeSubtitles(BaseTestSubtitles):
    # Available subtitles for QRS8MkLhQmM:
    # Language formats
    # ru       vtt, ttml, srv3, srv2, srv1, json3
    # fr       vtt, ttml, srv3, srv2, srv1, json3
    # en       vtt, ttml, srv3, srv2, srv1, json3
    # nl       vtt, ttml, srv3, srv2, srv1, json3
    # de       vtt, ttml, srv3, srv2, srv1, json3
    # ko       vtt, ttml, srv3, srv2, srv1, json3
    # it       vtt, ttml, srv3, srv2, srv1, json3
    # zh-Hant  vtt, ttml, srv3, srv2, srv1, json3
    # hi       vtt, ttml, srv3, srv2, srv1, json3
    # pt-BR    vtt, ttml, srv3, srv2, srv1, json3
    # es-MX    vtt, ttml, srv3, srv2, srv1, json3
    # ja       vtt, ttml, srv3, srv2, srv1, json3
    # pl       vtt, ttml, srv3, srv2, srv1, json3
    url = 'QRS8MkLhQmM'
    IE = YoutubeIE

    def test_youtube_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(len(subtitles.keys()), 13)
        self.assertEqual(md5(subtitles['en']), 'ae1bd34126571a77aabd4d276b28044d')
        self.assertEqual(md5(subtitles['it']), '0e0b667ba68411d88fd1c5f4f4eab2f9')
        for lang in ['fr', 'de']:
            self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)

    def _test_subtitles_format(self, fmt, md5_hash, lang='en'):
        self.DL.params['writesubtitles'] = True
        self.DL.params['subtitlesformat'] = fmt
        subtitles = self.getSubtitles()
        self.assertEqual(md5(subtitles[lang]), md5_hash)

    def test_youtube_subtitles_ttml_format(self):
        self._test_subtitles_format('ttml', 'c97ddf1217390906fa9fbd34901f3da2')

    def test_youtube_subtitles_vtt_format(self):
        self._test_subtitles_format('vtt', 'ae1bd34126571a77aabd4d276b28044d')

    def test_youtube_subtitles_json3_format(self):
        self._test_subtitles_format('json3', '688dd1ce0981683867e7fe6fde2a224b')

    def _test_automatic_captions(self, url, lang):
        self.url = url
        self.DL.params['writeautomaticsub'] = True
        self.DL.params['subtitleslangs'] = [lang]
        subtitles = self.getSubtitles()
        self.assertTrue(subtitles[lang] is not None)

    def test_youtube_automatic_captions(self):
        # Available automatic captions for 8YoUxe5ncPo:
        # Language formats (all in vtt, ttml, srv3, srv2, srv1, json3)
        # gu, zh-Hans, zh-Hant, gd, ga, gl, lb, la, lo, tt, tr,
        # lv, lt, tk, th, tg, te, fil, haw, yi, ceb, yo, de, da,
        # el, eo, en, eu, et, es, ru, rw, ro, bn, be, bg, uk, jv,
        # bs, ja, or, xh, co, ca, cy, cs, ps, pt, pa, vi, pl, hy,
        # hr, ht, hu, hmn, hi, ha, mg, uz, ml, mn, mi, mk, ur,
        # mt, ms, mr, ug, ta, my, af, sw, is, am,
        #                                         *it*, iw, sv, ar,
        # su, zu, az, id, ig, nl, no, ne, ny, fr, ku, fy, fa, fi,
        # ka, kk, sr, sq, ko, kn, km, st, sk, si, so, sn, sm, sl,
        # ky, sd
        # ...
        self._test_automatic_captions('8YoUxe5ncPo', 'it')

    @unittest.skip('Video unavailable')
    def test_youtube_translated_subtitles(self):
        # This video has a subtitles track, which can be translated (#4555)
        self._test_automatic_captions('Ky9eprVWzlI', 'it')

    def test_youtube_nosubtitles(self):
        self.DL.expect_warning('video doesn\'t have subtitles')
        # Available automatic captions for 8YoUxe5ncPo:
        # ...
        # 8YoUxe5ncPo has no subtitles
        self.url = '8YoUxe5ncPo'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertFalse(subtitles)

@is_download_test
class TestDailymotionSubtitles(BaseTestSubtitles):
    url = 'http://www.dailymotion.com/video/xczg00'
    IE = DailymotionIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertTrue(len(subtitles.keys()) >= 6)
        self.assertEqual(md5(subtitles['en']), '976553874490cba125086bbfea3ff76f')
        self.assertEqual(md5(subtitles['fr']), '594564ec7d588942e384e920e5341792')
        for lang in ['es', 'fr', 'de']:
            self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)

    def test_nosubtitles(self):
        self.DL.expect_warning('video doesn\'t have subtitles')
        self.url = 'http://www.dailymotion.com/video/x12u166_le-zapping-tele-star-du-08-aout-2013_tv'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertFalse(subtitles)

@is_download_test
@unittest.skip('IE broken')
class TestTedSubtitles(BaseTestSubtitles):
    url = 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html'
    IE = TedTalkIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertTrue(len(subtitles.keys()) >= 28)
        self.assertEqual(md5(subtitles['en']), '4262c1665ff928a2dada178f62cb8d14')
        self.assertEqual(md5(subtitles['fr']), '66a63f7f42c97a50f8c0e90bc7797bb5')
        for lang in ['es', 'fr', 'de']:
            self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)

@is_download_test
class TestVimeoSubtitles(BaseTestSubtitles):
    url = 'http://vimeo.com/76979871'
    IE = VimeoIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'de', 'en', 'es', 'fr'})
        self.assertEqual(md5(subtitles['en']), '386cbc9320b94e25cb364b97935e5dd1')
        self.assertEqual(md5(subtitles['fr']), 'c9b69eef35bc6641c0d4da8a04f9dfac')

    def test_nosubtitles(self):
        self.DL.expect_warning('video doesn\'t have subtitles')
        self.url = 'http://vimeo.com/68093876'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertFalse(subtitles)

@is_download_test
@unittest.skip('IE broken')
class TestWallaSubtitles(BaseTestSubtitles):
    url = 'http://vod.walla.co.il/movie/2705958/the-yes-men'
    IE = WallaIE

    def test_allsubtitles(self):
        self.DL.expect_warning('Automatic Captions not supported by this server')
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'heb'})
        self.assertEqual(md5(subtitles['heb']), 'e758c5d7cb982f6bef14f377ec7a3920')

    def test_nosubtitles(self):
        self.DL.expect_warning('video doesn\'t have subtitles')
        self.url = 'http://vod.walla.co.il/movie/2642630/one-direction-all-for-one'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertFalse(subtitles)

@is_download_test
@unittest.skip('IE broken')
class TestCeskaTelevizeSubtitles(BaseTestSubtitles):
    url = 'http://www.ceskatelevize.cz/ivysilani/10600540290-u6-uzasny-svet-techniky'
    IE = CeskaTelevizeIE

    def test_allsubtitles(self):
        self.DL.expect_warning('Automatic Captions not supported by this server')
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'cs'})
        self.assertTrue(len(subtitles['cs']) > 20000)

    def test_nosubtitles(self):
        self.DL.expect_warning('video doesn\'t have subtitles')
        self.url = 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertFalse(subtitles)

@is_download_test
@unittest.skip('IE broken')
class TestLyndaSubtitles(BaseTestSubtitles):
    url = 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html'
    IE = LyndaIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), '09bbe67222259bed60deaa26997d73a7')

@is_download_test
@unittest.skip('IE broken')
class TestNPOSubtitles(BaseTestSubtitles):
    url = 'http://www.npo.nl/nos-journaal/28-08-2014/POW_00722860'
    IE = NPOIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'nl'})
        self.assertEqual(md5(subtitles['nl']), 'fc6435027572b63fb4ab143abd5ad3f4')

@is_download_test
@unittest.skip('IE broken')
class TestMTVSubtitles(BaseTestSubtitles):
    url = 'http://www.cc.com/video-clips/p63lk0/adam-devine-s-house-party-chasing-white-swans'
    IE = ComedyCentralIE

    def getInfoDict(self):
        return super().getInfoDict()['entries'][0]

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), '78206b8d8a0cfa9da64dc026eea48961')

@is_download_test
class TestNRKSubtitles(BaseTestSubtitles):
    url = 'http://tv.nrk.no/serie/ikke-gjoer-dette-hjemme/DMPV73000411/sesong-2/episode-1'
    IE = NRKTVIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'nb-ttv'})
        self.assertEqual(md5(subtitles['nb-ttv']), '67e06ff02d0deaf975e68f6cb8f6a149')

@is_download_test
class TestRaiPlaySubtitles(BaseTestSubtitles):
    IE = RaiPlayIE

    def test_subtitles_key(self):
        self.url = 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'it'})
        self.assertEqual(md5(subtitles['it']), 'b1d90a98755126b61e667567a1f6680a')

    def test_subtitles_array_key(self):
        self.url = 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'it'})
        self.assertEqual(md5(subtitles['it']), '4b3264186fbb103508abe5311cfcb9cd')

@is_download_test
@unittest.skip('IE broken - DRM only')
class TestVikiSubtitles(BaseTestSubtitles):
    url = 'http://www.viki.com/videos/1060846v-punch-episode-18'
    IE = VikiIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), '53cb083a5914b2d84ef1ab67b880d18a')

@is_download_test
class TestThePlatformSubtitles(BaseTestSubtitles):
    # from http://www.3playmedia.com/services-features/tools/integrations/theplatform/
    # (see http://theplatform.com/about/partners/type/subtitles-closed-captioning/)
    url = 'theplatform:JFUjUE1_ehvq'
    IE = ThePlatformIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), '97e7670cbae3c4d26ae8bcc7fdd78d4b')

@is_download_test
@unittest.skip('IE broken')
class TestThePlatformFeedSubtitles(BaseTestSubtitles):
    url = 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207'
    IE = ThePlatformFeedIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), '48649a22e82b2da21c9a67a395eedade')

@is_download_test
class TestRtveSubtitles(BaseTestSubtitles):
    url = 'http://www.rtve.es/alacarta/videos/los-misterios-de-laura/misterios-laura-capitulo-32-misterio-del-numero-17-2-parte/2428621/'
    IE = RTVEALaCartaIE

    def test_allsubtitles(self):
        print('Skipping, only available from Spain')
        return
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'es'})
        self.assertEqual(md5(subtitles['es']), '69e70cae2d40574fb7316f31d6eb7fca')

@is_download_test
class TestDemocracynowSubtitles(BaseTestSubtitles):
    url = 'http://www.democracynow.org/shows/2015/7/3'
    IE = DemocracynowIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), 'a3cc4c0b5eadd74d9974f1c1f5101045')

    def test_subtitles_in_page(self):
        self.url = 'http://www.democracynow.org/2015/7/3/this_flag_comes_down_today_bree'
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})
        self.assertEqual(md5(subtitles['en']), 'a3cc4c0b5eadd74d9974f1c1f5101045')

@is_download_test
class TestPBSSubtitles(BaseTestSubtitles):
    url = 'https://www.pbs.org/video/how-fantasy-reflects-our-world-picecq/'
    IE = PBSIE

    def test_allsubtitles(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['allsubtitles'] = True
        subtitles = self.getSubtitles()
        self.assertEqual(set(subtitles.keys()), {'en'})

    def test_subtitles_dfxp_format(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['subtitlesformat'] = 'dfxp'
        subtitles = self.getSubtitles()
        self.assertIn(md5(subtitles['en']), ['643b034254cdc3768ff1e750b6b5873b'])

    def test_subtitles_vtt_format(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['subtitlesformat'] = 'vtt'
        subtitles = self.getSubtitles()
        self.assertIn(
            md5(subtitles['en']), ['937a05711555b165d4c55a9667017045', 'f49ea998d6824d94959c8152a368ff73'])

    def test_subtitles_srt_format(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['subtitlesformat'] = 'srt'
        subtitles = self.getSubtitles()
        self.assertIn(md5(subtitles['en']), ['2082c21b43759d9bf172931b2f2ca371'])

    def test_subtitles_sami_format(self):
        self.DL.params['writesubtitles'] = True
        self.DL.params['subtitlesformat'] = 'sami'
        subtitles = self.getSubtitles()
        self.assertIn(md5(subtitles['en']), ['4256b16ac7da6a6780fafd04294e85cd'])

if __name__ == '__main__':
    unittest.main()


code:
#!/usr/bin/env python3

# Allow direct execution
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import json

from yt_dlp.update import rsa_verify

class TestUpdate(unittest.TestCase):
    def test_rsa_verify(self):
        UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'versions.json'), 'rb') as f:
            versions_info = f.read().decode()
        versions_info = json.loads(versions_info)
        signature = versions_info['signature']
        del versions_info['signature']
        self.assertTrue(rsa_verify(
            json.dumps(versions_info, sort_keys=True).encode(),
            signature, UPDATES_RSA_KEY))

if __name__ == '__main__':
    unittest.main()