]> git.scottworley.com Git - paperdoorknob/blob - paperdoorknob_test.py
fetch: Multiple fetches per session
[paperdoorknob] / paperdoorknob_test.py
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 with requests.session() as s:
63 paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
64 self.assertEqual(self._request_counter, 1)
65 paperdoorknob.fetch(f"http://localhost:{self._port()}", s, TIMEOUT)
66 self.assertEqual(self._request_counter, 2)
67
68 def testFetchErrors(self) -> None:
69 with requests.session() as s:
70 with self.assertRaises(requests.HTTPError):
71 paperdoorknob.fetch(
72 f"http://localhost:{self._port()}/not_found", s, TIMEOUT)
73 with self.assertRaises(requests.HTTPError):
74 paperdoorknob.fetch(
75 f"http://localhost:{self._port()}/server_error", s, TIMEOUT)
76
77
78 if __name__ == '__main__':
79 unittest.main()