File size: 7,752 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""Conditional transport and question snapshot invalidation boundaries."""
import io
import json
from pathlib import Path
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch

from apps.console.server.http_app import Application, Response, conditional, make_server
from apps.console.server.question_review import Questions
from apps.console.server.registry import Registry


class ConditionalTests(unittest.TestCase):
    def test_validators(self):
        response = Response(200, {'Content-Type': 'application/json', 'Vary': 'Accept-Encoding'}, b'{}')
        first = conditional(response, 'GET', '/api/v1/questions', '')
        self.assertEqual(first.headers['Cache-Control'], 'no-cache')
        self.assertRegex(first.headers['ETag'], r'^"[0-9a-f]{32}"$')
        self.assertNotIn('ETag', response.headers)
        for method in ('GET', 'HEAD'):
            for match in (first.headers['ETag'], '*', '"other", ' + first.headers['ETag']):
                with self.subTest(method=method, match=match):
                    hit = conditional(response, method, '/api/v1/questions', match)
                    self.assertEqual(hit.status, 304)
                    self.assertEqual(hit.body, b'')
                    self.assertEqual(hit.headers, {k: first.headers[k] for k in ('ETag', 'Cache-Control', 'Vary')})
        self.assertEqual(conditional(response, 'GET', '/', '"other"').status, 200)
        for content_type in ('image/png', 'text/html; charset=utf-8', 'application/octet-stream'):   # 审题页的 .bin.gz 原来落到 no-store,热开每次整份重传
            self.assertIn('ETag', conditional(Response(200, {'Content-Type': content_type}, b'x'), 'GET', '/', '').headers)

    def test_exclusions(self):
        response = Response(200, {'Content-Type': 'application/json'}, b'{}')
        cases = [(response, 'GET', '/api/v1/questions/x/reveal'), (response, 'POST', '/'),
                 (Response(200, {**response.headers, 'Cache-Control': 'immutable'}, b'{}'), 'GET', '/'),
                 (Response(200, {'Content-Type': 'video/mp4'}, b'x'), 'GET', '/'),
                 (Response(200, response.headers, b'', io.BytesIO(b'x')), 'GET', '/'),
                 (Response(404, response.headers, b'{}'), 'GET', '/')]
        for item, method, path in cases:
            with self.subTest(method=method, path=path, headers=item.headers):
                self.assertIs(conditional(item, method, path, '*'), item)


class ApplicationCacheTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.root = Path(self.temp.name)
        (self.root / 'index.html').write_text('<html>cache</html>')
        self.app = Application(Registry([]), self.root)
        self.addCleanup(self.temp.cleanup)
        self.addCleanup(self.app.close)

    def test_index(self):
        first = self.app.dispatch('GET', '/')
        self.assertIn('ETag', first.headers)
        self.assertEqual(self.app.dispatch('GET', '/?v=1', {'iF-NoNe-MaTcH': first.headers['ETag']}).status, 304)

    def test_imported_import_segment_gets_media_reference(self):
        segment_id = 'batch/segment'
        self.app.registry.entries[segment_id] = SimpleNamespace(directory=self.root)
        (self.root / 'review-import.json').write_text('{}')
        view = {'schema': 'segment-view/6', 'warnings': []}
        reference = {'url': '/media/new.mp4', 'source_group_id': 'generator-script'}
        url = '/api/v1/segments/batch%2Fsegment'
        with patch('apps.console.server.segment_import.verify_import', return_value={}), \
                patch('apps.console.server.segment_import.read_import', return_value=(view, b'png')), \
                patch.object(self.app.media, 'reference', return_value=None) as media:
            first = self.app.dispatch('GET', url)
            self.assertEqual(first.status, 200)
            self.assertNotIn('media_ref', json.loads(first.body))
            media.return_value = reference
            second = self.app.dispatch('GET', url)
            self.assertEqual(second.status, 200)
            self.assertEqual(json.loads(second.body)['media_ref'], reference)
            self.assertEqual(self.app._segment(segment_id, True).body, b'png')

    def test_questions_cache_and_gzip(self):
        class FakeQuestions:
            key = 1
            calls = 0

            def listing_key(self, media=None):
                return self.key

            def listing(self, media=None):
                self.calls += 1
                return {'text': 'x' * 17000, 'version': self.key}

        fake = self.app.questions = FakeQuestions()
        first = self.app.dispatch('GET', '/api/v1/questions')
        self.app.dispatch('GET', '/api/v1/questions')
        self.assertEqual(fake.calls, 1)
        compressed = self.app.dispatch('GET', '/api/v1/questions', {'Accept-Encoding': 'gzip'})
        self.assertNotEqual(first.headers['ETag'], compressed.headers['ETag'])
        hit = self.app.dispatch('GET', '/api/v1/questions', {'Accept-Encoding': 'gzip', 'If-None-Match': compressed.headers['ETag']})
        self.assertEqual((hit.status, hit.body, hit.headers['Vary']), (304, b'', 'Accept-Encoding'))
        fake.key = 2
        changed = self.app.dispatch('GET', '/api/v1/questions')
        self.assertEqual(fake.calls, 2)
        self.assertNotEqual(first.headers['ETag'], changed.headers['ETag'])

    def test_304_transport(self):
        # Exercise the actual handler without opening a socket.
        with patch('apps.console.server.http_app.ThreadingHTTPServer') as server:
            make_server(self.app, 0)
        handler_class = server.call_args.args[1]
        handler = object.__new__(handler_class)
        handler.command, handler.path = 'GET', '/'
        handler.headers = {'If-None-Match': self.app.dispatch('GET', '/').headers['ETag']}
        handler.wfile = io.BytesIO()
        sent = {}
        handler.send_response = lambda status: sent.update(status=status)
        handler.send_header = lambda name, value: sent.update({name: value})
        handler.end_headers = lambda: None
        handler._respond()
        self.assertEqual(sent['status'], 304)
        self.assertNotIn('Content-Length', sent)
        self.assertEqual(handler.wfile.getvalue(), b'')


class ListingKeyTests(unittest.TestCase):
    def test_dependencies(self):
        with tempfile.TemporaryDirectory() as temp:
            root = Path(temp)
            directory = root / 'entry'
            directory.mkdir()
            source = root / 'input'
            source.write_text('a')
            manifest = directory / 'review-import.json'
            manifest.write_text(json.dumps({'inputs': {'x': {'path': str(source)}}}))
            nested = directory / 'nested'
            nested.mkdir()
            extra = nested / 'extra'
            extra.write_text('x')
            questions = Questions(SimpleNamespace(entries={'a': SimpleNamespace(id='a', directory=directory)}))
            first = questions.listing_key()
            self.assertEqual(first, questions.listing_key())
            for path in (source, extra, manifest):
                before = questions.listing_key()
                path.write_text(path.read_text() + ' ')
                self.assertNotEqual(before, questions.listing_key())
            before = questions.listing_key()
            source.unlink()
            self.assertNotEqual(before, questions.listing_key())
            self.assertIn((str(source), None), questions.listing_key()[0][1])
            before = questions.listing_key()
            questions.evidence_data = root
            self.assertNotEqual(before, questions.listing_key())


if __name__ == '__main__':
    unittest.main()