import functools import hashlib from http.server import ThreadingHTTPServer import pathlib import sys import threading import unittest import urllib.error import urllib.request ROOT = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from server import Handler class ServerTest(unittest.TestCase): @classmethod def setUpClass(cls): handler = functools.partial(Handler, directory=str(ROOT)) cls.server = ThreadingHTTPServer(('127.0.0.1', 0), handler) cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) cls.thread.start() cls.origin = 'http://127.0.0.1:' + str(cls.server.server_address[1]) @classmethod def tearDownClass(cls): cls.server.shutdown() cls.server.server_close() cls.thread.join() def test_data_and_fonts_are_same_origin_and_unchanged(self): files = { 'data/events.bin.gz': 'application/gzip', 'data/messages/1-0.json.gz': 'application/gzip', 'assets/fonts/LetterGothic.ttf': 'font/ttf', 'assets/vendor/fonts/KaTeX_Main-Regular.woff2': 'font/woff2', } for path, content_type in files.items(): with self.subTest(path=path): url = self.origin + '/' + path request = urllib.request.Request(url, headers={'Origin': self.origin}) with urllib.request.urlopen(request) as response: self.assertEqual(response.status, 200) self.assertEqual(response.url, url) self.assertIsNone(response.headers.get('Location')) self.assertIsNone(response.headers.get('Content-Encoding')) self.assertEqual(response.headers['Content-Type'], content_type) self.assertEqual(response.headers['Cache-Control'], 'no-cache') actual = hashlib.sha256(response.read()).hexdigest() self.assertEqual(actual, hashlib.sha256((ROOT/path).read_bytes()).hexdigest()) def test_reload_revalidates_the_page(self): url = self.origin + '/index.html' with urllib.request.urlopen(url) as response: modified = response.headers['Last-Modified'] request = urllib.request.Request(url, headers={'If-Modified-Since': modified}) with self.assertRaises(urllib.error.HTTPError) as caught: urllib.request.urlopen(request) self.assertEqual(caught.exception.code, 304) self.assertEqual(caught.exception.headers['Cache-Control'], 'no-cache') if __name__ == '__main__': unittest.main()