def test_der(): # This input is the following structure, using # https://github.com/google/der-ascii # # SEQUENCE { # SEQUENCE { # NULL {} # INTEGER { 42 } # OCTET_STRING { "hello" } # } # } der = b"\x30\x0e\x30\x0c\x05\x00\x02\x01\x2a\x04\x05\x68\x65\x6c\x6c\x6f" reader = DERReader(der) with pytest.raises(ValueError): reader.check_empty() with pytest.raises(ValueError): with reader: pass with pytest.raises(ZeroDivisionError): with DERReader(der): raise ZeroDivisionError # Parse the outer element. outer = reader.read_element(SEQUENCE) reader.check_empty() assert outer.data.tobytes() == der[2:] # Parse the outer element with read_any_element. reader = DERReader(der) tag, outer2 = reader.read_any_element() reader.check_empty() assert tag == SEQUENCE assert outer2.data.tobytes() == der[2:] # Parse the outer element with read_single_element. outer3 = DERReader(der).read_single_element(SEQUENCE) assert outer3.data.tobytes() == der[2:] # read_single_element rejects trailing data. with pytest.raises(ValueError): DERReader(der + der).read_single_element(SEQUENCE) # Continue parsing the structure. inner = outer.read_element(SEQUENCE) outer.check_empty() # Parsing a missing optional element should work. assert inner.read_optional_element(INTEGER) is None null = inner.read_element(NULL) null.check_empty() # Parsing a present optional element should work. integer = inner.read_optional_element(INTEGER) assert integer is not None assert integer.as_integer() == 42 octet_string = inner.read_element(OCTET_STRING) assert octet_string.data.tobytes() == b"hello" # Parsing a missing optional element should work when the input is empty. inner.check_empty() assert inner.read_optional_element(INTEGER) is None # Re-encode the same structure. der2 = encode_der( SEQUENCE, encode_der( SEQUENCE, encode_der(NULL), encode_der(INTEGER, encode_der_integer(42)), encode_der(OCTET_STRING, b"hello"), ), ) assert der2 == der
def test_der_reader_bad_input(bad_input): reader = DERReader(bad_input) with pytest.raises(ValueError): reader.read_any_element()