]>
Commit | Line | Data |
---|---|---|
1 | # paperdoorknob: Print glowfic | |
2 | # | |
3 | # This program is free software: you can redistribute it and/or modify it | |
4 | # under the terms of the GNU General Public License as published by the | |
5 | # Free Software Foundation, version 3. | |
6 | ||
7 | ||
8 | import unittest | |
9 | import threading | |
10 | from http.server import BaseHTTPRequestHandler, HTTPServer | |
11 | import requests | |
12 | import paperdoorknob | |
13 | ||
14 | TIMEOUT = 8 | |
15 | ||
16 | ||
17 | class FakeGlowficHTTPRequestHandler(BaseHTTPRequestHandler): | |
18 | ||
19 | def _notify_test(self) -> None: | |
20 | raise NotImplementedError() | |
21 | ||
22 | def _response_code(self) -> int: | |
23 | if self.path == "/not_found": | |
24 | return 404 | |
25 | if self.path == "/server_error": | |
26 | return 500 | |
27 | return 200 | |
28 | ||
29 | def do_GET(self) -> None: | |
30 | body = b'<html><body>This is glowfic</body></html>' | |
31 | self.send_response(self._response_code()) | |
32 | self.send_header("Content-type", "text/html") | |
33 | self.send_header("Content-Length", str(len(body))) | |
34 | self.end_headers() | |
35 | self.wfile.write(body) | |
36 | self._notify_test() | |
37 | ||
38 | ||
39 | class TestFetch(unittest.TestCase): | |
40 | def _port(self) -> int: | |
41 | port = self._web_server.socket.getsockname()[1] | |
42 | assert isinstance(port, int) | |
43 | return port | |
44 | ||
45 | def _count_request(self) -> None: | |
46 | self._request_counter += 1 | |
47 | ||
48 | def setUp(self) -> None: | |
49 | self._request_counter = 0 | |
50 | handler = type("Handler", (FakeGlowficHTTPRequestHandler,), { | |
51 | '_notify_test': lambda _: self._count_request()}) | |
52 | self._web_server = HTTPServer(('', 0), handler) | |
53 | self._thread = threading.Thread(target=self._web_server.serve_forever) | |
54 | self._thread.start() | |
55 | ||
56 | def tearDown(self) -> None: | |
57 | self._web_server.shutdown() | |
58 | self._thread.join() | |
59 | self._web_server.server_close() | |
60 | ||
61 | def testFetch(self) -> None: | |
62 | paperdoorknob.fetch(f"http://localhost:{self._port()}", TIMEOUT) | |
63 | self.assertEqual(self._request_counter, 1) | |
64 | paperdoorknob.fetch(f"http://localhost:{self._port()}", TIMEOUT) | |
65 | self.assertEqual(self._request_counter, 2) | |
66 | ||
67 | def testFetchErrors(self) -> None: | |
68 | with self.assertRaises(requests.HTTPError): | |
69 | paperdoorknob.fetch( | |
70 | f"http://localhost:{self._port()}/not_found", TIMEOUT) | |
71 | with self.assertRaises(requests.HTTPError): | |
72 | paperdoorknob.fetch( | |
73 | f"http://localhost:{self._port()}/server_error", TIMEOUT) | |
74 | ||
75 | ||
76 | if __name__ == '__main__': | |
77 | unittest.main() |