1. import re
  2. def decode_response_headers(headers):
  3. """
  4. Decodes response headers for hypothesis validation, handling edge cases.
  5. Args:
  6. headers (dict): A dictionary of response headers.
  7. Returns:
  8. dict: A dictionary of decoded headers. Returns an empty dictionary if input is invalid.
  9. """
  10. if not isinstance(headers, dict):
  11. return {}
  12. decoded_headers = {}
  13. for key, value in headers.items():
  14. if not isinstance(key, str):
  15. continue # Skip invalid keys
  16. if value is None:
  17. decoded_headers[key] = None
  18. elif isinstance(value, str):
  19. decoded_headers[key] = value.strip()
  20. elif isinstance(value, list):
  21. decoded_headers[key] = [str(item).strip() for item in value if item is not None]
  22. elif isinstance(value, (int, float)):
  23. decoded_headers[key] = value
  24. else:
  25. decoded_headers[key] = str(value) # Convert to string for consistency
  26. return decoded_headers
  27. if __name__ == '__main__':
  28. # Example Usage & Edge Case Handling
  29. headers1 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": "Bearer abc"}
  30. decoded_headers1 = decode_response_headers(headers1)
  31. print(f"Headers 1: {decoded_headers1}")
  32. headers2 = {"Content-Type": None, "Cache-Control": "no-cache", "Authorization": None}
  33. decoded_headers2 = decode_response_headers(headers2)
  34. print(f"Headers 2: {decoded_headers2}")
  35. headers3 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": [None, "Bearer abc"]}
  36. decoded_headers3 = decode_response_headers(headers3)
  37. print(f"Headers 3: {decoded_headers3}")
  38. headers4 = {"Content-Type": "text/html", "Cache-Control": "no-cache", "Authorization": 123}
  39. decoded_headers4 = decode_response_headers(headers4)
  40. print(f"Headers 4: {decoded_headers4}")
  41. headers5 = "not a dictionary"
  42. decoded_headers5 = decode_response_headers(headers5)
  43. print(f"Headers 5: {decoded_headers5}")
  44. headers6 = {"Content-Type": 123, "Cache-Control": "no-cache", "Authorization": "Bearer abc"}
  45. decoded_headers6 = decode_response_headers(headers6)
  46. print(f"Headers 6: {decoded_headers6}")

Add your comment