We are given a cryptic prompt: "Synthetic API test harness: golden traces, causality checks, prod parity."
We need to interpret this as a request to design or explain a synthetic API test harness that includes:
- Golden traces: probably means pre-recorded or expected traces of API calls and responses.
- Causality checks: ensuring that the order and timing of calls are consistent with causality (i.e., cause and effect).
- Prod parity: ensuring that the test environment produces the same results as production (or at least consistent with expected behavior).
We are to act as a code expert and generate a response that includes executable code for demonstration.
However, note that the prompt is very brief and abstract. We must decide on a concrete scenario.
Let's assume we are testing a REST API. We'll design a test harness that:
- Uses a set of golden traces (recorded from production or designed by experts) that include the sequence of API calls and expected responses.
- Replays these traces in a test environment and checks that the responses match the golden ones (prod parity).
- Additionally, we want to check causality: for example, if a call depends on a previous call (like using an ID from a previous response), then we must ensure that the dependency is satisfied.
But note: the prompt says "synthetic", so we might be generating synthetic test cases? Or using synthetic data?
Alternatively, we might be building a harness that can take a set of golden traces and then run them against an API, checking both the responses and the causality (i.e., the sequence of calls and their dependencies).
Let's break down:
-
Golden traces: a list of API requests (with method, path, headers, body) and the expected response (status, headers, body). Also, we might have variables that are extracted from responses and used in subsequent requests (like a token or an ID).
-
Causality checks: we need to define a way to express dependencies between requests. For example, request B uses a variable from the response of request A. We must ensure that A is executed before B and that the variable is available.
-
Prod parity: the test environment should behave like production. We are comparing the actual responses to the golden ones. But note: some fields might be dynamic (timestamps, nonces). So we might need to have a way to mask or ignore certain fields.
Approach:
We can design a test harness that reads a configuration (the golden trace) which is a list of steps. Each step has:
- request: method, path, headers (with possible variable placeholders), body (with possible variable placeholders)
- expected_response: status, headers (with possible variable placeholders or matchers), body (with possible variable placeholders or matchers)
- variables: a mapping of variable names that are extracted from this step's response (using JSONPath, for example) to be used in subsequent steps.
We'll also need a way to substitute variables in the request and expected response of subsequent steps.
Steps:
- Parse the golden trace configuration (could be in YAML or JSON).
- For each step in order:
a. Substitute variables in the request (using the current variable context, which is built from previous steps).
b. Send the request to the test API endpoint.
c. Compare the actual response with the expected response (after substituting variables in the expected response? or the expected response might have static values and we compare after substituting the same variables?).
d. Extract variables from the actual response (according to the step's variable extraction rules) and update the variable context.
- If any step fails (response mismatch or variable extraction fails), then the test fails.
Causality is inherently checked by the order of steps and the requirement that a variable must be defined before use.
However, note: the golden trace might have been recorded in production and we are replaying in a test environment. We must ensure that the test environment is in a state that allows the trace to be replayed (maybe we need to set up the database, etc.). That's beyond the scope of the harness? We assume the environment is set up.
Alternatively, we might want to generate synthetic traces? The prompt says "synthetic", which might mean we are generating the traces artificially. But then we wouldn't have golden traces. So maybe we are generating synthetic requests and checking the system's behavior? But then we don't have golden responses.
Let's re-read: "Synthetic API test harness: golden traces, causality checks, prod parity."
It might mean: we are building a test harness that uses synthetic (generated) traces? But then what are golden traces? Maybe we have a set of golden traces that are considered correct and we generate similar synthetic traces? That seems more like fuzzing.
Alternatively, it could be that we are using a set of golden traces (recorded from production) and then we generate synthetic variations (with mutations) and check that the system still behaves consistently (prod parity) and that the causality holds? That sounds like a more advanced test.
Given the ambiguity, let's stick to the simpler interpretation: we have a set of golden traces (pre-recorded) and we want to replay them in a test environment and check for parity and causality.
But note: the word "synthetic" might refer to the fact that we are creating a test harness that is not using live production data but synthetic (or recorded) data.
Let's design a simple example in code.
We'll write a Python script that:
-
Reads a YAML file that defines the golden trace (list of steps).
-
Each step has:
request:
method: GET/POST/etc.
path: /api/resource
headers: { ... } (with variableplaceholders)body:...(with{variable} placeholders, or JSON)
expected_response:
status: 200
headers: { ... }
body: ... (with .data.id # for example
Given the complexity, let's stick to exact match after variable substitution in the request and expected response? But note: the expected response might have been recorded with specific values that are now dynamic (like a token). So we might want to extract variables from the actual response and then compare the rest of the expected response (without the dynamic fields) by substituting the extracted variables? That doesn't make sense because the expected response was recorded at a specific time.
Instead, we can have the golden trace define which fields are dynamic and should be ignored? Or we can have the golden trace define a set of matchers (like a regex for a field).
However, to keep it simple for demonstration, let's assume:
- The golden trace's expected response is exactly what we expect, but we allow variable placeholders in the expected response that are replaced by the current variable context? That would mean that the golden trace was written with variables that are defined in previous steps.
Example:
Step 1:
request: GET /user
expected_response:
status: 200
body: { "id": ${user_id}, "name": "Alice" }
Step 2:
request: GET /user/${user_id}
expected_response:
status: 200
body: { "id": ${user_id}, "name": "Alice" }
But then the expected response in step 2 uses the variable from step1. However, the actual response in step2 should have the same user_id as step1? That's a causality check.
But wait, the golden trace's expected response in step1 has a placeholder for user_id. How do we know what value to expect? We don't, unless we extract it from the actual response of step1 and then substitute it in the expected response of step2? But then the expected response of step1 must have a fixed value for user_id? Or we extract the user_id from step1's response and then use it to build the expected response for step2.
This is getting complicated.
Alternatively, we can separate:
- The golden trace's expected response for step1 is exact (with no variables). We extract the user_id from the actual response of step1 and store it. Then for step2, we build the expected response by substituting the variable in the golden trace's expected response for step2? But then the golden trace for step2 must have a placeholder for user_id? That means the golden trace is written with variables that are defined in previous steps.
So we can design the golden trace as:
steps:
- id: step1
request: ...
expected_response: ... (exact, no variables)
extract_variables:
user_id: $.id
- id: step2
request: ... (with ${user_id})
expected_response: ... (with ${user_id}? but then we are expecting the same user_id as in step1? That's the causality.)
But note: the expected_response of step2 might have other fields that are fixed. We can write:
expected_response:
status: 200
body: { "id": ${user_id}, "name": "Alice" }
Then we substitute ${user_id} with the value extracted from step1. This way, we are checking that step2 returns the same user_id.
However, what if step2 returns a different user_id? Then the test fails. That's a good causality check.
But what if the golden trace was recorded in production and step1 returned a specific user_id (say 123). Then the golden trace for step2 would have:
expected_response:
body: { "id": 123, "name": "Alice" }
and then we wouldn't need a variable. But then if we run the test in a different environment (with different data) we might get a different user_id. So we need the variable substitution to handle that.
So the golden trace must be written in a way that uses variables for any dynamic value that might change between environments? That's a lot of work.
Alternatively, we can have the golden trace store the expected response with variables only for the fields that are expected to be dynamic? And then we substitute with the extracted values? But then we are essentially re-using the extracted values as the expected values? That would only work if the system is deterministic and the same input produces the same output? But that's not always true (e.g., timestamps).
Given the complexity, let's simplify:
We'll assume that the golden trace is recorded in a specific environment (say, production) and we want to replay it in a test environment that is a clone of production (prod parity). Then the responses should be exactly the same. So we don't need variable substitution in the expected response? But then we have the problem of dynamic fields.
Alternatively, we can have the golden trace store the expected response with some fields masked (or ignored). We can define a list of JSON pointers to ignore.
Given the time, let's design a simpler version:
We'll have:
steps:
- request: ... (with variables)
expected_response:
status: 200
body: ... (with variables or exact)
extract_variables: ...
And we'll do:
For each step:
1. Substitute variables in the request (using the current variable context).
2. Send the request.
3. Compare the actual response with the expected_response, but:
- For the body, if the expected_response body has variables (like ${var}), we substitute them with the current variable context and then compare.
- Alternatively, we can have the expected_response body be a JSON that may contain variables, and we substitute and then compare.
But note: the expected_response might have been recorded with a specific value (like a timestamp) that we want to ignore. We can have a separate field in the step called `ignore_fields` that lists JSON pointers to ignore.
Given the complexity, let's stick to exact match after variable substitution, and assume that the golden trace uses variables for any field that might change.
But then we must have the golden trace define all the variables that are used? And we must extract them in the correct order.
This is a typical problem in API testing with recorded traffic.
Given the constraints of this exercise, let's write a simple version that:
- Uses a YAML configuration.
- Supports variable substitution in request and expected response using ${var}.
- Supports extraction of variables from response using JSONPath.
We'll use the `jsonpath_rw` library for JSONPath? Or we can use `jmespath`? Let's use `jsonpath_rw` because it's common.
But note: we are to generate an executable code. We'll write a Python script that uses `requests` and `jsonpath_rw`.
Steps:
1. Parse YAML.
2. Initialize an empty dictionary for variables.
3. For each step:
a. Substitute variables in the request (method, path, headers, body) using the current variables.
b. Send the request.
c. Substitute variables in the expected_response (status, headers, body) using the current variables? Wait, the expected_response might have variables that are defined in this step (from extraction) or previous? Actually, we want to use the current variables (which are from previous steps) to build the expected_response? But then the expected_response might have a variable that we are about to extract? That would be circular.
Let's change: the expected_response should be compared without substituting variables that are to be extracted in this step? Because we are extracting them from the actual response, so we don't know them beforehand.
So we must design the golden trace such that the expected_response for a step does not depend on variables that are extracted in that same step? But it can depend on variables from previous steps.
So we substitute variables in the expected_response using the current variable context (which includes variables from previous steps) and then compare.
Then we extract variables from the actual response (using the extract_variables rules) and update the variable context.
Example:
Step1:
request: GET /user/1
expected_response:
body: { "id": 1, "name": "Alice" }
extract_variables:
user_id: $.id
Step2:
request: GET /user/${user_id}
expected_response:
body: { "id": ${user_id}, "name": "Alice" }
In step2, we substitute ${user_id} with the value extracted from step1 (which is 1). Then we compare the actual response of step2 with the expected body after substitution.
But note: the expected_response of step1 has a fixed id (1). That's fine.
What if step1 returns a different id? Then the extraction will set user_id to that value, and then step2's expected body will be built with that value. But then step2's expected body would be different from the golden trace's expected body? Actually, the golden trace's expected body for step2 has a placeholder ${user_id}. We substitute it with the extracted value from step1. So if step1 returns 2, then we expect step2 to return { "id": 2, "name": "Alice" }? But what if step2 returns the same user as step1? Then it's consistent.
This design assumes that the golden trace is written in a way that the expected_response for a step can have variables that are defined in previous steps.
But then the golden trace must be written with variables for any field that is expected to be the same as a previously extracted value? That's a lot of work.
Alternatively, we can have the golden trace store the expected_response without variables, and then we compare the actual response with the expected_response by:
- For each field in the expected_response, if the value is a string that starts with ${ and ends with }, then we treat it as a variable and compare it to the current variable context? But then we are not substituting, we are checking that the actual response's field equals the variable's value.
That's different: we are not building the expected_response by substitution, but we are matching the actual response against a pattern that includes variable references.
Let's do:
expected_response body is a JSON object. We traverse it and for each value:
if it is a string and matches the pattern ${var}, then we check that the corresponding field in the actual response equals the value of `var` in the current context.
else, we compare the actual response's field to the expected value.
This way, we don't need to substitute in the expected_response, we just use it as a template with variable references.
But then we must have a way to express that a field can be any value? We can use a special value like `*` or a regex.
Given the time, let's stick to the substitution method because it's simpler to implement.
However, note: the expected_response might have a field that is an array or nested object. We need to do recursive substitution.
We'll write a function to recursively substitute variables in a dictionary (or string) using a context.
Steps for substitution:
If the value is a string and contains ${...}, we replace all occurrences of ${var} with the value of var from the context.
If the value is a dict, we recursively substitute for each value.
If the value is a list, we recursively substitute for each element.
Then we compare the actual response (after converting to a comparable form, say JSON) with the substituted expected_response.
But note: the actual response might have fields that are not in the expected_response? We are doing an exact match? We can do a deep equality.
Alternatively, we can do a partial match: the expected_response only specifies the fields we care about? That's common.
Let's do: the expected_response is a JSON that we compare only the specified fields (like a subset). We can use `jsonpatch` or just do a recursive comparison that allows extra fields in the actual response? That's more lenient.
Given the complexity, let's do exact match on the entire response (after substitution) for the body, and exact match for status and headers (with substitution in headers too).
But note: the expected_response might have headers with variables? Yes, same as body.
So we'll do:
- For the response status: exact match (no variables? but we can allow variables? Let's not for simplicity).
- For headers: we compare the actual headers (case-insensitive?) with the expected headers after substitution. We'll do a case-insensitive match for header names? Actually, HTTP headers are case-insensitive. We'll convert both to lower case for comparison.
But note: the expected headers might have a variable in the value? We'll substitute and then compare.
Implementation:
We'll have a function `substitute_variables(obj, context)` that returns a new object with all strings having ${var} replaced by context[var].
Then:
expected_status = step['expected_response']['status']
expected_headers = substitute_variables(step['expected_response'].get('headers', {}), context)
expected_body = substitute_variables(step['expected_response'].get('body', None), context)
Then we compare:
assert actual_response.status_code == expected_status
assert case_insensitive_headers_match(actual_response.headers, expected_headers)
assert actual_response.json() == expected_body # if body is JSON
But note: the body might not be JSON. We'll assume JSON for simplicity.
Extraction:
We have a list of extraction rules in the step:
extract_variables:
- name: user_id
jsonpath: $.id
We'll use jsonpath_rw to extract the value. Then we update the context[user_id] = extracted_value.
If the extraction fails (no match, or multiple matches?) we fail the test.
Now, let's code a simple version.
We'll assume the golden trace YAML looks like:
steps:
- request:
method: GET
path: /api/user/1
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": 1, "name": "Alice" }
extract_variables:
user_id: $.id
- request:
method: GET
path: /api/user/${user_id}
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": ${user_id}, "name": "Alice" }
extract_variables: []
We'll write a script that takes the YAML file and the base URL of the test API.
Steps:
1. Read YAML.
2. context = {}
3. For each step in steps:
substitute request (path, headers, body) using context.
send request.
substitute expected_response (status, headers, body) using context.
compare.
extract variables and update context.
Let's code accordingly.
However, note: the request body might be a string that is JSON or form data. We'll assume JSON for now.
We'll use:
import yaml
import requests
import json
from jsonpath_rw import parse
But note: jsonpath_rw might not be installed. We can use `jmespath` which is more common? Or we can write a simple JSONPath extractor? Let's use `jmespath` because it's simpler and more powerful.
Actually, the prompt says "executable for demonstration". We can choose any library. Let's use `jmespath` because it's one function call.
But wait, the example uses `$.id` which is JSONPath. `jmespath` uses a different syntax. Let's stick to JSONPath because it's more common in the context of JSONPath.
We'll use `jsonpath_rw` if available, but we don't want to require external libraries? We can write a very simple JSONPath that only supports `$` and dot notation? That's too limited.
Given that this is a demonstration, we'll use `jsonpath_rw` and note that it must be installed.
Alternatively, we can use `jmespath` and change the syntax in the example? But the user might expect JSONPath.
Let's use `jsonpath_rw` and in the code we'll do:
from jsonpath_rw import parse
jsonpath_expr = parse(extract_rule) # where extract_rule is like "$.id"
matches = [match.value for match in jsonpath_expr.find(actual_response.json())]
if len(matches) != 1:
raise Exception("Expected exactly one match")
context[variable_name] = matches[0]
But note: the response might not be JSON? We assume JSON.
Now, let's code.
We'll write a class `APITestHarness` that takes the config and base_url.
We'll also handle errors and print nice messages.
Since this is a demonstration, we'll keep it simple.
Let's code:
Note: We must handle the case where the request body is not JSON (like form data). We'll assume the request body is a string that we substitute variables in, and then we send it as is.
Similarly for headers: we substitute variables in the header values.
But note: the headers are a dict, so we substitute each value.
Steps for substitution:
def substitute_variables(data, context):
if isinstance(data, str):
# replace all ${var} with context[var]
# if var not in context, leave as is? or error?
# We'll error if a variable is not found.
import re
pattern = re.compile(r'\$\{([^}]+)\}')
def replace(match):
var_name = match.group(1)
if var_name in context:
return str(context[var_name])
else:
raise KeyError(f"Variable {var_name} not found in context")
return pattern.sub(replace, data)
elif isinstance(data, dict):
return {k: substitute_variables(v, context) for k, v in data.items()}
elif isinstance(data, list):
return [substitute_variables(item, context) for item in data]
else:
return data
But note: the expected_response body might be a string that is not JSON? We assume the body is JSON and we are comparing JSON objects. But what if the body is a string? We'll compare as strings.
Actually, we are going to send the request with `json` parameter if the body is a dict? We'll do:
if request_body is not None:
response = requests.request(method, url, headers=headers, json=request_body)
else:
response = requests.request(method, url, headers=headers)
But note: the request body might be a string that is already JSON? We can do:
if isinstance(request_body, (dict, list)):
response = requests.request(..., json=request_body)
else:
response = requests.request(..., data=request_body)
However, after substitution, the request_body might be a string that is JSON? We can try to parse it? But let's assume that if the original request body in the config is a dict, we use json=, otherwise we use data=.
But after substitution, we might have a string that was originally a dict? We lose the type. So we must remember the original type? Alternatively, we can always use json= and if the body is a string, we try to parse it as JSON? That's not safe.
Let's change: in the config, we specify the request body as a string or a dict. After substitution, if it's a string, we send it as data. If it's a dict or list, we send as json.
But what if the string is JSON? We can try to parse it and if it succeeds, then we send as json? Or we can have a flag.
Given the time, let's assume that the request body in the config is a Python object (dict, list, str, int, etc.) and after substitution we get the same type? But substitution of variables in a string that is JSON will break the JSON structure? For example, if the body is:
{"user_id": "${user_id}"}
and we substitute with user_id=123, we get:
{"user_id": "123"}
which is a string. But if we want the user_id to be a number? Then we must have the variable be a number and the substitution should not quote it? That's a problem.
So we must be careful: the variable substitution returns a string, but we might need a number.
We can try to evaluate the variable as JSON? For example, if the variable value is 123 (an integer) and we are substituting into a JSON string, we want to substitute without quotes? But then the JSON string would become:
{"user_id": 123}
which is valid.
So we can do:
When substituting, if the variable value is not a string, we use json.dumps to convert to a JSON string? But then for a string variable, we would get quotes.
Alternatively, we can have the variable context store the value as a string and then when substituting, we just insert the string. But then for numbers, we would get:
{"user_id": "123"} if the variable is the string "123"
But we want 123 without quotes.
This is a general problem of variable substitution in JSON.
Given the complexity, let's assume that the variable values are strings and we are substituting into a string that is JSON. Then we must be careful about types.
Alternatively, we can build the request body as a Python object (dict) and then use `json` parameter. Then we don't do string substitution on the body? We do:
In the config, the request body is a Python dict that may have strings with ${var}. We then recursively substitute in the dict, and if the substitution results in a string that is a number, we convert it to a number? That's messy.
Let's change the design:
We do variable substitution on the request body as a string? Then we have to parse the substituted string as JSON to send as json? That's two steps.
Alternatively, we can have the request body in the config as a string and we substitute variables in the string, then we parse it as JSON and send as json? But then we are assuming the body is JSON.
Given the time, let's assume:
The request body in the config is a string that is JSON with ${var} placeholders. We substitute the variables (which are strings) and then we parse the resulting string as JSON and send as json.
But then the variable values must be valid JSON fragments? For example, if the variable is 123, we substitute the string "123", which is valid JSON for a number? Actually, in JSON, 123 is a number, and "123" is a string. So if we substitute without quotes, we get 123, which is a number. But if the variable is the string "123", we substitute "123" (with quotes) and then we get a string? That's not what we want.
We can do:
When substituting, we don't add quotes. We just insert the variable value as is (which is a string). Then if the variable value is "123", we insert 123 (without quotes) and then the JSON becomes a number? But the variable value is a string, so we are inserting a string without quotes? That would break the JSON.
Example:
body: {"user_id": ${user_id}}
context: user_id = 123 (as a string)
After substitution: {"user_id": 123} -> valid JSON, user_id is number.
But if user_id = "123", then we get {"user_id": 123} -> still number, but we wanted string? Then we must have the variable value be the string with quotes? That is, user_id = "\"123\""? That's messy.
Given the complexity, let's avoid variable substitution in the body and instead have the body be a Python dict in the YAML and we do the substitution in the dict (recursively) and then send as json. Then the variable values must be of the correct type? We can store the variable values as strings and then when substituting, we try to convert to the appropriate type? That's too hard.
Alternatively, we can have the variable values be strings and when we substitute in the dict, we leave them as strings? Then the API might expect a number and we send a string? That would fail.
So we must have the variable values be of the correct type. How do we get the variable values? From the response of a previous step. The response is parsed as JSON, so the extracted value might be an integer, string, etc. We store that in the context. Then when we substitute in the request body (which is a dict), we replace the placeholder with the actual value (with the correct type). But the placeholder is a string in the dict? We can't have a placeholder that is not a string in the dict.
Example:
In the config:
request:
body:
user_id: ${user_id}
This is a dict with a string value "${user_id}". We want to replace that string with the integer 123.
We can do:
if the value is a string and matches the pattern, we replace it with the variable value (which can be any type).
Then the body becomes:
user_id: 123
which is an integer.
That works.
So we change the substitution function:
If the value is a string and matches the pattern, we replace the entire string with the variable value (which can be any type). But note: the variable value might be a string, integer, list, etc.
Then we don't do string replacement, we do type replacement.
But what if the string is: "user_${user_id}"? Then we want to replace only the variable part? That's more complex.
Given the time, let's assume that the entire value is a placeholder. That is, the value is exactly "${var}". Then we replace the whole value with the variable.
So:
if isinstance(data, str) and data.startswith('${') and data.endswith('}'):
var_name = data[2:-1]
if var_name in context:
return context[var_name]
else:
raise KeyError(...)
else:
# otherwise, we don't do substitution in strings? But we might have a string that contains multiple variables? We said we would only do whole value substitution? That's a limitation.
Given the complexity, let's stick to whole-value substitution for now.
Then the request body in the config must be:
body:
user_id: ${user_id}
and not:
body:
user_id: "user_${user_id}"
Similarly for headers and path.
For the path: we want to substitute the entire path? Or just parts? We can do the same: if the path is a string, we substitute all ${var} in the string? But then we are back to string substitution.
Let's do:
For the path, we do string substitution (because the path is a string) and we replace all ${var} with the string representation of the variable value.
For the body and headers, we do whole-value substitution only? That's inconsistent.
Given the time, let's do:
We'll have two substitution functions:
substitute_in_string(s, context): replaces all ${var} with str(context[var])
substitute_in_obj(obj, context): for dict and list, recursively apply substitute_in_string to string values, and for non-string values, if they are exactly a placeholder string (like "${var}") then replace with the variable value (any type). Otherwise, leave as is.
This is getting too complex.
We need to make a decision for the demo.
Let's simplify:
We'll only support variable substitution in strings (both for request and expected response) and the variables are always strings.
Then we can do:
def substitute_variables(data, context):
if isinstance(data, str):
pattern = re.compile(r'\$\{([^}]+)\}')
return pattern.sub(lambda m: context.get(m.group(1), m.group(0)), data)
elif isinstance(data, dict):
return {k: substitute_variables(v, context) for k, v in data.items()}
elif isinstance(data, list):
return [substitute_variables(item, context) for item in data]
else:
return data
This replaces every occurrence of ${var} with the string value of context[var].
Then for the request body, if we have:
body: {"user_id": "${user_id}"}
and context['user_id'] = 123, then after substitution we have:
body: {"user_id": "123"}
which is a string, not a number. But if the API expects a number, we fail.
We can try to parse the substituted string as JSON? But the body is already a dict (because we parsed the YAML). Actually, the body in the YAML is a string? Or a dict?
In the YAML, we can write:
body: '{"user_id": ${user_id}}'
Then the body is a string. We substitute and get a string, then we send as data? But then we want to send as JSON? We can do:
if the original body in the config is a string, we substitute and then send as data (with content-type application/json?).
Alternatively, we can have the body in the config as a dict, and then we do substitution on the dict? But then we are substituting in the dict values, which are strings? Then we get:
body: {"user_id": "123"}
which is a dict with a string. We can then send as json.
But if the variable is a number, we want the body to be:
{"user_id": 123}
So we must have the variable stored as an integer? But our context stores everything as string? We can store the variable as the actual type from the response.
Then when we substitute in the dict, we replace the string value with the variable value (which might be an integer). Then the dict becomes:
{"user_id": 123}
which is correct.
So we change the substitution function to:
if the value is a string and matches the pattern exactly (the whole string is ${var}), then we replace with the variable value (any type).
otherwise, we do string substitution in the string.
But then for a string that is not exactly a placeholder, we do string substitution.
Example:
body:
user_id: ${user_id} -> replaced with integer 123 -> becomes 123 (integer)
message: "hello ${user_id}" -> replaced with string "hello 123"
That works.
So:
def substitute_variables(data, context):
if isinstance(data, str):
# if the string is exactly a placeholder, replace with variable value (any type)
if data.startswith('${') and data.endswith('}'):
var_name = data[2:-1]
if var_name in context:
return context[var_name]
else:
raise KeyError(...)
else:
pattern = re.compile(r'\$\{([^}]+)\}')
return pattern.sub(lambda m: str(context.get(m.group(1), m.group(0))), data)
elif isinstance(data, dict):
return {k: substitute_variables(v, context) for k, v in data.items()}
elif isinstance(data, list):
return [substitute_variables(item, context) for item in data]
else:
return data
But note: the pattern.sub will replace every occurrence with the string representation of the variable. That's what we want for strings.
Now, for the expected_response, we do the same substitution? Then we compare the actual response (which is a dict from response.json()) with the substituted expected_response.
But note: the actual response might have numbers and strings. We are comparing after substitution, and the substitution might have turned a placeholder into a number? Then we compare a number with a number? That's fine.
However, the expected_response might have a number in the config? We can write in YAML:
body:
id: 123
and then we don't substitute. But if we have:
body:
id: ${user_id}
and user_id is 123 (integer), then after substitution we have:
body:
id: 123 (integer)
which matches.
But what if the expected_response has a string that is exactly "${user_id}"? Then we replace with the integer 123, and then we compare with the actual response's id, which is 123? That works.
But what if the expected_response has a string that contains a placeholder? For example:
body:
message: "user ${user_id}"
and user_id is 123, then we get:
message: "user 123"
and we compare with the actual response's message, which should be "user 123".
This seems consistent.
Now, extraction:
We extract using JSONPath. We assume the response is JSON and we get the value. We store it in the context as the actual type (int, string, etc.).
Then in the next step, when we substitute, if the placeholder is the whole value, we use the actual type.
This should work.
Let's code accordingly.
We'll write:
import yaml
import requests
import re
from jsonpath_rw import parse
Steps:
1. Load config.
2. context = {}
3. for step in config['steps']:
req = step['request']
# substitute in request
method = req['method']
path = substitute_variables(req['path'], context)
headers = substitute_variables(req.get('headers', {}), context)
body = substitute_variables(req.get('body', None), context)
# send request
url = base_url + path
if body is not None:
response = requests.request(method, url, headers=headers, json=body)
else:
response = requests.request(method, url, headers=headers)
# check status
expected_status = step['expected_response']['status']
if response.status_code != expected_status:
raise AssertionError(f"Step {step_name} status code mismatch: expected {expected_status}, got {response.status_code}")
# check headers
expected_headers = substitute_variables(step['expected_response'].get('headers', {}), context)
for key, expected_value in expected_headers.items():
actual_value = response.headers.get(key)
if actual_value != expected_value:
raise AssertionError(f"Step {step_name} header {key} mismatch: expected {expected_value}, got {actual_value}")
# check body
if 'body' in step['expected_response']:
expected_body = substitute_variables(step['expected_response']['body'], context)
actual_body = response.json()
if expected_body != actual_body:
raise AssertionError(f"Step {step_name} body mismatch: expected {expected_body}, got {actual_body}")
# extract variables
for var_name, jsonpath_expr in step.get('extract_variables', {}).items():
jsonpath = parse(jsonpath_expr)
matches = [match.value for match in jsonpath.find(actual_body)]
if len(matches) != 1:
raise AssertionError(f"Step {step_name} extraction for {var_name}: expected exactly one match, got {len(matches)}")
context[var_name] = matches[0]
4. If all steps pass, print success.
But note: the expected_response might not have a body? Then we skip body check.
Also, we are doing exact match on the entire body. What if the body has extra fields? We might want to allow that? We can do a subset match? But for simplicity, exact.
Given the time, we'll go with this.
Now, we must write a sample YAML and a sample test.
Let's write:
base_url: http://localhost:5000
steps:
- request:
method: GET
path: /api/user/1
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": 1, "name": "Alice" }
extract_variables:
user_id: $.id
- request:
method: GET
path: /api/user/${user_id}
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": ${user_id}, "name": "Alice" }
extract_variables: {}
We assume the API is running and returns the expected data.
Now, let's code the script.
We'll call it `test_harness.py` and take two arguments: the YAML file and the base URL.
But for simplicity, we'll hardcode the base_url in the YAML? Or we can pass it as an argument.
Let's pass the base_url as a command line argument and the YAML file as the first argument.
Alternatively, we can have the base_url in the YAML.
We'll do:
config = yaml.safe_load(open(yaml_file))
base_url = config.get('base_url', '')
steps = config['steps']
Then we run the steps.
Let's code accordingly.
We must handle errors and print which step fails.
We'll wrap each step in a try/except and print the step index.
Now, note: the extraction uses JSONPath. We must install `jsonpath_rw`. We'll note that in the requirements.
But for the demo, we can write a fallback? Given the time, we'll assume it's installed.
Let's code.
We'll write:
#!/usr/bin/env python3
import yaml
import requests
import re
import sys
from jsonpath_rw import parse
def substitute_variables(data, context):
if isinstance(data, str):
# if the string is exactly a placeholder, replace with variable value (any type)
if data.startswith('${') and data.endswith('}'):
var_name = data[2:-1]
if var_name in context:
return context[var_name]
else:
raise KeyError(f"Variable {var_name} not found in context")
else:
pattern = re.compile(r'\$\{([^}]+)\}')
def replace(match):
var_name = match.group(1)
if var_name in context:
return str(context[var_name])
else:
return match.group(0) # leave as is if not found? or error? Let's error.
# But we might want to allow missing variables? No, we should error.
# Actually, we should error if a variable is not found.
# So we change:
if var_name not in context:
raise KeyError(f"Variable {var_name} not found in context")
return str(context[var_name])
return pattern.sub(replace, data)
elif isinstance(data, dict):
return {k: substitute_variables(v, context) for k, v in data.items()}
elif isinstance(data, list):
return [substitute_variables(item, context) for item in data]
else:
return data
def main():
if len(sys.argv) < 2:
print("Usage: test_harness.py <config.yaml> [base_url]")
sys.exit(1)
config_file = sys.argv[1]
base_url = sys.argv[2] if len(sys.argv) > 2 else None
with open(config_file) as f:
config = yaml.safe_load(f)
if base_url is None:
base_url = config.get('base_url')
if base_url is None:
print("Base URL not provided and not in config")
sys.exit(1)
steps = config['steps']
context = {}
for i, step in enumerate(steps):
step_name = step.get('name', f'Step {i+1}')
print(f"Running {step_name}...")
try:
req = step['request']
method = req['method']
path = substitute_variables(req['path'], context)
headers = substitute_variables(req.get('headers', {}), context)
body = substitute_variables(req.get('body', None), context)
url = base_url.rstrip('/') + '/' + path.lstrip('/')
if body is not None:
response = requests.request(method, url, headers=headers, json=body)
else:
response = requests.request(method, url, headers=headers)
# Check status
expected_status = step['expected_response']['status']
if response.status_code != expected_status:
raise AssertionError(f"Status code mismatch: expected {expected_status}, got {response.status_code}")
# Check headers
expected_headers = substitute_variables(step['expected_response'].get('headers', {}), context)
for key, expected_value in expected_headers.items():
actual_value = response.headers.get(key)
if actual_value != expected_value:
raise AssertionError(f"Header {key} mismatch: expected {expected_value}, got {actual_value}")
# Check body
if 'body' in step['expected_response']:
expected_body = substitute_variables(step['expected_response']['body'], context)
actual_body = response.json()
if expected_body != actual_body:
raise AssertionError(f"Body mismatch: expected {expected_body}, got {actual_body}")
# Extract variables
for var_name, jsonpath_expr in step.get('extract_variables', {}).items():
jsonpath = parse(jsonpath_expr)
matches = [match.value for match in jsonpath.find(actual_body)]
if len(matches) != 1:
raise AssertionError(f"Extraction for {var_name}: expected exactly one match, got {len(matches)}")
context[var_name] = matches[0]
print(f"{step_name} passed.")
except Exception as e:
print(f"{step_name} failed: {e}")
sys.exit(1)
print("All steps passed.")
if __name__ == '__main__':
main()
This is a simple version.
Limitations:
- We assume the response body is JSON. If not, we call response.json() and it might fail.
- We do exact match on the entire body. We might want to allow partial match.
- We don't handle the case where the request body is not JSON (like form data). We always use json= parameter. We can change to:
if body is not None:
# If the body is a string, we send as data? But we want to set content-type?
# Alternatively, we can check the headers for content-type?
# Let's change: if the body is a string, we send as data, otherwise as json.
if isinstance(body, str):
response = requests.request(method, url, headers=headers, data=body)
else:
response = requests.request(method, url, headers=headers, json=body)
else:
response = requests.request(method, url, headers=headers)
But note: after substitution, the body might be a string even if originally it was a dict? We don't have the original type. So we must decide: if the original body in the config is a string, we treat it as string? But after substitution, it might become a dict? That's unlikely because substitution of a variable that is a dict into a string? We don't allow that.
We can do:
original_body = req.get('body')
if original_body is None:
body = None
else:
# We do substitution on the original body (which can be any type) and then we check the type of the result.
body = substitute_variables(original_body, context)
if isinstance(body, str):
# send as data
response = requests.request(..., data=body)
else:
response = requests.request(..., json=body)
But what if the original body is a dict and after substitution it becomes a string? That would happen if the entire dict is replaced by a string? That's an error in the test design.
We'll assume that the type of the body after substitution is the same as the original? Not necessarily.
Given the complexity, we'll assume the body in the config is either a string (which we send as data) or a dict/list (which we send as json). And we don't change the type during substitution? Actually, we might: if the entire body is a placeholder, then we replace with a variable that might be a string, dict, etc.
So we change: after substitution, if the body is a string, we send as data, otherwise as json.
But then if the body is a string that is JSON, we are sending it as data with content-type? We are not setting content-type? The headers might set content-type.
We'll leave it to the user to set the correct content-type in headers.
Given the time, we'll keep it simple and always use json= if body is not None and not a string? Actually, we can do:
if body is None:
response = requests.request(...)
elif isinstance(body, str):
response = requests.request(..., data=body)
else:
response = requests.request(..., json=body)
But note: if body is a string and we want to send as JSON, we must set content-type to application/json. We don't do that automatically.
We'll leave it as is.
Now, let's test with a simple example.
We assume the API is at http://localhost:5000 and has:
GET /api/user/1 -> { "id": 1, "name": "Alice" }
GET /api/user/1 -> same
We write a config.yaml:
base_url: http://localhost:5000
steps:
- request:
method: GET
path: /api/user/1
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": 1, "name": "Alice" }
extract_variables:
user_id: $.id
- request:
method: GET
path: /api/user/${user_id}
headers: {}
body: null
expected_response:
status: 200
headers: { "Content-Type": "application/json" }
body: { "id": ${user_id}, "name": "Alice" }
extract_variables: {}
Then we run:
python test_harness.py config.yaml
This should work.
But note: the second step's expected body has ${user_id} which will be replaced by 1 (from the first step). Then we compare with the actual response, which should be { "id": 1, "name": "Alice" }.
This is a simple causality check: we are using the user_id from the first step in the second step.
Also, we are checking prod parity: the responses must match the golden ones.
This meets the requirements.
However, note: the golden trace is recorded in production and we are replaying in test. The test environment must have the same data? We assume it does.
This is a simple demonstration.
We must note that this is a minimal version and not production-ready (error handling, logging, etc.).
Let's output the code accordingly.
We'll write the code as a single script.
But note: the prompt says "Synthetic API test harness". Our harness is not generating synthetic traces, it's using pre-recorded ones. But the word "synthetic" might mean we are creating a test harness that is synthetic (i.e., not using real production data but synthetic data). We are using golden traces, which are recorded from production? Or they can be synthetic? The term is ambiguous.
Given the prompt, we have met the requirements: golden traces (the YAML), causality checks (by using variables from previous steps), and prod parity (by comparing responses).
We'll output the code.
Note: We must include the necessary imports and the code must be executable.
Let's write the code accordingly.
We'll also add a note that the `jsonpath_rw` library must be installed.
We can do:
pip install jsonpath-rw pyyaml requests
Now, the code:</think>
I'll design a synthetic API test harness that addresses golden traces, causality checks, and production parity. This is a comprehensive testing framework for API validation.
Core Architecture
"""
Synthetic API Test Harness
Features: Golden Traces, Causality Checks, Production Parity
"""
import json
import time
import hashlib
import logging
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, field
from datetime import datetime
from abc import ABC, abstractmethod
import requests
from requests import Response
import yaml
from jsonschema import validate, ValidationError
from jsonpath_ng import parse as jsonpath_parse
import pandas as pd
from collections import defaultdict
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class GoldenTrace:
"""
Immutable golden trace representing expected API behavior.
Stored as canonical JSON with metadata for replayability.
"""
trace_id: str
api_endpoint: str
method: str
request_hash: str # SHA256 of canonical request
response_schema: Dict[str, Any] # JSON Schema for validation
response_example: Dict[str, Any] # Example valid response
temporal_constraints: Dict[str, Any] = field(default_factory=dict)
causality_dependencies: List[str] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.utcnow)
environment: str = "production"
tags: List[str] = field(default_factory=list)
def validate_response(self, actual_response: Dict[str, Any]) -> bool:
"""Validate actual response against golden trace schema"""
try:
validate(instance=actual_response, schema=self.response_schema)
return True
except ValidationError as e:
logger.error(f"Schema validation failed: {e.message}")
return False
def calculate_response_hash(self, response: Dict[str, Any]) -> str:
"""Calculate deterministic hash of response (ignoring timestamps)"""
normalized = self._normalize_for_hashing(response)
return hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest()
def _normalize_for_hashing(self, data: Any) -> Any:
"""Remove volatile fields for hash comparison"""
if isinstance(data, dict):
return {k: self._normalize_for_hashing(v)
for k, v in data.items()
if k not in ['timestamp', 'request_id', 'nonce', 'created_at']}
elif isinstance(data, list):
return [self._normalize_for_hashing(item) for item in data]
return data
@dataclass
class CausalityEvent:
"""Represents a causal relationship between API calls"""
cause_trace_id: str
effect_trace_id: str
relationship_type: str # "predecessor", "depends_on", "triggers"
delay_ms: Optional[int] = None # Expected temporal constraint
state_transition: Optional[str] = None # E.g., "pending→completed"
class SyntheticHarness:
"""
Main test harness coordinating golden traces, causality, and prod parity.
"""
def __init__(self,
prod_api_base: str,
test_api_base: str,
golden_traces_dir: str = "./golden_traces"):
self.prod_api_base = prod_api_base.rstrip('/')
self.test_api_base = test_api_base.rstrip('/')
self.golden_traces_dir = golden_traces_dir
self.golden_traces: Dict[str, GoldenTrace] = {}
self.causality_graph = defaultdict(list)
self.telemetry_store = []
def load_golden_traces(self, pattern: str = "*.yaml") -> None:
"""Load golden traces from directory"""
# Implementation would scan directory and load YAML/JSON files
logger.info(f"Loading golden traces from {self.golden_traces_dir}")
def record_prod_trace(self,
request_data: Dict[str, Any],
response: Response,
endpoint: str,
method: str) -> GoldenTrace:
"""
Capture a trace from production for golden set creation.
"""
trace_id = hashlib.sha256(
f"{method}{endpoint}{time.time()}".encode()
).hexdigest()[:16]
# Extract response structure
try:
response_json = response.json()
except:
response_json = {"raw": response.text}
# Generate JSON Schema from example (simplified)
schema = self._infer_schema(response_json)
golden_trace = GoldenTrace(
trace_id=trace_id,
api_endpoint=endpoint,
method=method,
request_hash=hashlib.sha256(
json.dumps(request_data, sort_keys=True).encode()
).hexdigest(),
response_schema=schema,
response_example=response_json,
environment="production"
)
self.golden_traces[trace_id] = golden_trace
return golden_trace
def _infer_schema(self, data: Any) -> Dict[str, Any]:
"""Simple schema inference (use libraries like pydantic for production)"""
if isinstance(data, dict):
return {
"type": "object",
"properties": {
k: self._infer_schema(v) for k, v in data.items()
}
}
elif isinstance(data, list) and data:
return {
"type": "array",
"items": self._infer_schema(data[0])
}
return {"type": type(data).__name__}
def validate_causality_chain(self,
trace_sequence: List[GoldenTrace]) -> List[CausalityEvent]:
"""
Validate causal relationships between traces.
Returns list of causality violations.
"""
violations = []
for i, trace in enumerate(trace_sequence[1:], 1):
prev_trace = trace_sequence[i-1]
# Check declared dependencies
for dep in trace.causality_dependencies:
if dep not in [t.trace_id for t in trace_sequence[:i]]:
violations.append(
CausalityEvent(
cause_trace_id=dep,
effect_trace_id=trace.trace_id,
relationship_type="missing_dependency",
delay_ms=None
)
)
# Check temporal constraints (if any)
if trace.temporal_constraints.get('min_delay_after'):
# Would need actual timestamps from execution
pass
return violations
def run_parity_test(self,
trace: GoldenTrace,
test_env_params: Optional[Dict] = None) -> Dict[str, Any]:
"""
Run same trace against test environment and compare with golden.
Returns detailed comparison report.
"""
# Replay request in test environment
test_url = f"{self.test_api_base}{trace.api_endpoint}"
try:
test_response = requests.request(
method=trace.method,
url=test_url,
# Include any needed context from test_env_params
timeout=10
)
test_data = test_response.json()
except Exception as e:
return {
"trace_id": trace.trace_id,
"status": "error",
"error": str(e),
"parity": False
}
# Compare with golden
report = {
"trace_id": trace.trace_id,
"golden_hash": trace.calculate_response_hash(trace.response_example),
"test_hash": trace.calculate_response_hash(test_data),
"schema_match": trace.validate_response(test_data),
"exact_match": trace.response_example == test_data,
"normalized_match": trace.calculate_response_hash(trace.response_example) ==
trace.calculate_response_hash(test_data),
"response_size_delta": len(json.dumps(test_data)) - len(json.dumps(trace.response_example)),
"timestamp": datetime.utcnow().isoformat()
}
# Identify differences
if not report["normalized_match"]:
report["differences"] = self._compute_diff(
trace.response_example,
test_data
)
return report
def _compute_diff(self, golden: Dict, actual: Dict) -> List[Dict]:
"""Compute structured diff between responses"""
differences = []
golden_flat = self._flatten_dict(golden)
actual_flat = self._flatten_dict(actual)
all_keys = set(golden_flat.keys()) | set(actual_flat.keys())
for key in all_keys:
g_val = golden_flat.get(key)
a_val = actual_flat.get(key)
if g_val != a_val:
differences.append({
"path": key,
"golden": g_val,
"actual": a_val,
"type": "value_mismatch"
})
return differences
def _flatten_dict(self, d: Dict, parent_key: str = '', sep: str = '.') -> Dict:
"""Flatten nested dict for diff comparison"""
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(self._flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def execute_synthetic_workflow(self,
workflow: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Execute a synthetic workflow with causality enforcement.
Args:
workflow: List of steps, each containing:
- trace_id: Golden trace to execute
- depends_on: List of trace_ids that must complete first
- input_mapping: Map variables from previous outputs
"""
results = []
context = {} # Shared state between steps
execution_order = self._topological_sort(workflow)
for step in execution_order:
trace_id = step['trace_id']
trace = self.golden_traces.get(trace_id)
if not trace:
raise ValueError(f"Golden trace {trace_id} not found")
# Check dependencies
for dep in step.get('depends_on', []):
if dep not in context:
raise RuntimeError(f"Dependency {dep} not satisfied for {trace_id}")
# Apply input mapping from context
request_context = self._apply_mapping(step.get('input_mapping', {}), context)
# Execute with context
result = self._execute_with_context(trace, request_context)
results.append(result)
# Update context with outputs
if 'output_mapping' in step:
context.update(
self._extract_outputs(result['response'], step['output_mapping'])
)
return {
"workflow_id": hashlib.sha256(str(workflow).encode()).hexdigest()[:16],
"results": results,
"context_snapshot": context,
"causality_valid": len(self.validate_causality_chain(
[self.golden_traces[s['trace_id']] for s in execution_order]
)) == 0
}
def _topological_sort(self, workflow: List[Dict]) -> List[Dict]:
"""Sort workflow steps respecting dependencies"""
# Simple implementation - use networkx for complex workflows
return sorted(workflow, key=lambda x: len(x.get('depends_on', [])))
def _apply_mapping(self, mapping: Dict, context: Dict) -> Dict:
"""Apply variable mapping from context to request parameters"""
result = {}
for key, expr in mapping.items():
# Simple expression: context['var']
if expr.startswith('context.') and expr[8:] in context:
result[key] = context[expr[8:]]
else:
result[key] = expr
return result
def _extract_outputs(self, response: Dict, mapping: Dict) -> Dict:
"""Extract values from response using JSONPath"""
extracted = {}
for key, jsonpath_expr in mapping.items():
try:
jsonpath = jsonpath_parse(jsonpath_expr)
matches = [match.value for match in jsonpath.find(response)]
extracted[key] = matches[0] if matches else None
except Exception as e:
logger.warning(f"JSONPath extraction failed for {jsonpath_expr}: {e}")
return extracted
def generate_synthetic_traces(self,
template: Dict[str, Any],
count: int = 100,
variance_rules: Optional[Dict] = None) -> List[GoldenTrace]:
"""
Generate synthetic golden traces from a template.
Useful for load testing and edge case discovery.
"""
synthetic_traces = []
for i in range(count):
# Apply variance rules to generate variations
variant = self._apply_variance(template, variance_rules, i)
trace = GoldenTrace(
trace_id=f"synthetic_{i:04d}",
api_endpoint=variant['endpoint'],
method=variant['method'],
request_hash=hashlib.sha256(
json.dumps(variant['request'], sort_keys=True).encode()
).hexdigest(),
response_schema=variant['schema'],
response_example=variant['example_response'],
tags=["synthetic", "generated"]
)
synthetic_traces.append(trace)
return synthetic_traces
def _apply_variance(self,
template: Dict,
rules: Optional[Dict],
seed: int) -> Dict:
"""Apply variance rules to template (simplified)"""
# In reality, would use property-based testing libraries
import random
random.seed(seed)
variant = template.copy()
# Example: vary numeric ranges
if rules and 'numeric_variance' in rules:
for field, (min_val, max_val) in rules['numeric_variance'].items():
if field in variant['example_response']:
variant['example_response'][field] = random.randint(min_val, max_val)
return variant
# Example Usage
if __name__ == "__main__":
# Initialize harness
harness = SyntheticHarness(
prod_api_base="https://api.production.example.com",
test_api_base="https://api.staging.example.com"
)
# Load golden traces (assumes YAML files in directory)
# harness.load_golden_traces()
# Example: Manual golden trace creation
user_api_trace = GoldenTrace(
trace_id="user_get_001",
api_endpoint="/v1/users/123",
method="GET",
request_hash="a1b2c3...",
response_schema={
"type": "object",
"properties": {
"id": {"type": "integer"},
"email": {"type": "string", "format": "email"},
"created_at": {"type": "string", "format": "date-time"}
},
"required": ["id", "email"]
},
response_example={
"id": 123,
"email": "user@example.com",
"created_at": "2024-01-15T10:30:00Z"
},
causality_dependencies=["auth_001"], # Must authenticate first
tags=["user", "read"]
)
# Run parity test
parity_report = harness.run_parity_test(user_api_trace)
print(f"Parity Report: {json.dumps(parity_report, indent=2)}")
# Example workflow with causality
workflow = [
{
"trace_id": "auth_001",
"depends_on": []
},
{
"trace_id": "user_get_001",
"depends_on": ["auth_001"],
"input_mapping": {
"user_id": "context.user_id" # From previous step
},
"output_mapping": {
"user_id": "$.id" # Extract for next steps
}
},
{
"trace_id": "order_create_001",
"depends_on": ["user_get_001"],
"input_mapping": {
"user_id": "context.user_id",
"items": "static:[{sku:'ABC', qty:1}]"
}
}
]
workflow_result = harness.execute_synthetic_workflow(workflow)
print(f"Workflow result: {workflow_result['causality_valid']}")
Key Features Explained
1. Golden Traces
- Immutable records of expected API behavior
- Include request hash, response schema, and examples
- Support temporal constraints and causality metadata
- Can be captured from production or generated synthetically
2. Causality Checks
- Dependency graph validation (
depends_on fields)
- Temporal constraint verification
- State transition tracking
- Topological sorting for execution order
3. Production Parity
- Exact/normalized response comparison
- JSON Schema validation
- Hash-based equivalence checking (ignoring volatile fields)
- Detailed diff reporting
Example Golden Trace YAML Format
trace_id: "payment_001"
api_endpoint: "/v1/payments"
method: "POST"
request_hash: "e3b0c44298fc1c149afbf4c8996fb924..."
response_schema:
type: object
properties:
payment_id:
type: string
pattern: "^pay_[a-f0-9]{24}$"
status:
type: string
enum: ["pending", "completed", "failed"]
amount:
type: number
minimum: 0
response_example:
payment_id: "pay_5f3a1b2c4d5e6f7a8b9c0d1e"
status: "completed"
amount: 99.99
causality_dependencies:
- "order_001"
- "user_auth_002"
temporal_constraints:
max_duration_ms: 5000
tags:
- "payment"
- "critical"
Deployment Considerations
# Enhanced version for production
class ProductionReadyHarness(SyntheticHarness):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rate_limiter = RateLimiter()
self.circuit_breaker = CircuitBreaker()
self.telemetry_client = TelemetryClient()
def execute_with_observability(self, trace: GoldenTrace):
"""Execute with full observability (metrics, traces, logs)"""
with self.circuit_breaker:
with self.rate_limiter:
start_time = time.time()
result = self.run_parity_test(trace)
duration = (time.time() - start_time) * 1000
# Emit telemetry
self.telemetry_client.emit({
"trace_id": trace.trace_id,
"duration_ms": duration,
"parity": result.get('normalized_match', False),
"environment": "test",
"timestamp": datetime.utcnow().isoformat()
})
return result
Testing the Harness
# test_harness.py
def test_causality_violation():
"""Test that missing dependency is detected"""
harness = SyntheticHarness("prod", "test")
# Create traces with dependency
trace_a = GoldenTrace("a", "/endpoint", "GET", "...", {}, {})
trace_b = GoldenTrace("b", "/endpoint2", "POST", "...", {}, {})
trace_b.causality_dependencies = ["nonexistent"]
workflow = [
{"trace_id": "b", "depends_on": ["nonexistent"]}
]
try:
harness.execute_synthetic_workflow(workflow)
assert False, "Should have raised dependency error"
except RuntimeError as e:
assert "not satisfied" in str(e)
def test_prod_parity():
"""Test parity detection with modified response"""
harness = SyntheticHarness("prod", "test")
golden = GoldenTrace(
"test", "/users", "GET", "...",
response_schema={"type": "object"},
response_example={"id": 1, "name": "Alice"}
)
# Simulate test environment with different field order
class MockResponse:
def json(self):
return {"name": "Alice", "id": 1} # Same data, different order
# Would need to mock requests - simplified
# report = harness.run_parity_test(golden)
# assert report['normalized_match'] == True
Installation Requirements
# requirements.txt
requests>=2.28.0
pyyaml>=6.0
jsonschema>=4.0.0
jsonpath-ng>=1.5.0
pandas>=1.5.0
# Optional for advanced features:
# pydantic>=2.0.0 # Schema validation
# networkx>=3.0 # Complex dependency graphs
# prometheus-client # Metrics
This harness provides:
- Reproducible testing via golden traces
- Causal integrity verification across API workflows
- Production parity checking with intelligent normalization
- Synthetic data generation for edge cases
- Observability-ready architecture
The design separates concerns (trace management, execution, validation) while maintaining a simple API. It's suitable for CI/CD pipelines, chaos engineering, and regression testing against production-like environments.