Sometimes you need something that only looks like a fortress.1
Folly is a mock API, generated from standard API specifications (currently OpenAPI-only), that can set up mock scenarios based on manual configuration or Arazzo specifications.
Folly mocks the Equinix APIs. Its goal is integration tests for API clients, for example the Equinix Terraform provider. A test selects an Arazzo workflow and an outcome. Folly then answers the client's calls in the order that the workflow describes.
Status: Folly serves mock scenarios for success and failure outcomes. See DEVELOPMENT.md for the plan.
| In scope | Not in scope (later) |
|---|---|
| Specs from the Equinix API catalog | Explicit mock configuration (hand-written paths and bodies) |
| Mock scenarios from Arazzo workflows | Warn-only mode for validation mismatches |
| Success and failure outcomes | A 418 response for mismatches |
| Loop control (a count of polls, or a time, before the loop ends) | Parallel sessions |
Token flow as its own scenario (client_credent
F438
ials) |
STS token exchange |
| Prism request and response validation, Prism failure behavior | Specs other than OpenAPI 3.x (Swagger 2, AsyncAPI) |
Folly does not invent new failure modes. When a request or response does not match the spec, Folly uses the behavior and the error templates of Prism. See "Validation behavior".
https://docs.equinix.com/.well-known/api-catalog is an RFC 9727 linkset (application/linkset+json). Each API has one service-desc link to an OpenAPI YAML file, for example https://docs.equinix.com/api-catalog/fabricv4/openapi.yaml (OpenAPI 3.0.3, 2.8 MB, server https://api.equinix.com). The catalog does not list any Arazzo documents. Most linked descriptions are OpenAPI 3.x files. Some are Swagger 2.0 files, and one entry (emgv1) is an AsyncAPI file. Folly supports OpenAPI 3.x only, so folly sync skips the other kinds and logs each skip. Arazzo does not list Swagger 2 as a source, and teams should move their APIs to OpenAPI 3.
Equinix does not publish Arazzo documents. This repository holds them in flows/. We write them by reading the client code (Terraform provider source) and the OpenAPI spec.
| File | Content |
|---|---|
flows/common/authenticate.arazzo.yaml |
authenticate: get a bearer token (POST /oauth2/v1/token, client_credentials grant). |
flows/fabric-cloud-router.arazzo.yaml |
Lifecycle of the equinix_fabric_cloud_router resource. It does not get a token. |
Authentication is a separate flow, and Folly mocks it as a separate scenario. The reason is in the provider code (internal/config/config.go and extensions/equinixoauth2 in equinix-sdk-go). The provider has three ways to get a token:
| Method | Calls the token API? | Folly support |
|---|---|---|
client_credentials through equinixoauth2 (most common) |
Yes. POST /oauth2/v1/token, when the provider needs its first token and again after the token expires. |
First version |
Static token (EQUINIX_API_TOKEN) |
No | Works with no auth scenario |
STS token exchange (sts.eqix.equinix.com) |
Yes, but on the STS API (stsv1 in the catalog) |
Later |
The token call happens at a time that the resource flow does not control. A resource flow must not contain it.
Workflows in fabric-cloud-router.arazzo.yaml:
| Workflow | Calls |
|---|---|
provisionCloudRouter |
createCloudRouter, poll getCloudRouterByUuid until PROVISIONED, one more read |
updateCloudRouterName |
wait until PROVISIONED, updateCloudRouterByUuid (JSON Patch), poll until PROVISIONED, read |
deprovisionCloudRouter |
deleteCloudRouterByUuid, poll until DEPROVISIONED |
cloudRouterLifecycle |
the three workflows above in order (one Terraform apply, update, destroy cycle) |
Why this resource: it has all the client behavior that Folly must support. It has a create, an update, and a delete. Each change ends in a polling loop on the state field. The GET response changes between polls, and later requests reuse a value from an earlier response (uuid).
Source of the flow: equinix/resource_fabric_cloud_router.go in the provider. The retryAfter and retryLimit values in the flow describe the provider (30-second delay, 10-minute timeout). Folly ignores them.
Check the files with redocly lint. It validates the Arazzo structure only.
API client (Terraform provider)
| HTTP
v
+------------------------------------------------------------+
| Folly |
| |
| Router ---> Scenario engine ---> Response builder |
| | (Arazzo state (Prism mock body, |
| | machine, loops) patched by criteria) |
| v | |
| Prism instance per spec <---------------+ |
| (validate request, mock, validate response) |
| |
| Spec store (specs/ + lockfile) <-- folly sync |
+------------------------------------------------------------+
- Spec store and
folly sync.folly syncreads the catalog, downloads eachservice-descfile tospecs/, and writesspecs/folly-specs.lock.jsonwith the URL and the SHA-256 checksum of each file. Folly starts fromspecs/and needs no network. If any download or check fails,folly syncchanges nothing on disk. - Router. Folly chooses the spec by the method and the path of the request. It ignores the host, because the catalog APIs run on different hosts and none of them has a base path. If two specs have the same method and path, Folly refuses to start. If two specs match a path, the route with more fixed path segments wins.
- Prism. Folly uses
@stoplight/prism-httpas a library, with one instance per spec. Prism validates the request, builds a mock response, and validates the response. Folly does not write its own validator. - Scenario engine. It loads the Arazzo workflow and builds a state machine. See the next section.
- Response builder. It starts from the Prism mock body for the chosen status code. It then sets the fields that the step criteria require (for example
state), and it keeps values consistent across steps (for exampleuuid). Prism validates the final body.
folly sync [--out specs] [--catalog <url>] [--only fabricv4,accesstokenv1]
folly check [--out specs]
folly serve [--out specs] [--only fabricv4,accesstokenv1] [--port 4010] [--host 127.0.0.1]
syncdownloads the specs.--onlylimits it to the named APIs.checkcompares the files in the spec directory with the lock file. It uses no network. It fails if a file is missing or changed.serveloads the specs, checks them against the lock file, and starts the mock server.--config <file>adds scenarios. It uses no network. It listens on127.0.0.1unless you set--host. Point the client at it: the Terraform provider uses theendpointargument (EQUINIX_API_ENDPOINT) for the API andsts_endpointfor STS. Folly logs each request and each Prism violation.GET /__folly/healthanswers 200 when Folly is ready. A CI job can wait for it.- Responses that Folly sends for an invalid request or an unknown path are Prism problem-details responses. A path that no loaded spec describes gets a 404.
Folly acts as the server side of the workflow. The Arazzo document describes what a client does. Folly turns each step into an expected request and a planned response.
| Arazzo element | Folly behavior |
|---|---|
steps in order |
The expected sequence of requests. Nested workflowId steps are expanded in place. |
operationId |
Matches the incoming method and path (through the OpenAPI source description). The url of the source description must be a URL that folly sync wrote to the lock file. |
parameters and requestBody |
Folly compares a request value only when it knows the expected value: an earlier response of Folly ($steps.*.outputs.*) or an input that the configuration sets. A literal in a flow is an example, and Folly does not enforce it. |
successCriteria |
The response to send when the step succeeds. Folly asks Prism for the response with the status code of the criteria, and sets the body fields that the criteria name. |
onFailure with type: retry and criteria |
A loop. Folly sends a response that matches the retry criteria until the configured count or time ends the loop (see "Scenario configuration"). It then sends a response that matches successCriteria. |
outputs |
Folly records the values from the response that it sent. Later steps use them. |
retryAfter, retryLimit |
Ignored. Folly does not wait, and it makes no assumption about how many polls the client sends in a given time. |
Supported conditions: $statusCode == <number> and $response.body#/<json-pointer> == <literal | $inputs.* | $steps.*.outputs.* | $request.*>. $request.body#/<json-pointer> and $request.path.<name>, $request.query.<name>, $request.header.<name> read the request that the client sent. A criterion such as $response.body#/name == $request.body#/name makes the mock echo the value, and a step output such as name: $request.body#/name lets a later criterion echo it again. Real clients need this: a client can compare the API response with its own configuration. Each criteria list must contain a $statusCode condition for a status that the operation documents. Folly refuses to start, and names the problem, when a workflow uses anything else: goto or end actions, onSuccess, operationPath, other criteria types, other operators, or other runtime expressions.
What the client gets:
| Request | Response |
|---|---|
| The next expected request of a run, or a create request that starts a run | The planned response. The run moves on, except while a loop answers "keep waiting". |
| A request that is not valid for the spec | Prism's response for that request (see "Validation behavior"). The scenario does not move on. |
A wrong operation, a wrong value that Folly knows, an id that no run owns, a create request that no match rule accepts, or a call after the workflow has finished |
The 422 problem-details response that Prism generates (UNPROCESSABLE_ENTITY), with the differences in validation. No run moves on. |
A bearer token that the auth scenario did not issue |
The documented 401 of the operation, or a generated 401. |
A YAML file lists scenarios. Each scenario selects one Arazzo workflow. The token flow and the resource flow are separate scenarios. examples/cloud-router.folly.yaml is a complete example for the Cloud Router flows:
specs: ../specs # the directory that `folly sync` wrote, relative to this file
# stateful: false # optional: do not keep the resources that clients create
scenarios:
- name: auth
flow: ../flows/common/authenticate.arazzo.yaml
workflow: authenticate
- name: cloud-router
flow: ../flows/fabric-cloud-router.arazzo.yaml
workflow: cloudRouterLifecycle
auth: auth # accept only bearer tokens that the "auth" scenario issued
inputs: # Folly checks these values in the client requests
name: test-router
newName: test-router-renamed
packageCode: LAB
metroCode: AM
projectId: 44f4c4f8-2f39-494e-838c-d8e640591be5
notificationEmails: [test@example.com]
outcome: success
loops: # one entry for every polling step
provisionCloudRouter.waitProvisioned: { iterations: 3 }
updateCloudRouterName.waitReady: { iterations: 0 }
updateCloudRouterName.waitUpdated: { duration: 90s }
deprovisionCloudRouter.waitDeprovisioned: { iterations: 2 }Start the server with folly serve --config examples/cloud-router.folly.yaml. Folly refuses to start, and lists every problem, when a flow or the configuration is not valid.
Rules for scenarios:
-
Auth scenario. A workflow with one step and no loop repeats. The client can call the token endpoint any number of times, at any time, and Folly answers each call. The token step must have an output
accessToken: $response.body#/<field>. Folly puts a new, unique token in that field of each response. -
auth:binding. If a scenario hasauth: <name>, every request for that scenario must carry a bearer token that the named scenario issued. Any issued token is valid, so a client can get a new token between two steps. Ifauth:is absent, Folly accepts any bearer token that Prism's security check accepts. This covers a client that uses a static token. -
Tolerant reads. A scenario with
tolerantReads: trueanswers aGETthat is not the next step from the resource store, and the scenario does not move on. A test framework can send reads that the flow does not list (for example a refresh between the steps of a test). Without it, Folly answers 422 for such a read when the flow lists the operation. A write that is not the next step always gets the 422. -
Runs. A scenario is a template. Each create request that it accepts starts a run of its workflow, and a run has its own position, its own loop counters, and its own step outputs. Many runs can be active at the same time, so several clients (for example the tests of a test suite that run in parallel) can use one Folly. A request after the first goes to the run that expects it: the id in the path, and the other values that the flow knows, tell the runs apart. A run that has finished is removed, and the next create request starts a new run.
-
match. An operation (method and path) can belong to only one scenario, unless every scenario that uses it has amatchrule. The rule says which create request starts a run of the scenario. It can test values of the request body (JSON pointers), the query, and the headers:- name: network workflow: networkLifecycle match: body: { /name: Ipwan_tf_acc_PFCR } - name: network-mixed workflow: networkCreateDestroy match: body: { /name: Tf_Network_PFCR }
If no scenario accepts a create request, Folly answers 422 and names the rule that each scenario did not meet. Folly refuses to start when two scenarios share an operation and one of them has no
match. An operation that no scenario uses gets the plain Prism response from the spec examples. -
Steps that tie to a run. Every step after the first needs a path parameter with a value from an earlier step or an input (for example
$steps.createRouter.outputs.routerId). Without it Folly cannot tell which run the request belongs to, and it refuses to start. A workflow with one step and no loop (a token request, or a data source) needs none: it has no runs to tell apart. -
Loops.
loopshas one entry for every polling step, named<workflowId>.<stepId>. Folly refuses to start if an entry is missing or names a step that does not poll. There is no default, so a loop cannot run for ever by accident. An entry has one of two forms:iterations: N: the client receives N "keep waiting" responses and then the "done" response, and Folly counts requests only.iterations: 0answers "done" at once.duration: <time>(for example90s): the client receives "keep waiting" responses until the time has passed, and then the "done" response. The time starts at the first request to the polling step. Folly does not predict or check how many requests arrive in that time.- Tradeoff. The clock could instead start at the request that began the change (for example the create call). That start would match a real API more closely, because a real change takes time from the create call and not from the first poll. It would also need a link between the polling step and the step that began the change, and Arazzo does not state that link. A client that polls late sees a longer wait (measured from the create call) than a real API would give, so a test that depends on the total time since the create call can pass or fail for the wrong reason. We chose the simple rule for the first version. We can add a
since: <stepId>option later.
- Tradeoff. The clock could instead start at the request that began the change (for example the create call). That start would match a real API more closely, because a real change takes time from the create call and not from the first poll. It would also need a link between the polling step and the step that began the change, and Arazzo does not state that link. A client that polls late sees a longer wait (measured from the create call) than a real API would give, so a test that depends on the total time since the create call can pass or fail for the wrong reason. We chose the simple rule for the first version. We can add a
-
Outcome.
outcome: successis the default.outcome: failuremakes one step fail:outcome: failure failAt: provisionCloudRouter.createRouter # <workflowId>.<stepId> failWith: 400 # optional
- The steps before
failAtsucceed, with the loops thatloopssets. The stepfailAtanswers with a failure response, every time the client sends the request. The scenario does not move on, so the client cannot reach the later steps. A request for a later step gets the 422 response. failWithis a status code from 400 to 599 that the operation documents. If it is absent, Folly uses the lowest documented 4xx code other than 401 and 403, or else the lowest documented 5xx code. If the operation documents none of these, Folly refuses to start.- The failure response is the example that the spec gives for that status. The text of the example does not always describe the real cause (see "Prism behavior" in
DEVELOPMENT.md). failAtcan name a polling step. The step then fails at the first request, and the loop does not run.loopsneeds entries only for the polling steps that the client can reach, which are the polling steps beforefailAt.failAtcan be absent when the workflow has one step. A failure outcome on the token scenario makes every token call fail, so the client never gets a token. This tests how the client handles a failed login.- Folly still checks the request before it sends a failure response, as for any step.
- The steps before
Folly builds a response in three steps:
- Prism gives the example response that the spec has for the status code.
- The resource store makes the response consistent for the whole run of Folly (see below).
- A scenario, if one owns the operation, sets the status code and the fields that the flow names (
state, and the values that a criterion copies from the request or from an earlier step).
An operation that no scenario uses goes through steps 1 and 2 only.
Resources of a run. Folly keeps the resources that clients create, in memory, until it stops. A resource also keeps the values that a scenario sets in a response (the state, for example), so a later read returns the state that the client last saw:
| Request | Response |
|---|---|
A create (POST to a collection) |
A new resource. Folly generates a new id (a new UUID for an id with the uuid format) and writes it in the links of the body (href). The values that the request sent replace the values of the example. The values that the request did not send come from the example. |
| A read of one resource | The stored values, the same as the create response (and as the last change). An id that Folly did not create gets the 404 that the spec documents. |
PATCH |
A JSON Patch (an array) or a merge patch (an object) changes the stored resource. A patch that cannot be applied gets a 422. |
PUT |
The values of the request replace the stored values. |
ETag header |
When the spec documents an ETag header on a read, a PATCH, or a PUT, Folly sends the revision of the resource: 1 after the create, and 1 more for each change. |
DELETE |
The resource is gone. A later read gets the 404. (In a scenario, the flow decides what a read returns, for example DEPROVISIONING.) |
Folly finds the resource types in the specs. A type is a POST operation on a collection path (/routers) that returns a JSON body, and exactly one path with one more path parameter (/routers/{routerId}) that has a GET, PUT, PATCH, or DELETE. A path with only a POST (for example a file upload to a device) is not a resource. At startup Folly asks Prism for a sample of each success response of the create operation, and it uses the first status whose body has an id property: the property whose value ends the href of the body, or uuid, or id. This matters for an operation that documents more than one success status. Folly then answers a create with that status (for example 201 or 202), because the other status can describe the request and not the resource. A type for which Folly finds no id property keeps no resources, and every operation on it returns the spec example. Folly logs these types at startup. Responses that list resources (a search, or a GET of a collection) are not made from the store yet.
For a type that Folly keeps, a resource that was not created in this run does not exist: a read of an unknown id gets the documented 404. Set stateful: false in the configuration file to turn the store off. Every response is then the spec example, plus what a scenario sets.
A criterion can also set a value that the real API computes and the request does not carry, for example $response.body#/changeLog/createdBy == 'folly'. This is the way to give a test the values that it checks. A path with a number (#/accounts/0/accountName) creates an array. Folly checks the response against the spec, so a value that the spec does not allow (for example a status that is not in the enum) makes Folly answer with a 500 problem response and log the violation. Properties that the spec does not list are allowed, so a flow can also write the shape that a real client reads when the spec differs from the real API.
Folly uses Prism for validation. Prism behaves as follows:
- Invalid request. Prism looks in the spec for a documented response in this order: 422 then 400 (415, 422, 400 for a wrong content type, and 401 for a security failure). It sends the first one that the operation documents, with the example body from the spec. If the operation documents none of them, Prism generates a 422 problem-details response. For
createCloudRouterthe client gets the documented 400. ForgetCloudRouterByUuidthe client gets a generated 422. Prism lists the real violations invalidations.input, and Folly logs them. - Invalid response. In mock mode Prism only reports a violation in
validations.output. It still sends the response. Folly does the same for a response that comes straight from the spec examples: it sends the response and logs a warning. Some catalog examples do not match their own schema, and the client must still get a response. Folly also validates a response that it builds itself (a scenario changes the body, see "How Folly reads an Arazzo workflow"). A violation in such a response means that the flow or the spec has an error. Folly then sends Prism'sVIOLATIONSproblem-details response (status 500) with the violations, and logs them. - Unknown path. Prism returns a 404 error (
NO_PATH_MATCHED_ERROR). - There is no warn mode and no 418 response.
client-tests/ holds tests that run real API clients against Folly. Both need Go and the specs from folly sync. The script clones the provider source at the version in client-tests/terraform-provider/PROVIDER_REF, and it starts Folly for each run.
npm run test:terraform-providerruns the code of the Equinix Terraform provider against the Cloud Router flows. It calls the create, update, and delete functions ofequinix_fabric_cloud_router. It runs Folly once for each case (folly.yamlis the success case, andfolly.<case>.yamlis a failure case). The success case takes about four minutes, because the provider waits 30 seconds before each poll.npm run test:terraform-acceptanceruns the upstream acceptance test of the provider thatclient-tests/terraform-provider/acceptance-tests.txtlists. It runs it the way the provider's CI does:TF_ACC=1 go test, withEQUINIX_API_ENDPOINTpointing at Folly. Folly runs the scenarios of each case inacceptance-cases.json: the success case (the token scenario and theterraformAcceptanceCycleflow with polling loops), and two failure cases. A failure case passes when the test fails with the error that the scenario sends. The runner prints the scenario trace of each case. The test framework downloads the Terraform CLI on its first run.