Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: add json-schema validator postprocessor in http/scenario gun #194

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions components/providers/scenario/config/hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ type RequestPostprocessorHCL struct {
Body *[]string `hcl:"body" yaml:"body,omitempty"`
StatusCode *int `hcl:"status_code" yaml:"status_code,omitempty"`
Size *AssertSizeHCL `hcl:"size,block" yaml:"size,omitempty"`
Source string `hcl:"source" yaml:"source,omitempty"`
Schema string `hcl:"schema" yaml:"schema,omitempty"`
}

type RequestPreprocessorHCL struct {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package postprocessor

import (
"fmt"
"github.com/xeipuuv/gojsonschema"
"io"
"net/http"
"path/filepath"
"strings"
)

type AssertJsonSchema struct {
Source string `config:"source"`
Schema string `config:"schema"`
}

func (a AssertJsonSchema) Process(_ *http.Response, body io.Reader) (map[string]any, error) {
var schemaLoader gojsonschema.JSONLoader

switch a.Source {
case "file":
absPath, err := filepath.Abs(a.Schema)

if err != nil {
return nil, fmt.Errorf("assert/json-schema fail to get schema file absolute path: %w", err)
}

filePath := "file:///" + absPath
schemaLoader = gojsonschema.NewReferenceLoader(filePath)

case "url":
schemaLoader = gojsonschema.NewReferenceLoader(a.Schema)
case "json_string":
schemaLoader = gojsonschema.NewStringLoader(a.Schema)
default:
return nil, fmt.Errorf("unknown schema source %s", a.Source)
}

var b []byte
var err error

if body != nil {
b, err = io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("assert/json-schema can't read body: %w", err)
}
}

schema, err := gojsonschema.NewSchema(schemaLoader)

if err != nil {
return nil, fmt.Errorf("assert/json-schema can't create schema: %w", err)
}

respJson := gojsonschema.NewBytesLoader(b)
result, err := schema.Validate(respJson)

if err != nil {
return nil, fmt.Errorf("assert/json-schema validate error: %w", err)
}

if !result.Valid() {
var errors []string
for _, desc := range result.Errors() {
errors = append(errors, desc.String())
}

return nil, fmt.Errorf("assert/json-schema validation errors: %s", strings.Join(errors, ", "))
}

return nil, nil
}

func (a AssertJsonSchema) Validate() error {

if a.Source != "file" && a.Source != "url" && a.Source != "json_string" {
return fmt.Errorf("assert/json-schema unknown schema source %s", a.Source)
}

if a.Schema == "" {
var invalidSource string

switch a.Source {
case "file":
invalidSource = "file path"
case "url":
invalidSource = "url"
case "json_string":
invalidSource = "json string"
}

return fmt.Errorf("assert/json-schema invalid schema %s", invalidSource)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package postprocessor

import (
"bytes"
"fmt"
"github.com/stretchr/testify/assert"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
)

func TestAssertJsonSchema_Process(t *testing.T) {
type fields struct {
Source string
Schema string
}

type args struct {
resp *http.Response
body io.Reader
}

tests := []struct {
name string
fields fields
args args
wantErr assert.ErrorAssertionFunc
}{
{
name: "Validate response from file",
fields: fields{
Source: "file",
Schema: "testdata/test_schema.json",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.NoError,
},
{
name: "Validate response from json-string",
fields: fields{
Source: "json_string",
Schema: "{\"type\": \"object\"}",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.NoError,
},
{
name: "Invalid Body",
fields: fields{
Source: "file",
Schema: "testdata/test_schema.json",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: nil, // for this postprocessor we don't care about response, we need only body for validate
},
wantErr: assert.Error,
},
{
name: "Invalid schema source",
fields: fields{
Source: "test_source",
Schema: "testdata/test_schema.json",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.Error,
},
{
name: "Invalid schema file path",
fields: fields{
Source: "file",
Schema: "not_existing_schema.json",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.Error,
},
{
name: "Invalid schema url path",
fields: fields{
Source: "url",
Schema: "https://example.com",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.Error,
},
{
name: "Invalid schema json-string",
fields: fields{
Source: "json_string",
Schema: "",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.Error,
},
{
name: "Schema validation error",
fields: fields{
Source: "json_string",
Schema: "{\"type\": \"array\"}",
},
args: args{
resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil},
body: bytes.NewReader([]byte(`{"message": "Hello, World!"}`)),
},
wantErr: assert.Error,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
a := AssertJsonSchema{
Schema: tt.fields.Schema,
Source: tt.fields.Source,
}

process, err := a.Process(tt.args.resp, tt.args.body)
assert.Nil(t, process)
tt.wantErr(t, err, fmt.Sprintf("Process(%v, %v)", tt.args.resp, tt.args.body))
})
}
}

func TestAssertUrlJsonSchema_Process(t *testing.T) {
t.Run("Validate response with url schema", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(serveSchemaHandler))

a := AssertJsonSchema{
Schema: server.URL + "/?file=test_schema.json",
Source: "url",
}

resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: nil}
body := bytes.NewReader([]byte(`{"message": "Hello, World!"}`))

process, err := a.Process(resp, body)

server.Close()

assert.Nil(t, process)
assert.NoError(t, err)
})
}

func serveSchemaHandler(w http.ResponseWriter, r *http.Request) {
schemaName := r.URL.Query().Get("file")
if schemaName == "" {
http.Error(w, "Missing file name", http.StatusBadRequest)
return
}

schemaPath := "testdata/" + schemaName

data, err := os.ReadFile(schemaPath)
if err != nil {
http.Error(w, "Failed to load schema: "+err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")

_, err = w.Write(data)
if err != nil {
log.Fatal(err)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "object"
}
9 changes: 9 additions & 0 deletions components/providers/scenario/import/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func Import(fs afero.Fs) {
RegisterPostprocessor("var/xpath", NewVarXpathPostprocessor)
RegisterPostprocessor("var/header", NewVarHeaderPostprocessor)
RegisterPostprocessor("assert/response", NewAssertResponsePostprocessor)
RegisterPostprocessor("assert/json-schema", NewAssertJsonSchemaPostprocessor)

RegisterTemplater("text", func() gun.Templater {
return templater.NewTextTemplater()
Expand Down Expand Up @@ -112,3 +113,11 @@ func NewVarXpathPostprocessor(cfg postprocessor.Config) gun.Postprocessor {
Mapping: cfg.Mapping,
}
}

func NewAssertJsonSchemaPostprocessor(cfg postprocessor.AssertJsonSchema) (gun.Postprocessor, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
return &cfg, nil
}
74 changes: 74 additions & 0 deletions docs/content/en/generator/scenario-http-generator.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,80 @@ request "your_request_name" {
}
```

##### assert/json-schema

Checks response body matches the specified json-schema

**HCL examples:**

**Use json-schema from file:**

```terraform
request "your_request_name" {
postprocessor "assert/json-schema" {
source = "file"
schema = "my_json_schema.json"
}
}
```
**Use json-schema from json-string:**

```terraform
request "your_request_name" {
postprocessor "assert/json-schema" {
source = "json_string"
schema = "{ \"type\" : \"object\" }"
}
}
```

**Use json-schema located on the host:**

**Important: specify the request scheme (http/https)**

```terraform
request "your_request_name" {
postprocessor "assert/json-schema" {
source = "url"
schema = "https://examplehost.com/#validation_schema.json"
}
}
```

**YAML examples**

**Use json-schema from file:**
```yaml
requests:
- name: "your_request_name"
postprocessors:
- type: assert/json-schema
source: file
schema: "my_json_schema.json"
```

**Use json-schema from json-string:**
```yaml
requests:
- name: "your_request_name"
postprocessors:
- type: assert/json-schema
source: json_string
schema: '{ "type" : "array" }'
```

**Use json-schema located on the host:**

**Important: specify the request scheme (http/https)**
```yaml
requests:
- name: "your_request_name"
postprocessors:
- type: assert/json-schema
source: url
schema: "https://examplehost.com/#validation_schema.json"
```

### Scenarios

The minimum fields for the script are name and list of requests
Expand Down
Loading