github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/cmd/swagger/commands/generate/spec_test.go (about) 1 package generate 2 3 import ( 4 "encoding/json" 5 "os" 6 "testing" 7 8 "github.com/thetreep/go-swagger/codescan" 9 10 "github.com/jessevdk/go-flags" 11 "github.com/stretchr/testify/assert" 12 "gopkg.in/yaml.v3" 13 ) 14 15 const ( 16 basePath = "../../../../fixtures/goparsing/spec" 17 jsonResultFile = basePath + "/api_spec_go111.json" 18 yamlResultFile = basePath + "/api_spec_go111.yml" 19 ) 20 21 func TestSpecFileExecute(t *testing.T) { 22 files := []string{"", "spec.json", "spec.yml", "spec.yaml"} 23 for _, outputFile := range files { 24 spec := &SpecFile{ 25 WorkDir: basePath, 26 Output: flags.Filename(outputFile), 27 } 28 29 err := spec.Execute(nil) 30 assert.NoError(t, err) 31 if outputFile != "" { 32 _ = os.Remove(outputFile) 33 } 34 } 35 } 36 37 func TestGenerateJSONSpec(t *testing.T) { 38 opts := codescan.Options{ 39 WorkDir: basePath, 40 Packages: []string{"./..."}, 41 } 42 43 swspec, err := codescan.Run(&opts) 44 assert.NoError(t, err) 45 46 data, err := marshalToJSONFormat(swspec, true) 47 assert.NoError(t, err) 48 49 expected, err := os.ReadFile(jsonResultFile) 50 assert.NoError(t, err) 51 52 verifyJSONData(t, data, expected) 53 } 54 55 func TestGenerateYAMLSpec(t *testing.T) { 56 opts := codescan.Options{ 57 WorkDir: basePath, 58 Packages: []string{"./..."}, 59 } 60 61 swspec, err := codescan.Run(&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 assert.Equal(t, expected, got) 83 } 84 85 func verifyYAMLData(t *testing.T, data, expectedYAML []byte) { 86 var got interface{} 87 var expected interface{} 88 89 err := yaml.Unmarshal(data, &got) 90 assert.NoError(t, err) 91 92 err = yaml.Unmarshal(expectedYAML, &expected) 93 assert.NoError(t, err) 94 assert.Equal(t, expected, got) 95 }