github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/cmd/swagger/commands/generate/spec_go111_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/codescan"
    12  
    13  	"github.com/jessevdk/go-flags"
    14  	"github.com/stretchr/testify/assert"
    15  	"gopkg.in/yaml.v3"
    16  )
    17  
    18  const (
    19  	basePath       = "../../../../fixtures/goparsing/spec"
    20  	jsonResultFile = basePath + "/api_spec_go111.json"
    21  	yamlResultFile = basePath + "/api_spec_go111.yml"
    22  )
    23  
    24  func TestSpecFileExecute(t *testing.T) {
    25  	files := []string{"", "spec.json", "spec.yml", "spec.yaml"}
    26  	for _, outputFile := range files {
    27  		spec := &SpecFile{
    28  			WorkDir: basePath,
    29  			Output:  flags.Filename(outputFile),
    30  		}
    31  
    32  		err := spec.Execute(nil)
    33  		assert.NoError(t, err)
    34  		if outputFile != "" {
    35  			_ = os.Remove(outputFile)
    36  		}
    37  	}
    38  }
    39  
    40  func TestGenerateJSONSpec(t *testing.T) {
    41  	opts := codescan.Options{
    42  		WorkDir:  basePath,
    43  		Packages: []string{"./..."},
    44  	}
    45  
    46  	swspec, err := codescan.Run(&opts)
    47  	assert.NoError(t, err)
    48  
    49  	data, err := marshalToJSONFormat(swspec, true)
    50  	assert.NoError(t, err)
    51  
    52  	expected, err := os.ReadFile(jsonResultFile)
    53  	assert.NoError(t, err)
    54  
    55  	verifyJSONData(t, data, expected)
    56  }
    57  
    58  func TestGenerateYAMLSpec(t *testing.T) {
    59  	opts := codescan.Options{
    60  		WorkDir:  basePath,
    61  		Packages: []string{"./..."},
    62  	}
    63  
    64  	swspec, err := codescan.Run(&opts)
    65  	assert.NoError(t, err)
    66  
    67  	data, err := marshalToYAMLFormat(swspec)
    68  	assert.NoError(t, err)
    69  
    70  	expected, err := os.ReadFile(yamlResultFile)
    71  	assert.NoError(t, err)
    72  
    73  	verifyYAMLData(t, data, expected)
    74  }
    75  
    76  func verifyJSONData(t *testing.T, data, expectedJSON []byte) {
    77  	var got interface{}
    78  	var expected interface{}
    79  
    80  	err := json.Unmarshal(data, &got)
    81  	assert.NoError(t, err)
    82  
    83  	err = json.Unmarshal(expectedJSON, &expected)
    84  	assert.NoError(t, err)
    85  	assert.Equal(t, expected, got)
    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  	assert.Equal(t, expected, got)
    98  }