File size: 2,641 Bytes
c1e4f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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()