Consumer-driven response contract
Implement `verify_contract(expectation, response)` — a check of a provider
response against the consumer's expectations (consumer-driven contract).
`expectation` describes only what the client actually reads:
```python
{
"status": 200,
"body": {
"type": "object",
"required": {
"id": "integer",
"customer": {
"type": "object",
"required": {"id": "integer", "email": "string"},
},
"items": {
"type": "array",
"items": {
"type": "object",
"required": {"sku": "string", "qty": "integer"},
},
},
},
"optional": {"coupon": "string", "note": {"type": ["string", "null"]}},
"allow_extra": False,
},
}
```
`response` is the provider answer:
```python
{"status": 200, "body": {...}}
```
The function returns a report:
```python
{"ok": True, "violations": []}
```
or
```python
{
"ok": False,
"violations": [
{"path": "$.body.customer.email", "kind": "missing", "expected": "string"},
{"path": "$.body.id", "kind": "type", "expected": "integer", "actual": "str"},
{"path": "$.body.debug", "kind": "extra", "expected": "absent"},
],
}
```
Rules:
- `status` is compared exactly; a mismatch is a violation with
`kind: "status"`;
- `body` is validated against the schema;
- a schema is a type string (`"string"`, `"integer"`, `"number"`, `"boolean"`,
`"null"`, `"any"`, `"object"`, `"array"`) or an object:
- `"type"` is required;
- for `object`: `required` and `optional` are "field → schema" objects,
`allow_extra` defaults to `true`;
- for `array` in object form: `items` is required and describes every
element; the bare string `"array"` means "any list";
- a type may be a list: `["string", "null"]`; a structural type
(`object`/`array`) may only be combined with `null`;
- a missing required field is a violation with `kind: "missing"`;
- a type mismatch is a violation with `kind: "type"`; `integer` rejects
`bool`, `number` accepts `int` and `float` but rejects `bool`;
- an extra field with `allow_extra: false` is a violation with
`kind: "extra"`; with `allow_extra: true` (the default) provider additions
are allowed;
- do not stop at the first error: return every violation;
- violation order: `status` first, then `required` fields in declaration
order, then present `optional` fields in declaration order, then extra
fields alphabetically; array elements follow their index;
- a response that is not an object, or lacks `status` or `body`, is a
violation, not an exception;
- a malformed `expectation` (unknown type, `required`/`optional` overlap,
non-bool `allow_extra`, `array` without `items`, unexpected keys) raises
`ExpectationError`; the expectation is validated before the response.
A field path looks like `$.body.items[0].qty`.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
How is an absent optional field different from an optional field with the wrong type? And what should happen when the provider adds a field the consumer never declared?