Reject a malformed chunk length
Reject a malformed chunk length
A chunked body cannot be decoded if its length token is not hexadecimal. This example isolates that decision with the synthetic line G7;debug=yes\r\n. It first removes the optional chunk extension, then checks every remaining byte against an explicit ASCII hexadecimal alphabet. Because G is not allowed, the function raises ValueError before calling int() or consuming body bytes.
The try block demonstrates the expected rejection path. It asserts the exception message so the output does not depend on an interpreter-generated conversion error, then prints a stable result. The final assertion proves the example reached the rejection branch for this one malformed token. It does not prove that a larger HTTP parser rejects every invalid chunked message. No newer API is used; the example uses established Python 3 language and bytes features.
The check is intentionally narrow. It rejects leading plus or minus signs and whitespace because those bytes are absent from HEX_DIGITS; it does not separately diagnose why a byte is invalid. It also does not validate CRLF placement, maximum chunk sizes, trailer fields, or the surrounding transfer-coding declaration. A production parser should define those rules, report structured errors, and apply input-size limits. The example has no network I/O and retains no data beyond its byte literal.
Python’s HTTP client documentation describes chunked transfer encoding in HTTP handling. The base-16 conversion behavior comes from the int() documentation.
AI-assistance disclosure: AI assisted the drafting of this educational example.
HEX_DIGITS = b"0123456789abcdefABCDEF"
def parse_chunk_length(line):
token = line.rstrip(b"\r\n").split(b";", 1)[0]
if not token or any(byte not in HEX_DIGITS for byte in token):
raise ValueError("invalid chunk length")
return int(token, 16)
fixture = b"G7;debug=yes\r\n"
try:
parse_chunk_length(fixture)
except ValueError as error:
assert str(error) == "invalid chunk length"
print("rejected:", error)
else:
raise AssertionError("fixture should be rejected")
rejected: invalid chunk length