...

Source file src/github.com/go-openapi/validate/doc_test.go

Documentation: github.com/go-openapi/validate

     1  // Copyright 2015 go-swagger maintainers
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package validate_test
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"os"
    21  	"path/filepath"
    22  	"testing"
    23  
    24  	"github.com/go-openapi/loads" // Spec loading
    25  	"github.com/go-openapi/spec"
    26  	"github.com/go-openapi/strfmt"   // OpenAPI format extensions
    27  	"github.com/go-openapi/validate" // This package
    28  	"github.com/stretchr/testify/require"
    29  )
    30  
    31  func ExampleSpec() {
    32  	// Example with high level spec validation call, without showing warnings
    33  
    34  	// Example with spec file in this repo:
    35  	path := "fixtures/validation/valid-ref.json"
    36  	doc, err := loads.Spec(path)
    37  	if err == nil {
    38  		validate.SetContinueOnErrors(true)         // Set global options
    39  		errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions
    40  
    41  		if errs == nil {
    42  			fmt.Println("This spec is valid")
    43  		} else {
    44  			fmt.Printf("This spec has some validation errors: %v\n", errs)
    45  		}
    46  	} else {
    47  		fmt.Println("Could not load this spec")
    48  	}
    49  	// Output: This spec is valid
    50  }
    51  
    52  func ExampleSpec_second() {
    53  	// Example with high level spec validation call, without showing warnings
    54  
    55  	// Example with online spec URL:
    56  	url := "http://petstore.swagger.io/v2/swagger.json"
    57  	doc, err := loads.JSONSpec(url)
    58  	if err == nil {
    59  		validate.SetContinueOnErrors(true)         // Set global options
    60  		errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions
    61  
    62  		if errs == nil {
    63  			fmt.Println("This spec is valid")
    64  		} else {
    65  			fmt.Printf("This spec has some validation errors: %v\n", errs)
    66  		}
    67  	} else {
    68  		fmt.Println("Could not load this spec:", err)
    69  	}
    70  
    71  	// Output:
    72  	// This spec is valid
    73  }
    74  
    75  func ExampleSpecValidator_Validate() {
    76  	// Example of spec validation call with full result
    77  
    78  	// Example with online spec URL:
    79  	// url := "http://petstore.swagger.io/v2/swagger.json"
    80  	// doc, err := loads.JSONSpec(url)
    81  
    82  	// Example with spec file in this repo:
    83  	path := "fixtures/validation/valid-ref.json"
    84  	doc, err := loads.Spec(path)
    85  	if err == nil {
    86  		validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
    87  		validator.SetContinueOnErrors(true)  // Set option for this validator
    88  		result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
    89  		if result.IsValid() {
    90  			fmt.Println("This spec is valid")
    91  		} else {
    92  			fmt.Println("This spec has some validation errors")
    93  		}
    94  		if result.HasWarnings() {
    95  			fmt.Println("This spec has some validation warnings")
    96  		}
    97  	}
    98  	// Output:
    99  	// This spec is valid
   100  	// This spec has some validation warnings
   101  }
   102  
   103  func ExampleSpecValidator_Validate_url() {
   104  	// Example of spec validation call with full result
   105  
   106  	// Example with online spec URL:
   107  	url := "http://petstore.swagger.io/v2/swagger.json"
   108  	doc, err := loads.JSONSpec(url)
   109  	if err == nil {
   110  		validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
   111  		validator.SetContinueOnErrors(true)  // Set option for this validator
   112  		result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
   113  		if result.IsValid() {
   114  			fmt.Println("This spec is valid")
   115  		} else {
   116  			fmt.Println("This spec has some validation errors")
   117  		}
   118  		if result.HasWarnings() {
   119  			fmt.Println("This spec has some validation warnings")
   120  		}
   121  	}
   122  
   123  	// Output:
   124  	// This spec is valid
   125  }
   126  
   127  func ExampleAgainstSchema() {
   128  	// Example using encoding/json as unmarshaller
   129  	var schemaJSON = `
   130  {
   131      "properties": {
   132          "name": {
   133              "type": "string",
   134              "pattern": "^[A-Za-z]+$",
   135              "minLength": 1
   136          }
   137  	},
   138      "patternProperties": {
   139  	  "address-[0-9]+": {
   140           "type": "string",
   141           "pattern": "^[\\s|a-z]+$"
   142  	  }
   143      },
   144      "required": [
   145          "name"
   146      ],
   147  	"additionalProperties": false
   148  }`
   149  
   150  	schema := new(spec.Schema)
   151  	_ = json.Unmarshal([]byte(schemaJSON), schema)
   152  
   153  	input := map[string]interface{}{}
   154  
   155  	// JSON data to validate
   156  	inputJSON := `{"name": "Ivan","address-1": "sesame street"}`
   157  	_ = json.Unmarshal([]byte(inputJSON), &input)
   158  
   159  	// strfmt.Default is the registry of recognized formats
   160  	err := validate.AgainstSchema(schema, input, strfmt.Default)
   161  	if err != nil {
   162  		fmt.Printf("JSON does not validate against schema: %v", err)
   163  	} else {
   164  		fmt.Printf("OK")
   165  	}
   166  	// Output:
   167  	// OK
   168  }
   169  
   170  func TestValidate_Issue112(t *testing.T) {
   171  	t.Run("returns no error on body includes `items` key", func(t *testing.T) {
   172  		body := map[string]interface{}{"items1": nil}
   173  		err := validate.AgainstSchema(getSimpleSchema(), body, strfmt.Default)
   174  		require.NoError(t, err)
   175  	})
   176  
   177  	t.Run("returns no error when body includes `items` key", func(t *testing.T) {
   178  		body := map[string]interface{}{"items": nil}
   179  		err := validate.AgainstSchema(getSimpleSchema(), body, strfmt.Default)
   180  		require.NoError(t, err)
   181  	})
   182  }
   183  
   184  func getSimpleSchema() *spec.Schema {
   185  	return &spec.Schema{
   186  		SchemaProps: spec.SchemaProps{
   187  			Type: spec.StringOrArray{"object"},
   188  		},
   189  	}
   190  }
   191  
   192  func Test_Issue102_Circular(t *testing.T) {
   193  	// assert that the issue is fixed in go-openapi/spec
   194  	for _, fixture := range []string{
   195  		filepath.Join("fixtures", "bugs", "102", "fixture-102.json"),
   196  		filepath.Join("fixtures", "bugs", "123-validate", "fixture-123.json"),
   197  	} {
   198  		t.Run(fixture, func(t *testing.T) {
   199  			filebytes, err := os.ReadFile(fixture)
   200  			require.NoError(t, err)
   201  
   202  			openAPIv2Doc := json.RawMessage(filebytes)
   203  
   204  			doc, err := loads.Analyzed(openAPIv2Doc, "")
   205  			require.NoError(t, err)
   206  
   207  			validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
   208  			validator.SetContinueOnErrors(true)
   209  			res, _ := validator.Validate(doc)
   210  			require.Emptyf(t, res.Errors, "unexpected validation erorrs: %v", res.Errors)
   211  		})
   212  	}
   213  }
   214  

View as plain text