File size: 3,641 Bytes
1f150ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The extracted validator matches the pinned original under every patched app limit."""
import ast
import contextlib
import hashlib
import io
from pathlib import Path
import unittest
import zipfile
from unittest.mock import patch

from backend import app, reader_archive

OLD = Path(__file__).resolve().parents[3] / 'scripts/coverage-anchors/reader-archive-old-app.py.snapshot'


def build(files, comment=b''):
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as book_zip:
        for name, content in files.items():
            book_zip.writestr(name, content)
        book_zip.comment = comment
    return buffer.getvalue()


def outcome(call, raw):
    try:
        call(raw)
    except Exception as error:
        return (type(error).__name__, str(error), type(error.__cause__).__name__)
    return None


class ReaderArchiveContractTests(unittest.TestCase):
    def original_code(self):
        source = OLD.read_bytes()
        self.assertEqual(hashlib.sha256(source).hexdigest(),
                         '282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca')
        nodes = [node for node in ast.parse(source).body
                 if isinstance(node, ast.FunctionDef) and node.name == 'validate_reader_archive']
        self.assertEqual(len(nodes), 1)
        nodes[0].name = '_original_validate_reader_archive'
        return compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])), '<original>', 'exec')

    def test_public_names_are_the_extracted_objects(self):
        for name in ('ReaderArchiveLimitError', 'ReaderArchiveInvalidError', 'ReaderDocumentLimitError'):
            self.assertIs(getattr(app, name), getattr(reader_archive, name))
        self.assertIs(app.validate_reader_archive.__module__, app.__name__)

    def test_original_and_wrapper_agree_under_patched_limits(self):
        code = self.original_code()
        corpus = [build({'a.txt': b'hello'}), build({'a.txt': b'hello'}, b'comment'), build({}),
                  build({'bomb': b'x' * 100000}), build({'../escape': b'x'}), build({'d/': b'', 'd/a': b'text'}),
                  b'PKnot-a-zip', b'', build({'a.txt': b'hello'})[:-1]]
        cases = [{}, {'READER_ARCHIVE_MAX_ENTRIES': 0}, {'READER_ARCHIVE_MAX_EXPANDED_BYTES': 3},
                 {'READER_ARCHIVE_MAX_METADATA_BYTES': 1}, {'READER_RESOURCE_MAX_ARCHIVE_BYTES': 10},
                 {'READER_ARCHIVE_MAX_COMPRESSION_RATIO': 0}, {'READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES': 0}]
        seen = set()
        for limits in cases:
            for raw in corpus:
                with self.subTest(limits=limits, size=len(raw)), patch.dict(app.__dict__), contextlib.ExitStack() as stack:
                    for name, value in limits.items():
                        stack.enter_context(patch.object(app, name, value))
                    exec(code, app.__dict__)  # noqa: S102
                    expected = outcome(app._original_validate_reader_archive, raw)
                    self.assertEqual(outcome(app.validate_reader_archive, raw), expected)
                    seen.add(expected)
        self.assertIn(None, seen)
        self.assertGreater(len({item[0] for item in seen if item}), 1)

    def test_wrapper_reads_limits_at_call_time(self):
        raw = build({'a.txt': b'hello'})
        self.assertIsNone(app.validate_reader_archive(raw))
        with patch.object(app, 'READER_ARCHIVE_MAX_ENTRIES', 0), self.assertRaises(app.ReaderArchiveLimitError):
            app.validate_reader_archive(raw)
        self.assertIsNone(app.validate_reader_archive(raw))


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