]> git.scottworley.com Git - paperdoorknob/blame - paperdoorknob_test.py
fetch: Verify error handling
[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):
36 def setUp(self) -> None:
680f7d10
SW
37 web_server = HTTPServer(('', 0), FakeGlowficHTTPRequestHandler)
38 self._port = web_server.socket.getsockname()[1]
b25a2f90
SW
39 threading.Thread(target=web_server.serve_forever).start()
40 self._stop_server = web_server.shutdown
41
42 def tearDown(self) -> None:
43 self._stop_server()
44
45 def testFetch(self) -> None:
680f7d10 46 paperdoorknob.fetch(f"http://localhost:{self._port}", TIMEOUT)
b25a2f90 47
6fdb8f01
SW
48 def testFetchErrors(self) -> None:
49 with self.assertRaises(requests.HTTPError):
50 paperdoorknob.fetch(
51 f"http://localhost:{self._port}/not_found", TIMEOUT)
52 with self.assertRaises(requests.HTTPError):
53 paperdoorknob.fetch(
54 f"http://localhost:{self._port}/server_error", TIMEOUT)
55
b25a2f90
SW
56
57if __name__ == '__main__':
58 unittest.main()