test_huffman.py (1954B)
1 # -*- coding: utf-8 -*- 2 from hpack import HPACKDecodingError 3 from hpack.huffman import HuffmanEncoder 4 from hpack.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH 5 from hpack.huffman_table import decode_huffman 6 7 from hypothesis import given, example 8 from hypothesis.strategies import binary 9 10 11 class TestHuffman: 12 13 def test_request_huffman_decoder(self): 14 assert ( 15 decode_huffman(b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff') == 16 b"www.example.com" 17 ) 18 assert decode_huffman(b'\xa8\xeb\x10d\x9c\xbf') == b"no-cache" 19 assert decode_huffman(b'%\xa8I\xe9[\xa9}\x7f') == b"custom-key" 20 assert ( 21 decode_huffman(b'%\xa8I\xe9[\xb8\xe8\xb4\xbf') == b"custom-value" 22 ) 23 24 def test_request_huffman_encode(self): 25 encoder = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH) 26 assert ( 27 encoder.encode(b"www.example.com") == 28 b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff' 29 ) 30 assert encoder.encode(b"no-cache") == b'\xa8\xeb\x10d\x9c\xbf' 31 assert encoder.encode(b"custom-key") == b'%\xa8I\xe9[\xa9}\x7f' 32 assert ( 33 encoder.encode(b"custom-value") == b'%\xa8I\xe9[\xb8\xe8\xb4\xbf' 34 ) 35 36 37 class TestHuffmanDecoder: 38 @given(data=binary()) 39 @example(b'\xff') 40 @example(b'\x5f\xff\xff\xff\xff') 41 @example(b'\x00\x3f\xff\xff\xff') 42 def test_huffman_decoder_properly_handles_all_bytestrings(self, data): 43 """ 44 When given random bytestrings, either we get HPACKDecodingError or we 45 get a bytestring back. 46 """ 47 # The examples aren't special, they're just known to hit specific error 48 # paths through the state machine. Basically, they are strings that are 49 # definitely invalid. 50 try: 51 result = decode_huffman(data) 52 except HPACKDecodingError: 53 result = b'' 54 55 assert isinstance(result, bytes)