Skip to content

Commit

Permalink
Merge pull request #20 from micovery/feat_mock_oas_command
Browse files Browse the repository at this point in the history
feat: implement mock oas command
  • Loading branch information
micovery authored Oct 30, 2024
2 parents f69787c + 415a35d commit 116eb07
Show file tree
Hide file tree
Showing 19 changed files with 2,341 additions and 94 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ dist
./test
dist/
site
venv
venv
.venv
2 changes: 2 additions & 0 deletions cmd/apigee-go-gen/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package main

import (
"github.com/apigee/apigee-go-gen/cmd/apigee-go-gen/mock"
"github.com/apigee/apigee-go-gen/cmd/apigee-go-gen/render"
"github.com/apigee/apigee-go-gen/cmd/apigee-go-gen/transform"
"github.com/apigee/apigee-go-gen/pkg/flags"
Expand All @@ -35,6 +36,7 @@ func init() {

RootCmd.AddCommand(render.Cmd)
RootCmd.AddCommand(transform.Cmd)
RootCmd.AddCommand(mock.Cmd)
RootCmd.AddCommand(VersionCmd)

RootCmd.PersistentFlags().Var(&showStack, "show-stack", "show stack trace for errors")
Expand Down
29 changes: 29 additions & 0 deletions cmd/apigee-go-gen/mock/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mock

import (
"github.com/apigee/apigee-go-gen/cmd/apigee-go-gen/mock/oas"
"github.com/spf13/cobra"
)

var Cmd = &cobra.Command{
Use: "mock",
Short: "Generate a mock API proxy",
}

func init() {
Cmd.AddCommand(oas.Cmd)
}
66 changes: 66 additions & 0 deletions cmd/apigee-go-gen/mock/oas/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package oas

import (
"fmt"
"github.com/apigee/apigee-go-gen/pkg/common/resources"
"github.com/apigee/apigee-go-gen/pkg/flags"
"github.com/apigee/apigee-go-gen/pkg/mock"
"github.com/spf13/cobra"
)

var input = flags.NewString("")
var output = flags.NewString("")
var debug = flags.NewBool(false)

var Cmd = &cobra.Command{
Use: "oas",
Short: "Generate a mock API proxy from an OpenAPI 3.X spec",
Long: Usage(),
RunE: func(cmd *cobra.Command, args []string) error {
return mock.GenerateMockProxyBundle(string(input), string(output), bool(debug))
},
}

func init() {
Cmd.Flags().SortFlags = false
Cmd.Flags().VarP(&input, "input", "i", `path to OpenAPI spec (e.g. "./path/to/spec.yaml")`)
Cmd.Flags().VarP(&output, "output", "o", `output directory or zip file (e.g. "./path/to/apiproxy.zip")`)
Cmd.Flags().VarP(&debug, "debug", "", `prints rendered template before creating API proxy bundle"`)

_ = Cmd.MarkFlagRequired("input")
_ = Cmd.MarkFlagRequired("output")
_ = Cmd.Flags().MarkHidden("debug")

}

func Usage() string {
usageText := `
This command generates a mock API proxy bundle from an OpenAPI 3.X Spec.
The mock API proxy includes the following features:
%[1]s
`

mockFeatures, err := resources.FS.ReadFile("mock_features.txt")
if err != nil {
panic(err)
}

return fmt.Sprintf(usageText, mockFeatures)
}
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ The `apigee-go-gen` CLI tool streamlines your Apigee development experience usin

* **[Transformation commands](./transform/index.md)** Easily convert between Apigee's API proxy format and YAML for better readability and management.
* **[Template rendering commands](./render/index.md)** Enjoy powerful customization and dynamic configuration options, inspired by the flexibility of Helm using the Go [text/template](https://pkg.go.dev/text/template) engine.
* **[Mock generation command](./mock/commands/mock-oas.md)** Effortlessly create a mock API proxy from your OpenAPI 3.X spec, complete with dynamic response bodies, headers, and status codes.

By using this tool alongside the [Apigee CLI](https://github.com/apigee/apigeecli), you'll unlock a highly customizable workflow. This is perfect for both streamlined local development and robust CI/CD pipelines.

Expand Down
29 changes: 29 additions & 0 deletions docs/mock/commands/mock-oas.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Mock OAS
<!--
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

This command generates a mock API proxy bundle from your OpenAPI 3 specification.

## Usage

The `mock oas` command takes the following parameters:

```text
-i, --input string path to OpenAPI spec (e.g. "./path/to/spec.yaml")
-o, --output string output directory or zip file (e.g. "./path/to/apiproxy.zip")
-h, --help help for oas
```

194 changes: 194 additions & 0 deletions docs/mock/mock-openapi-spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
# Mock OpenAPI Spec
<!--
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

You can use the [mock oas](./commands/mock-oas.md) command to create a mock API proxy from your OpenAPI 3 specification, allowing you to simulate API behavior without a real backend.

## Examples

Below are a couple example of how to use the [mock oas](./commands/mock-oas.md) command

#### Create bundle zip

```shell
apigee-go-gen mock oas \
--input ./examples/specs/oas3/petstore.yaml \
--output ./out/mock-apiproxies/petstore.zip
```

#### Create bundle dir
```shell
apigee-go-gen mock oas \
--input ./examples/specs/oas3/petstore.yaml \
--output ./out/mock-apiproxies/petstore
```



## Mock API Proxy Features

The generated mock API proxy supports the following features.

### :white_check_mark: Base Path from Spec

The `Base Path` for the mock API proxy is derived from the first element of the [servers](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.1.md#oas-servers) array in your OpenAPI spec.

For example, if your server array looks like this:

```yaml
servers:
- url: https://petstore.swagger.io/v3
- url: https://petstore.swagger.io/staging/v3
```
The mock API proxy `Base Path` will be `/v3`

### :white_check_mark: CORS Support

The generated mock API proxy includes the Apigee CORS policy, making it easy to test your API from various browser-based clients.

Here's how it works:

* **Automatic CORS Headers:** The proxy automatically adds the necessary CORS headers (like `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, etc.) to all responses.

* **Preflight Requests:** The proxy correctly handles preflight `OPTIONS` requests, responding with the appropriate CORS headers to indicate allowed origins, methods, and headers.

* **Permissive Configuration:** By default, the CORS policy is configured to be as permissive as possible, allowing requests from any origin with any HTTP method and headers. This maximizes flexibility for your testing.

This built-in CORS support ensures that your mock API behaves like a real API in a browser environment, simplifying your development and testing workflow.

### :white_check_mark: Request Validation


By default, the mock API proxy validates the incoming requests against your specification.
This ensures that the HTTP headers, query parameters, and request body all conform to the defined rules.

This helps you catch errors in your client code early on.

You can disable request validation by passing the header:

```
Mock-Validate-Request: false
```


### :white_check_mark: Dynamic Response Status Code

The mock API proxy automatically generates different status codes for your mock API responses. Here's how it works:

* **Prioritizes success:** If the [operation](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.1.md#operation-object) allows `HTTP 200` status code, the proxy will use it.
* **Random selection:** If `HTTP 200` is not allowed for a particular operation, the proxy will pick a random status code from those allowed.

**Want more control?** You can use headers to select response the status code:

* **Specific status code:** Use the `Mock-Status` header in your request and set it to the desired code (e.g., `Mock-Status: 404`).
* **Random status code:** Use the `Mock-Fuzz: true` header to get a random status code from your spec.

If you use both `Mock-Status` and `Mock-Fuzz`, `Mock-Status` takes precedence.

### :white_check_mark: Dynamic Response Content-Type

The mock API proxy automatically selects the `Content-Type` for responses:

* **JSON preferred:** If the operation allows `application/json`, the proxy will default to using it.
* **Random selection:** If `application/json` is not available, the proxy will randomly choose from the media types available for that operation.

**Want more control?** You can use headers to select the response Content-Type:

* **Standard `Accept` header:** You can use the standard `Accept` header in your request to request a specific media type (e.g., `Accept: application/xml`).
* **Random media type:** Alternatively, use the `Mock-Fuzz: true` header to have the proxy select a random media type the available ones.

If you use both `Accept` and `Mock-Fuzz`, the `Accept` header will take precedence.


### :white_check_mark: Dynamic Response Body

The mock API proxy can generate realistic response bodies based on your OpenAPI spec.

Here's how it determines what to send back for any particular operation's response (in order):

1. **Prioritizes `example` field:** If the response includes an `example` field, the proxy will use that example.

2. **Handles multiple `examples`:** If the response has an `examples` field with multiple examples, the proxy will randomly select one. You can use the `Mock-Example` header to specify which example you want (e.g., `Mock-Example: my-example`).

3. **Uses schema examples:** If no response examples are provided, but the schema for the response has an `example`, the proxy will use that.

4. **Generates from schema:** As a last resort, the proxy will generate a random example based on the response schema. This works for JSON, YAML, and XML.

You can use the `Mock-Fuzz: true` header to force the proxy to always generate a random example from the schema, even if other static examples are available.


### :white_check_mark: Repeatable API Responses

The mock API proxy uses a special technique to make its responses seem random, while still allowing you to get the same response again if needed. Here's how it works:

* **Pseudo-random numbers:** The "random" choices the proxy makes (like status codes and content) are actually generated using a pseudo-random number generator (PRNG). This means the responses look random, but are determined by a starting value called a "seed."

* **Unique seeds:** Each request uses a different seed, so responses vary. However, the seed is provided in a special response header called `Mock-Seed`.

* **Getting the same response:** To get an identical response, simply include the `Mock-Seed` header in a new request, using the value from a previous response. This forces the proxy to use the same seed and generate the same "random" choices, resulting in an identical response.

This feature is super helpful for:

* **Testing:** Ensuring your tests always get the same response.
* **Debugging:** Easily recreating specific scenarios to pinpoint issues in application code.

Essentially, by using the `Mock-Seed` header, you can control the randomness of the mock API responses, making them repeatable for testing and debugging.

### :white_check_mark: Example Generation from JSON Schemas

The following fields are supported when generating examples from a JSON schema:

* `$ref` - local references are followed
* `$oneOf` - chooses a random schema
* `$anyOf` - chooses a random schema
* `$allOf` - combines all schemas
* `object` type
* `required` field - all required properties are chosen
* `properties` field - a random set of properties is chosen
* `additionalProperties` field - only used when there are no `properties` defined
* `array` type
* `minItems`, `maxItems` fields - array length chosen randomly between these values
* `items` field - determines the type of array elements
* `prefixItems` (not supported yet)
* `null` type
* `const` type
* `boolean` type - true or false randomly chosen
* `string` type
* `enum` field - a random value is chosen from the list
* `pattern` field (not supported yet)
* `format` field
* `date-time` format
* `date` format
* `time` format
* `email` format
* `uuid` format
* `uri` format
* `hostname` format
* `ipv4` format
* `ipv6` format
* `duration` format
* `minLength`, `maxLength` fields - string length chosen randomly between these values
* `integer` type
* `minimum`, `maximum` fields - a random integer value chosen randomly between these values
* `exclusiveMinimuim` field (boolean, JSON-Schema 4)
* `exclusiveMaximum` field (boolean, JSON-Schema 4)
* `multipleOf` field
* `number` type
* `minimum`, `maximum` fields - a random float value chosen randomly between these values
* `exclusiveMinimuim` field (boolean, JSON-Schema 4)
* `exclusiveMaximum` field (boolean, JSON-Schema 4)
* `multipleOf` field
Loading

0 comments on commit 116eb07

Please sign in to comment.