35 / 65 · 14 API Testing Fundamentals · Error Handling and Environment Management← prev⊞ allnext →☰ Read as one page
5.4Malformed Request Testing
def test_invalid_json_body(api):
"""Sending invalid JSON should return 400, not 500."""
r = requests.post(f"{api._base_url}/users",
data="this is not json",
headers={**api.headers, "Content-Type": "application/json"})
assert r.status_code == 400
def test_wrong_content_type(api):
"""Sending form data to a JSON endpoint should be handled gracefully."""
r = requests.post(f"{api._base_url}/users",
data="name=test&email=test@test.com",
headers={**api.headers, "Content-Type": "application/x-www-form-urlencoded"})
assert r.status_code in (400, 415) # Bad Request or Unsupported Media Type
def test_extra_fields_ignored_or_rejected(api):
"""Unknown fields should be ignored or rejected, not cause errors."""
r = api.post("/users", json={
"name": "Test",
"email": "test@test.com",
"role": "viewer",
"unknown_field": "should be ignored",
"admin_override": True # Potential mass assignment attack
})
assert r.status_code in (201, 400) # Either accepted (ignoring) or rejected
if r.status_code == 201:
# If accepted, verify extra fields were NOT persisted
user = api.get(f"/users/{r.json()['id']}").json()
assert "unknown_field" not in user
assert "admin_override" not in user
def test_extremely_large_payload(api):
"""Very large payloads should be rejected, not crash the server."""
r = api.post("/users", json={
"name": "A" * 1_000_000,
"email": "test@test.com"
})
assert r.status_code in (400, 413) # Bad Request or Payload Too Large