import re
def decode_response_headers(headers):
"""
Decodes response headers for hypothesis validation, handling edge cases.
Args:
headers (dict): A dictionary of response headers.
Returns:
dict: A dictionary of decoded headers. Returns an empty dictionary if input is invalid.
"""
if not isinstance(headers, dict):
return {}
decoded_headers = {}
for key, value in headers.items():
if not isinstance(key, str):
continue # Skip invalid keys
if value is None:
decoded_headers[key] = None
elif isinstance(value, str):
decoded_headers[key] = value.strip()
elif isinstance(value, list):
decoded_headers[key] = [str(item).strip() for item in value if item is not None]
elif isinstance(value, (int, float)):
decoded_headers[key] = value
else:
decoded_headers[key] = str(value) # Convert to string for consistency
return decoded_headers
if __name__ == '__main__':
# Example Usage & Edge Case Handling
headers1 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": "Bearer abc"}
decoded_headers1 = decode_response_headers(headers1)
print(f"Headers 1: {decoded_headers1}")
headers2 = {"Content-Type": None, "Cache-Control": "no-cache", "Authorization": None}
decoded_headers2 = decode_response_headers(headers2)
print(f"Headers 2: {decoded_headers2}")
headers3 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": [None, "Bearer abc"]}
decoded_headers3 = decode_response_headers(headers3)
print(f"Headers 3: {decoded_headers3}")
headers4 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": 123}
decoded_headers4 = decode_response_headers(headers4)
print(f"Headers 4: {decoded_headers4}")
headers5 = "not a dictionary"
decoded_headers5 = decode_response_headers(headers5)
print(f"Headers 5: {decoded_headers5}")
headers6 = {"Content-Type": 123, "Cache-Control": "no-cache", "Authorization": "Bearer abc"}
decoded_headers6 = decode_response_headers(headers6)
print(f"Headers 6: {decoded_headers6}")
Add your comment