aboutsummaryrefslogtreecommitdiffstats
path: root/test/netlib/http/test_encoding.py
blob: 89600709664cbc0d35be3819a259c426ac67bb65 (plain)
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
import mock
import pytest

from netlib.http import encoding
from mitmproxy.test import tutils


@pytest.mark.parametrize("encoder", [
    'identity',
    'none',
])
def test_identity(encoder):
    assert b"string" == encoding.decode(b"string", encoder)
    assert b"string" == encoding.encode(b"string", encoder)
    with tutils.raises(ValueError):
        encoding.encode(b"string", "nonexistent encoding")


@pytest.mark.parametrize("encoder", [
    'gzip',
    'br',
    'deflate',
])
def test_encoders(encoder):
    assert "" == encoding.decode("", encoder)
    assert b"" == encoding.decode(b"", encoder)

    assert "string" == encoding.decode(
        encoding.encode(
            "string",
            encoder
        ),
        encoder
    )
    assert b"string" == encoding.decode(
        encoding.encode(
            b"string",
            encoder
        ),
        encoder
    )

    with tutils.raises(ValueError):
        encoding.decode(b"foobar", encoder)


def test_cache():
    decode_gzip = mock.MagicMock()
    decode_gzip.return_value = b"decoded"
    encode_gzip = mock.MagicMock()
    encode_gzip.return_value = b"encoded"

    with mock.patch.dict(encoding.custom_decode, gzip=decode_gzip):
        with mock.patch.dict(encoding.custom_encode, gzip=encode_gzip):
            assert encoding.decode(b"encoded", "gzip") == b"decoded"
            assert decode_gzip.call_count == 1

            # should be cached
            assert encoding.decode(b"encoded", "gzip") == b"decoded"
            assert decode_gzip.call_count == 1

            # the other way around as well
            assert encoding.encode(b"decoded", "gzip") == b"encoded"
            assert encode_gzip.call_count == 0

            # different encoding
            decode_gzip.return_value = b"bar"
            assert encoding.encode(b"decoded", "deflate") != b"decoded"
            assert encode_gzip.call_count == 0

            # This is not in the cache anymore
            assert encoding.encode(b"decoded", "gzip") == b"encoded"
            assert encode_gzip.call_count == 1