File: test_huffman.py

package info (click to toggle)
python-hpack 4.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 444 kB
  • sloc: python: 5,866; makefile: 25
file content (55 lines) | stat: -rw-r--r-- 1,954 bytes parent folder | download | duplicates (16)
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
# -*- coding: utf-8 -*-
from hpack import HPACKDecodingError
from hpack.huffman import HuffmanEncoder
from hpack.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH
from hpack.huffman_table import decode_huffman

from hypothesis import given, example
from hypothesis.strategies import binary


class TestHuffman:

    def test_request_huffman_decoder(self):
        assert (
            decode_huffman(b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff') ==
            b"www.example.com"
        )
        assert decode_huffman(b'\xa8\xeb\x10d\x9c\xbf') == b"no-cache"
        assert decode_huffman(b'%\xa8I\xe9[\xa9}\x7f') == b"custom-key"
        assert (
            decode_huffman(b'%\xa8I\xe9[\xb8\xe8\xb4\xbf') == b"custom-value"
        )

    def test_request_huffman_encode(self):
        encoder = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH)
        assert (
            encoder.encode(b"www.example.com") ==
            b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff'
        )
        assert encoder.encode(b"no-cache") == b'\xa8\xeb\x10d\x9c\xbf'
        assert encoder.encode(b"custom-key") == b'%\xa8I\xe9[\xa9}\x7f'
        assert (
            encoder.encode(b"custom-value") == b'%\xa8I\xe9[\xb8\xe8\xb4\xbf'
        )


class TestHuffmanDecoder:
    @given(data=binary())
    @example(b'\xff')
    @example(b'\x5f\xff\xff\xff\xff')
    @example(b'\x00\x3f\xff\xff\xff')
    def test_huffman_decoder_properly_handles_all_bytestrings(self, data):
        """
        When given random bytestrings, either we get HPACKDecodingError or we
        get a bytestring back.
        """
        # The examples aren't special, they're just known to hit specific error
        # paths through the state machine. Basically, they are strings that are
        # definitely invalid.
        try:
            result = decode_huffman(data)
        except HPACKDecodingError:
            result = b''

        assert isinstance(result, bytes)