github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/cmd/swagger/commands/generate/spec_test.go (about) 1 //go:build !go1.11 2 // +build !go1.11 3 4 package generate 5 6 import ( 7 "encoding/json" 8 "os" 9 "testing" 10 11 "github.com/go-swagger/go-swagger/scan" 12 "github.com/jessevdk/go-flags" 13 "github.com/stretchr/testify/assert" 14 "gopkg.in/yaml.v3" 15 ) 16 17 const ( 18 basePath = "../../../../fixtures/goparsing/spec" 19 jsonResultFile = basePath + "/api_spec.json" 20 yamlResultFile = basePath + "/api_spec.yml" 21 ) 22 23 func TestSpecFileExecute(t *testing.T) { 24 files := []string{"", "spec.json", "spec.yml", "spec.yaml"} 25 for _, outputFile := range files { 26 spec := &SpecFile{ 27 BasePath: basePath, 28 Output: flags.Filename(outputFile), 29 } 30 31 err := spec.Execute(nil) 32 assert.NoError(t, err) 33 if outputFile != "" { 34 os.Remove(outputFile) 35 } 36 } 37 } 38 39 func TestGenerateJSONSpec(t *testing.T) { 40 opts := scan.Opts{ 41 BasePath: basePath, 42 } 43 44 swspec, err := scan.Application(opts) 45 assert.NoError(t, err) 46 47 data, err := marshalToJSONFormat(swspec, true) 48 assert.NoError(t, err) 49 50 expected, err := os.ReadFile(jsonResultFile) 51 assert.NoError(t, err) 52 53 verifyJSONData(t, data, expected) 54 } 55 56 func TestGenerateYAMLSpec(t *testing.T) { 57 opts := scan.Opts{ 58 BasePath: basePath, 59 } 60 61 swspec, err := scan.Application(opts) 62 assert.NoError(t, err) 63 64 data, err := marshalToYAMLFormat(swspec) 65 assert.NoError(t, err) 66 67 expected, err := os.ReadFile(yamlResultFile) 68 assert.NoError(t, err) 69 70 verifyYAMLData(t, data, expected) 71 } 72 73 func verifyJSONData(t *testing.T, data, expectedJSON []byte) { 74 var got interface{} 75 var expected interface{} 76 77 err := json.Unmarshal(data, &got) 78 assert.NoError(t, err) 79 80 err = json.Unmarshal(expectedJSON, &expected) 81 assert.NoError(t, err) 82 83 if !assert.ObjectsAreEqual(got, expected) { 84 assert.Fail(t, "marshaled JSON data doesn't equal expected JSON data") 85 } 86 } 87 88 func verifyYAMLData(t *testing.T, data, expectedYAML []byte) { 89 var got interface{} 90 var expected interface{} 91 92 err := yaml.Unmarshal(data, &got) 93 assert.NoError(t, err) 94 95 err = yaml.Unmarshal(expectedYAML, &expected) 96 assert.NoError(t, err) 97 98 if !assert.ObjectsAreEqual(got, expected) { 99 assert.Fail(t, "marshaled YAML data doesn't equal expected YAML data") 100 } 101 }