Skip to content

Commit

Permalink
Replace json tag with yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
wangqj committed May 8, 2019
1 parent 1c4862f commit c6979f5
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 49 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ go struct
```go
type X struct {
A int
B int `json:"C"` //Will generate C here
D int `json:"-"` //Will ignore it
B int `yaml:"C"` //Will generate C here
D int `yaml:"-"` //Will ignore it
}
```
result
Expand Down
14 changes: 7 additions & 7 deletions model_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ func (b modelBuilder) addModel(st reflect.Type, nameOverride string) *Items {

for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
//add json tag,if =="" ignore
if b.jsonNameOfField(field) == "" {
//add tag,if =="" ignore
if b.nameOfField(field) == "" {
continue
} else {
field.Name = b.jsonNameOfField(field)
field.Name = b.nameOfField(field)

}
sm.Properties[field.Name] = &Items{}
Expand Down Expand Up @@ -151,11 +151,11 @@ func (b modelBuilder) isPrimitiveType(modelName string) bool {
return strings.Contains("uint uint8 uint16 uint32 uint64 int int8 int16 int32 int64 float32 float64 bool string byte rune time.Time", modelName)
}

// jsonNameOfField returns the name of the field as it should appear in JSON format
// nameOfField returns the name of the field as it should appear in JSON format
// An empty string indicates that this field is not part of the JSON representation
func (b modelBuilder) jsonNameOfField(field reflect.StructField) string {
if jsonTag := field.Tag.Get("json"); jsonTag != "" {
s := strings.Split(jsonTag, ",")
func (b modelBuilder) nameOfField(field reflect.StructField) string {
if tag := field.Tag.Get("yaml"); tag != "" {
s := strings.Split(tag, ",")
if s[0] == "-" {
// empty name signals skip property
return ""
Expand Down
14 changes: 7 additions & 7 deletions model_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

func TestSampleToModelAsJson(t *testing.T) {
testJsonFromStruct(t, sample{items: []item{}}, `{
testFromStruct(t, sample{items: []item{}}, `{
"sample": {
"type": "object",
"properties": {
Expand Down Expand Up @@ -62,7 +62,7 @@ func TestAnonymousPtrStruct(t *testing.T) {
}
}
}`
testJsonFromStruct(t, X{}, expected)
testFromStruct(t, X{}, expected)
}

type File struct {
Expand All @@ -72,7 +72,7 @@ type File struct {

//test recursion struct
func TestRecursiveStructure(t *testing.T) {
testJsonFromStruct(t, File{}, `{
testFromStruct(t, File{}, `{
"File": {
"type": "object",
"properties": {
Expand Down Expand Up @@ -146,11 +146,11 @@ func TestKeyFrom(t *testing.T) {
}
}

func TestJsonTag(t *testing.T) {
func Test(t *testing.T) {
type X struct {
A int
B int `json:"C"`
D int `json:"-"`
B int `yaml:"C"`
D int `yaml:"-"`
}

expected := `{
Expand All @@ -169,5 +169,5 @@ func TestJsonTag(t *testing.T) {
}
}`

testJsonFromStruct(t, X{}, expected)
testFromStruct(t, X{}, expected)
}
61 changes: 34 additions & 27 deletions swagger_test.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
package swagger

import (
"testing"
"encoding/json"
"github.com/emicklei/go-restful"
"strings"
"os"
"strings"
"testing"
)

//测试Info
func TestInfoStruct(t *testing.T) {
config := Config{
Info: Info{
Title: "Title",
Description: "Description",
Version: "Version",
Title: "Title",
Description: "Description",
Version: "Version",
},
}
sws := newSwaggerService(config)
listing := APIDefinition{
Swagger: swaggerVersion,
Info: sws.config.Info,
Swagger: swaggerVersion,
Info: sws.config.Info,
BasePath: "",
Paths: nil,
Paths: nil,
}
str, err := json.MarshalIndent(listing, "", " ")
if err != nil {
Expand All @@ -40,6 +41,7 @@ func TestInfoStruct(t *testing.T) {
}
`)
}

//测试Api
func TestServiceToApi(t *testing.T) {
ws := new(restful.WebService)
Expand Down Expand Up @@ -85,13 +87,14 @@ func TestServiceToApi(t *testing.T) {
}

func dummy(req *restful.Request, res *restful.Response) {}

type sample struct {
id string `swagger:"required"` // TODO
items []item
rootItem item `json:"root" description:"root desc"`
rootItem item `yaml:"root" description:"root desc"`
}
type item struct {
itemName string `json:"name"`
itemName string `yaml:"name"`
}
type TestItem struct {
Id, Name string
Expand All @@ -104,6 +107,7 @@ type Responses struct {
Users *[]User
Items *[]TestItem
}

//测试responses
func TestComposeResponses(t *testing.T) {
responseErrors := map[int]restful.ResponseError{}
Expand All @@ -119,11 +123,12 @@ func TestComposeResponses(t *testing.T) {
t.Errorf("got %s want #/definitions/TestItem", msgs["400"].Schema.Ref)
}
}

//测试Definitions
func TestAddModel(t *testing.T) {
sws := newSwaggerService(Config{})
api := APIDefinition{
Definitions: map[string]*Items{}}
Definitions: map[string]*Items{}}

sws.addModelFromSampleTo(Responses{Items: &[]TestItem{}}, &api.Definitions)
model, ok := atMap("Responses", &api.Definitions)
Expand All @@ -138,13 +143,13 @@ func TestAddModel(t *testing.T) {
str = str + key
}
if !strings.Contains(str, "Code") {
t.Fatal("missing code" )
t.Fatal("missing code")
}
if !strings.Contains(str, "Users") {
t.Fatal("missing User" )
t.Fatal("missing User")
}
if !strings.Contains(str, "Items") {
t.Fatal("missing Items" )
t.Fatal("missing Items")
}
if model.Properties["Code"].Type != "integer" {
t.Fatal("wrong code type:" + model.Properties["Code"].Type.(string))
Expand Down Expand Up @@ -180,10 +185,10 @@ func TestAddModel(t *testing.T) {
str1 = str1 + key
}
if !strings.Contains(str1, "Id") {
t.Fatal("missing User Id" )
t.Fatal("missing User Id")
}
if !strings.Contains(str1, "Name") {
t.Fatal("missing User Name" )
t.Fatal("missing User Name")
}
if model1.Properties["Id"].Type != "string" {
t.Fatal("wrong User Id type:" + model1.Properties["Id"].Type.(string))
Expand All @@ -204,10 +209,10 @@ func TestAddModel(t *testing.T) {
str2 = str2 + key
}
if !strings.Contains(str2, "Id") {
t.Fatal("missing TestItem Id" )
t.Fatal("missing TestItem Id")
}
if !strings.Contains(str2, "Name") {
t.Fatal("missing TestItem Name" )
t.Fatal("missing TestItem Name")
}
if model2.Properties["Id"].Type != "string" {
t.Fatal("wrong TestItem Id type:" + model2.Properties["Id"].Type.(string))
Expand All @@ -216,46 +221,48 @@ func TestAddModel(t *testing.T) {
t.Fatal("wrong TestItem Name type:" + model2.Properties["Name"].Type.(string))
}
}

//测试将openapi协议以json形式保存在本地
func TestWriteJsonToFile(t *testing.T) {
//测试前请先设定环境变量
val := os.Getenv("SWAGGERFILEPATH")
os.Remove(val);
os.Mkdir(val,0777)
os.Remove(val)
os.Mkdir(val, 0777)
ws := new(restful.WebService)
ws.Path("/file")
ws.Consumes(restful.MIME_JSON)
ws.Produces(restful.MIME_JSON)
ws.Route(ws.GET("/write").To(dummy).Writes(sample{}))
cfg := Config{
WebServices: []*restful.WebService{ws},
FileStyle: "json",
WebServices: []*restful.WebService{ws},
FileStyle: "json",
SwaggerFilePath: val,
}
sws := newSwaggerService(cfg)
sws.WriteToFile()
files, err := ListDir(val,"json")
files, err := ListDir(val, "json")
if err != nil || len(files) != 1 {
t.Fatal("No local json file was generated")
}
}

//测试将openapi协议以yaml形式保存在本地
func TestWriteYamlToFile(t *testing.T) {
val := os.Getenv("SWAGGERFILEPATH")
os.RemoveAll(val);
os.Mkdir(val,0777)
os.RemoveAll(val)
os.Mkdir(val, 0777)
ws := new(restful.WebService)
ws.Path("/file")
ws.Consumes(restful.MIME_JSON)
ws.Produces(restful.MIME_JSON)
ws.Route(ws.GET("/write").To(dummy).Writes(sample{}))
cfg := Config{
WebServices: []*restful.WebService{ws},
WebServices: []*restful.WebService{ws},
SwaggerFilePath: val,
}
sws := newSwaggerService(cfg)
sws.WriteToFile()
files, err := ListDir(val,"yaml")
files, err := ListDir(val, "yaml")
if err != nil || len(files) != 1 {
t.Fatal("No local yaml file was generated")
}
Expand Down
12 changes: 6 additions & 6 deletions utils_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package swagger

import (
"encoding/json"
"reflect"
"testing"
"bytes"
"strings"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
)

func compareJson(t *testing.T, actualJsonAsString string, expectedJsonAsString string) bool {
Expand Down Expand Up @@ -50,7 +50,7 @@ func withLineNumbers(content string) string {
}
return buffer.String()
}
func testJsonFromStruct(t *testing.T, sample interface{}, expectedJson string) bool {
func testFromStruct(t *testing.T, sample interface{}, expectedJson string) bool {
return testJsonFromStructWithConfig(t, sample, expectedJson, &Config{})
}

Expand Down Expand Up @@ -83,4 +83,4 @@ func ListDir(dirPth string, suffix string) (files []string, err error) {
}
}
return files, nil
}
}

0 comments on commit c6979f5

Please sign in to comment.