Debian Codegraph @

tests/test_timeout.py

raw
1 import threading
2 import time
3 from http.server import BaseHTTPRequestHandler
4 from socketserver import TCPServer
5
6 import av
7
8 from .common import TestCase, fate_suite
9
10 CONTENT = open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb").read()
11 # Needs to be long enough for all host OSes to deal.
12 TIMEOUT = 0.25
13 DELAY = 4 * TIMEOUT
14
15
16 class HttpServer(TCPServer):
17 allow_reuse_address = True
18
19 def handle_error(self, request: object, client_address: object) -> None:
20 pass
21
22
23 class SlowRequestHandler(BaseHTTPRequestHandler):
24 def do_GET(self) -> None:
25 time.sleep(DELAY)
26 self.send_response(200)
27 self.send_header("Content-Length", str(len(CONTENT)))
28 self.end_headers()
29 self.wfile.write(CONTENT)
30
31 def log_message(self, format: object, *args: object) -> None:
32 pass
33
34
35 class TestTimeout(TestCase):
36 port = 8002
37
38 def setUp(cls) -> None:
39 while True:
40 try:
41 cls._server = HttpServer(("", cls.port), SlowRequestHandler)
42 except OSError:
43 cls.port += 1
44 else:
45 break
46
47 cls._thread = threading.Thread(target=cls._server.handle_request)
48 cls._thread.daemon = True # Make sure the tests will exit.
49 cls._thread.start()
50
51 def tearDown(cls) -> None:
52 cls._thread.join(1) # Can't wait forever or the tests will never exit.
53 cls._server.server_close()
54
55 def test_no_timeout(self) -> None:
56 start = time.time()
57 av.open(f"http://localhost:{self.port}/mpeg2_field_encoding.ts")
58 duration = time.time() - start
59 assert duration > DELAY
60
61 def test_open_timeout(self) -> None:
62 with self.assertRaises(av.ExitError):
63 start = time.time()
64 av.open(
65 f"http://localhost:{self.port}/mpeg2_field_encoding.ts", timeout=TIMEOUT
66 )
67
68 duration = time.time() - start
69 assert duration < DELAY
70
71 def test_open_timeout_2(self) -> None:
72 with self.assertRaises(av.ExitError):
73 start = time.time()
74 av.open(
75 f"http://localhost:{self.port}/mpeg2_field_encoding.ts",
76 timeout=(TIMEOUT, None),
77 )
78
79 duration = time.time() - start
80 assert duration < DELAY