]> git.scottworley.com Git - paperdoorknob/blame - paperdoorknob_test.py
fetch: test: Hold reference to webserver
[paperdoorknob] / paperdoorknob_test.py
CommitLineData
b25a2f90
SW
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
8import unittest
9import threading
10from http.server import BaseHTTPRequestHandler, HTTPServer
6fdb8f01 11import requests
b25a2f90
SW
12import paperdoorknob
13
b25a2f90
SW
14TIMEOUT = 8
15
16
17class FakeGlowficHTTPRequestHandler(BaseHTTPRequestHandler):
18
6fdb8f01
SW
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
b25a2f90
SW
26 def do_GET(self) -> None:
27 body = b'<html><body>This is glowfic</body></html>'
6fdb8f01 28 self.send_response(self._response_code())
b25a2f90
SW
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
35class TestFetch(unittest.TestCase):
681380e2
SW
36 def _port(self) -> int:
37 port = self._web_server.socket.getsockname()[1]
38 assert isinstance(port, int)
39 return port
40
b25a2f90 41 def setUp(self) -> None:
681380e2
SW
42 self._web_server = HTTPServer(('', 0), FakeGlowficHTTPRequestHandler)
43 self._thread = threading.Thread(target=self._web_server.serve_forever)
e3ba2056 44 self._thread.start()
b25a2f90
SW
45
46 def tearDown(self) -> None:
681380e2 47 self._web_server.shutdown()
e3ba2056 48 self._thread.join()
b25a2f90
SW
49
50 def testFetch(self) -> None:
681380e2 51 paperdoorknob.fetch(f"http://localhost:{self._port()}", TIMEOUT)
b25a2f90 52
6fdb8f01
SW
53 def testFetchErrors(self) -> None:
54 with self.assertRaises(requests.HTTPError):
55 paperdoorknob.fetch(
681380e2 56 f"http://localhost:{self._port()}/not_found", TIMEOUT)
6fdb8f01
SW
57 with self.assertRaises(requests.HTTPError):
58 paperdoorknob.fetch(
681380e2 59 f"http://localhost:{self._port()}/server_error", TIMEOUT)
6fdb8f01 60
b25a2f90
SW
61
62if __name__ == '__main__':
63 unittest.main()