]> git.scottworley.com Git - paperdoorknob/blob - paperdoorknob_test.py
fetch: test: Explicitly close webserver
[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 _response_code(self) -> int:
20 if self.path == "/not_found":
21 return 404
22 if self.path == "/server_error":
23 return 500
24 return 200
25
26 def do_GET(self) -> None:
27 body = b'<html><body>This is glowfic</body></html>'
28 self.send_response(self._response_code())
29 self.send_header("Content-type", "text/html")
30 self.send_header("Content-Length", str(len(body)))
31 self.end_headers()
32 self.wfile.write(body)
33
34
35 class TestFetch(unittest.TestCase):
36 def _port(self) -> int:
37 port = self._web_server.socket.getsockname()[1]
38 assert isinstance(port, int)
39 return port
40
41 def setUp(self) -> None:
42 self._web_server = HTTPServer(('', 0), FakeGlowficHTTPRequestHandler)
43 self._thread = threading.Thread(target=self._web_server.serve_forever)
44 self._thread.start()
45
46 def tearDown(self) -> None:
47 self._web_server.shutdown()
48 self._thread.join()
49 self._web_server.server_close()
50
51 def testFetch(self) -> None:
52 paperdoorknob.fetch(f"http://localhost:{self._port()}", TIMEOUT)
53
54 def testFetchErrors(self) -> None:
55 with self.assertRaises(requests.HTTPError):
56 paperdoorknob.fetch(
57 f"http://localhost:{self._port()}/not_found", TIMEOUT)
58 with self.assertRaises(requests.HTTPError):
59 paperdoorknob.fetch(
60 f"http://localhost:{self._port()}/server_error", TIMEOUT)
61
62
63 if __name__ == '__main__':
64 unittest.main()