|
| 1 | +import unittest |
| 2 | +import os |
| 3 | +import http_server |
| 4 | + |
| 5 | + |
| 6 | +class TestCase(unittest.TestCase): |
| 7 | + |
| 8 | + def test_response_ok(self): |
| 9 | + mimetype = b"image/bmp" |
| 10 | + body = b"foo" |
| 11 | + |
| 12 | + response = http_server.response_ok(body=body, mimetype=mimetype) |
| 13 | + str_response = response.decode() |
| 14 | + |
| 15 | + self.assertIn("\r\n\r\n", str_response) |
| 16 | + |
| 17 | + str_header, str_body = str_response.split("\r\n\r\n") |
| 18 | + |
| 19 | + self.assertEqual(body.decode(), str_body) |
| 20 | + self.assertEqual("HTTP/1.1 200 OK", |
| 21 | + str_header.splitlines()[0]) |
| 22 | + self.assertIn("Content-Type: " + mimetype.decode(), str_header) |
| 23 | + |
| 24 | + def test_response_method_not_allowed(self): |
| 25 | + response = http_server.response_method_not_allowed() |
| 26 | + str_response = response.decode() |
| 27 | + |
| 28 | + self.assertEqual("HTTP/1.1 405 Method Not Allowed", |
| 29 | + str_response.splitlines()[0]) |
| 30 | + |
| 31 | + def test_response_not_found(self): |
| 32 | + response = http_server.response_not_found() |
| 33 | + str_response = response.decode() |
| 34 | + |
| 35 | + self.assertEqual("HTTP/1.1 404 Not Found", |
| 36 | + str_response.splitlines()[0]) |
| 37 | + |
| 38 | + def test_parse_request_bad_method(self): |
| 39 | + request_head = "POST /foo HTTP/1.1" |
| 40 | + |
| 41 | + with self.assertRaises(NotImplementedError): |
| 42 | + http_server.parse_request(request_head) |
| 43 | + |
| 44 | + def test_parse_request(self): |
| 45 | + path = "/foo" |
| 46 | + request_head = "GET {} HTTP/1.1".format(path) |
| 47 | + |
| 48 | + self.assertEqual(path, http_server.parse_request(request_head)) |
| 49 | + |
| 50 | + def test_response_path_file(self): |
| 51 | + path = "/a_web_page.html" |
| 52 | + |
| 53 | + content, mime_type = http_server.response_path(path) |
| 54 | + |
| 55 | + self.assertEqual(b"text/html", mime_type) |
| 56 | + |
| 57 | + with open(os.path.join("webroot", "a_web_page.html"), "rb") as f: |
| 58 | + self.assertEqual(f.read(), content) |
| 59 | + |
| 60 | + def test_response_path_dir(self): |
| 61 | + path = "/" |
| 62 | + |
| 63 | + content, mime_type = http_server.response_path(path) |
| 64 | + |
| 65 | + self.assertIn(b"favicon.ico", content) |
| 66 | + self.assertIn(b"make_time.py", content) |
| 67 | + self.assertIn(b"sample.txt", content) |
| 68 | + self.assertIn(b"a_web_page.html", content) |
| 69 | + |
| 70 | + def test_response_path_not_found(self): |
| 71 | + path = "/foo/bar/baz/doesnt/exist" |
| 72 | + |
| 73 | + with self.assertRaises(NameError): |
| 74 | + http_server.response_path(path) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == '__main__': |
| 78 | + unittest.main() |
0 commit comments