1 Star 0 Fork 0

brucelin_cn/swag

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
parser_test.go 89.74 KB
一键复制 编辑 原始数据 按行查看 历史
coldWater 提交于 2021-11-12 02:23 . chore: fix bug and refactor (#1048)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327
package swag
import (
"bytes"
"encoding/json"
"go/ast"
goparser "go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
const defaultParseDepth = 100
const mainAPIFile = "main.go"
func TestNew(t *testing.T) {
t.Run("SetMarkdownFileDirectory", func(t *testing.T) {
t.Parallel()
expected := "docs/markdown"
p := New(SetMarkdownFileDirectory(expected))
assert.Equal(t, expected, p.markdownFileDir)
})
t.Run("SetCodeExamplesDirectory", func(t *testing.T) {
t.Parallel()
expected := "docs/examples"
p := New(SetCodeExamplesDirectory(expected))
assert.Equal(t, expected, p.codeExampleFilesDir)
})
t.Run("SetStrict", func(t *testing.T) {
t.Parallel()
p := New()
assert.Equal(t, false, p.Strict)
p = New(SetStrict(true))
assert.Equal(t, true, p.Strict)
})
t.Run("SetDebugger", func(t *testing.T) {
t.Parallel()
logger := log.New(&bytes.Buffer{}, "", log.LstdFlags)
p := New(SetDebugger(logger))
assert.Equal(t, logger, p.debug)
})
t.Run("SetFieldParserFactory", func(t *testing.T) {
t.Parallel()
p := New(SetFieldParserFactory(nil))
assert.Nil(t, p.fieldParserFactory)
})
}
func TestParser_ParseDefinition(t *testing.T) {
p := New()
// Parsing existing type
definition := &TypeSpecDef{
PkgPath: "github.com/swagger/swag",
File: &ast.File{
Name: &ast.Ident{
Name: "swag",
},
},
TypeSpec: &ast.TypeSpec{
Name: &ast.Ident{
Name: "Test",
},
},
}
expected := &Schema{}
p.parsedSchemas[definition] = expected
schema, err := p.ParseDefinition(definition)
assert.NoError(t, err)
assert.Equal(t, expected, schema)
// Parsing *ast.FuncType
definition = &TypeSpecDef{
PkgPath: "github.com/swagger/swag/model",
File: &ast.File{
Name: &ast.Ident{
Name: "model",
},
},
TypeSpec: &ast.TypeSpec{
Name: &ast.Ident{
Name: "Test",
},
Type: &ast.FuncType{},
},
}
_, err = p.ParseDefinition(definition)
assert.Error(t, err)
}
func TestParser_ParseGeneralApiInfo(t *testing.T) {
t.Parallel()
expected := `{
"schemes": [
"http",
"https"
],
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.\nIt has a lot of beautiful features.",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0",
"x-logo": {
"altText": "Petstore logo",
"backgroundColor": "#FFFFFF",
"url": "https://redocly.github.io/redoc/petstore-logo.png"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
"BasicAuth": {
"type": "basic"
},
"OAuth2AccessCode": {
"type": "oauth2",
"flow": "accessCode",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information"
},
"x-tokenname": "id_token"
},
"OAuth2Application": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Implicit": {
"type": "oauth2",
"flow": "implicit",
"authorizationUrl": "https://example.com/oauth/authorize",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
},
"x-google-audiences": "some_audience.google.com"
},
"OAuth2Password": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"read": " Grants read access",
"write": " Grants write access"
}
}
},
"x-google-endpoints": [
{
"allowCors": true,
"name": "name.endpoints.environment.cloud.goog"
}
],
"x-google-marks": "marks values"
}`
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
err := p.ParseGeneralAPIInfo("testdata/main.go")
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParser_ParseGeneralApiInfoTemplated(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"paths": {},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
"BasicAuth": {
"type": "basic"
},
"OAuth2AccessCode": {
"type": "oauth2",
"flow": "accessCode",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information"
}
},
"OAuth2Application": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Implicit": {
"type": "oauth2",
"flow": "implicit",
"authorizationUrl": "https://example.com/oauth/authorize",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Password": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"read": " Grants read access",
"write": " Grants write access"
}
}
},
"x-google-endpoints": [
{
"allowCors": true,
"name": "name.endpoints.environment.cloud.goog"
}
],
"x-google-marks": "marks values"
}`
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
err := p.ParseGeneralAPIInfo("testdata/templated.go")
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParser_ParseGeneralApiInfoExtensions(t *testing.T) {
// should return an error because extension value is not a valid json
t.Run("Test invalid extension value", func(t *testing.T) {
t.Parallel()
expected := "annotation @x-google-endpoints need a valid json value"
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
err := p.ParseGeneralAPIInfo("testdata/extensionsFail1.go")
if assert.Error(t, err) {
assert.Equal(t, expected, err.Error())
}
})
// should return an error because extension don't have a value
t.Run("Test missing extension value", func(t *testing.T) {
t.Parallel()
expected := "annotation @x-google-endpoints need a value"
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
err := p.ParseGeneralAPIInfo("testdata/extensionsFail2.go")
if assert.Error(t, err) {
assert.Equal(t, expected, err.Error())
}
})
}
func TestParser_ParseGeneralApiInfoWithOpsInSameFile(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.\nIt has a lot of beautiful features.",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {},
"version": "1.0"
},
"paths": {}
}`
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
err := p.ParseGeneralAPIInfo("testdata/single_file_api/main.go")
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParser_ParseGeneralAPIInfoMarkdown(t *testing.T) {
t.Parallel()
p := New(SetMarkdownFileDirectory("testdata"))
mainAPIFile := "testdata/markdown.go"
err := p.ParseGeneralAPIInfo(mainAPIFile)
assert.NoError(t, err)
expected := `{
"swagger": "2.0",
"info": {
"description": "Swagger Example API Markdown Description",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {},
"version": "1.0"
},
"paths": {},
"tags": [
{
"description": "Users Tag Markdown Description",
"name": "users"
}
]
}`
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
p = New()
err = p.ParseGeneralAPIInfo(mainAPIFile)
assert.Error(t, err)
}
func TestParser_ParseGeneralApiInfoFailed(t *testing.T) {
t.Parallel()
gopath := os.Getenv("GOPATH")
assert.NotNil(t, gopath)
p := New()
assert.Error(t, p.ParseGeneralAPIInfo("testdata/noexist.go"))
}
func TestParser_ParseAcceptComment(t *testing.T) {
t.Parallel()
expected := []string{
"application/json",
"text/xml",
"text/plain",
"text/html",
"multipart/form-data",
"application/x-www-form-urlencoded",
"application/vnd.api+json",
"application/x-json-stream",
"application/octet-stream",
"image/png",
"image/jpeg",
"image/gif",
"application/xhtml+xml",
"application/health+json",
}
comment := `@Accept json,xml,plain,html,mpfd,x-www-form-urlencoded,json-api,json-stream,octet-stream,png,jpeg,gif,application/xhtml+xml,application/health+json`
parser := New()
assert.NoError(t, parseGeneralAPIInfo(parser, []string{comment}))
assert.Equal(t, parser.swagger.Consumes, expected)
assert.Error(t, parseGeneralAPIInfo(parser, []string{`@Accept cookies,candies`}))
parser = New()
assert.NoError(t, parser.ParseAcceptComment(comment[len(acceptAttr)+1:]))
assert.Equal(t, parser.swagger.Consumes, expected)
}
func TestParser_ParseProduceComment(t *testing.T) {
t.Parallel()
expected := []string{
"application/json",
"text/xml",
"text/plain",
"text/html",
"multipart/form-data",
"application/x-www-form-urlencoded",
"application/vnd.api+json",
"application/x-json-stream",
"application/octet-stream",
"image/png",
"image/jpeg",
"image/gif",
"application/xhtml+xml",
"application/health+json",
}
comment := `@Produce json,xml,plain,html,mpfd,x-www-form-urlencoded,json-api,json-stream,octet-stream,png,jpeg,gif,application/xhtml+xml,application/health+json`
parser := New()
assert.NoError(t, parseGeneralAPIInfo(parser, []string{comment}))
assert.Equal(t, parser.swagger.Produces, expected)
assert.Error(t, parseGeneralAPIInfo(parser, []string{`@Produce cookies,candies`}))
parser = New()
assert.NoError(t, parser.ParseProduceComment(comment[len(produceAttr)+1:]))
assert.Equal(t, parser.swagger.Produces, expected)
}
func TestParser_ParseGeneralAPIInfoCollectionFromat(t *testing.T) {
t.Parallel()
parser := New()
assert.NoError(t, parseGeneralAPIInfo(parser, []string{
"@query.collection.format csv",
}))
assert.Equal(t, parser.collectionFormatInQuery, "csv")
assert.NoError(t, parseGeneralAPIInfo(parser, []string{
"@query.collection.format tsv",
}))
assert.Equal(t, parser.collectionFormatInQuery, "tsv")
}
func TestParser_ParseGeneralAPITagGroups(t *testing.T) {
t.Parallel()
parser := New()
assert.NoError(t, parseGeneralAPIInfo(parser, []string{
"@x-tagGroups [{\"name\":\"General\",\"tags\":[\"lanes\",\"video-recommendations\"]}]",
}))
expected := []interface{}{map[string]interface{}{"name": "General", "tags": []interface{}{"lanes", "video-recommendations"}}}
assert.Equal(t, parser.swagger.Extensions["x-tagGroups"], expected)
}
func TestParser_ParseGeneralAPITagDocs(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@tag.name Test",
"@tag.docs.description Best example documentation"}))
parser = New()
err := parseGeneralAPIInfo(parser, []string{
"@tag.name test",
"@tag.description A test Tag",
"@tag.docs.url https://example.com",
"@tag.docs.description Best example documentation"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().Tags, "", " ")
expected := `[
{
"description": "A test Tag",
"name": "test",
"externalDocs": {
"description": "Best example documentation",
"url": "https://example.com"
}
}
]`
assert.Equal(t, expected, string(b))
}
func TestParser_ParseGeneralAPISecurity(t *testing.T) {
t.Run("ApiKey", func(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.apikey ApiKey"}))
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.apikey ApiKey",
"@in header"}))
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.apikey ApiKey",
"@name X-API-KEY"}))
err := parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.apikey ApiKey",
"@in header",
"@name X-API-KEY"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().SecurityDefinitions, "", " ")
expected := `{
"ApiKey": {
"type": "apiKey",
"name": "X-API-KEY",
"in": "header"
}
}`
assert.Equal(t, expected, string(b))
})
t.Run("OAuth2Application", func(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.application OAuth2Application"}))
err := parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.application OAuth2Application",
"@tokenUrl https://example.com/oauth/token"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().SecurityDefinitions, "", " ")
expected := `{
"OAuth2Application": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://example.com/oauth/token"
}
}`
assert.Equal(t, expected, string(b))
})
t.Run("OAuth2Implicit", func(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.implicit OAuth2Implicit"}))
err := parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.implicit OAuth2Implicit",
"@authorizationurl https://example.com/oauth/authorize"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().SecurityDefinitions, "", " ")
expected := `{
"OAuth2Implicit": {
"type": "oauth2",
"flow": "implicit",
"authorizationUrl": "https://example.com/oauth/authorize"
}
}`
assert.Equal(t, expected, string(b))
})
t.Run("OAuth2Password", func(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.password OAuth2Password"}))
err := parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.password OAuth2Password",
"@tokenUrl https://example.com/oauth/token"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().SecurityDefinitions, "", " ")
expected := `{
"OAuth2Password": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "https://example.com/oauth/token"
}
}`
assert.Equal(t, expected, string(b))
})
t.Run("OAuth2AccessCode", func(t *testing.T) {
t.Parallel()
parser := New()
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.accessCode OAuth2AccessCode"}))
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.accessCode OAuth2AccessCode",
"@tokenUrl https://example.com/oauth/token"}))
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.accessCode OAuth2AccessCode",
"@authorizationurl https://example.com/oauth/authorize"}))
err := parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.accessCode OAuth2AccessCode",
"@tokenUrl https://example.com/oauth/token",
"@authorizationurl https://example.com/oauth/authorize"})
assert.NoError(t, err)
b, _ := json.MarshalIndent(parser.GetSwagger().SecurityDefinitions, "", " ")
expected := `{
"OAuth2AccessCode": {
"type": "oauth2",
"flow": "accessCode",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token"
}
}`
assert.Equal(t, expected, string(b))
assert.Error(t, parseGeneralAPIInfo(parser, []string{
"@securitydefinitions.oauth2.accessCode OAuth2AccessCode",
"@tokenUrl https://example.com/oauth/token",
"@authorizationurl https://example.com/oauth/authorize",
"@scope.read,write Multiple scope"}))
})
}
func TestParser_RefWithOtherPropertiesIsWrappedInAllOf(t *testing.T) {
t.Run("Readonly", func(t *testing.T) {
src := `
package main
type Teacher struct {
Name string
} //@name Teacher
type Student struct {
Name string
Age int ` + "`readonly:\"true\"`" + `
Teacher Teacher ` + "`readonly:\"true\"`" + `
OtherTeacher Teacher
} //@name Student
// @Success 200 {object} Student
// @Router /test [get]
func Fun() {
}
`
expected := `{
"info": {
"contact": {}
},
"paths": {
"/test": {
"get": {
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/Student"
}
}
}
}
}
},
"definitions": {
"Student": {
"type": "object",
"properties": {
"age": {
"type": "integer",
"readOnly": true
},
"name": {
"type": "string"
},
"otherTeacher": {
"$ref": "#/definitions/Teacher"
},
"teacher": {
"allOf": [
{
"$ref": "#/definitions/Teacher"
}
],
"readOnly": true
}
}
},
"Teacher": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
}
}
}`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
})
}
func TestGetAllGoFileInfo(t *testing.T) {
t.Parallel()
searchDir := "testdata/pet"
p := New()
err := p.getAllGoFileInfo("testdata", searchDir)
assert.NoError(t, err)
assert.Equal(t, 2, len(p.packages.files))
}
func TestParser_ParseType(t *testing.T) {
t.Parallel()
searchDir := "testdata/simple/"
p := New()
err := p.getAllGoFileInfo("testdata", searchDir)
assert.NoError(t, err)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
assert.NotNil(t, p.packages.uniqueDefinitions["api.Pet3"])
assert.NotNil(t, p.packages.uniqueDefinitions["web.Pet"])
assert.NotNil(t, p.packages.uniqueDefinitions["web.Pet2"])
}
func TestGetSchemes(t *testing.T) {
t.Parallel()
schemes := getSchemes("@schemes http https")
expectedSchemes := []string{"http", "https"}
assert.Equal(t, expectedSchemes, schemes)
}
func TestParseSimpleApi1(t *testing.T) {
t.Parallel()
expected, err := ioutil.ReadFile("testdata/simple/expected.json")
assert.NoError(t, err)
searchDir := "testdata/simple"
p := New()
p.PropNamingStrategy = PascalCase
err = p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.JSONEq(t, string(expected), string(b))
}
func TestParseSimpleApi_ForSnakecase(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0"
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {
"/file/upload": {
"post": {
"description": "Upload file",
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json"
],
"summary": "Upload file",
"operationId": "file.upload",
"parameters": [
{
"type": "file",
"description": "this is a test file",
"name": "file",
"in": "formData",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
},
"/testapi/get-string-by-int/{some_id}": {
"get": {
"description": "get string by ID",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Add a new pet to the store",
"operationId": "get-string-by-int",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "Some ID",
"name": "some_id",
"in": "path",
"required": true
},
{
"description": "Some ID",
"name": "some_id",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/web.Pet"
}
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
},
"/testapi/get-struct-array-by-string/{some_id}": {
"get": {
"security": [
{
"ApiKeyAuth": []
},
{
"BasicAuth": []
},
{
"OAuth2Application": [
"write"
]
},
{
"OAuth2Implicit": [
"read",
"admin"
]
},
{
"OAuth2AccessCode": [
"read"
]
},
{
"OAuth2Password": [
"admin"
]
}
],
"description": "get struct array by ID",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"operationId": "get-struct-array-by-string",
"parameters": [
{
"type": "string",
"description": "Some ID",
"name": "some_id",
"in": "path",
"required": true
},
{
"enum": [
1,
2,
3
],
"type": "integer",
"description": "Category",
"name": "category",
"in": "query",
"required": true
},
{
"minimum": 0,
"type": "integer",
"default": 0,
"description": "Offset",
"name": "offset",
"in": "query",
"required": true
},
{
"maximum": 50,
"type": "integer",
"default": 10,
"description": "Limit",
"name": "limit",
"in": "query",
"required": true
},
{
"maxLength": 50,
"minLength": 1,
"type": "string",
"default": "\"\"",
"description": "q",
"name": "q",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
}
},
"definitions": {
"web.APIError": {
"type": "object",
"properties": {
"created_at": {
"type": "string"
},
"error_code": {
"type": "integer"
},
"error_message": {
"type": "string"
}
}
},
"web.Pet": {
"type": "object",
"required": [
"price"
],
"properties": {
"birthday": {
"type": "integer"
},
"category": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "category_name"
},
"photo_urls": {
"type": "array",
"items": {
"type": "string",
"format": "url"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
},
"small_category": {
"type": "object",
"required": [
"name"
],
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "detail_category_name"
},
"photo_urls": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
}
}
}
}
},
"coeffs": {
"type": "array",
"items": {
"type": "number"
}
},
"custom_string": {
"type": "string"
},
"custom_string_arr": {
"type": "array",
"items": {
"type": "string"
}
},
"data": {},
"decimal": {
"type": "number"
},
"id": {
"type": "integer",
"format": "int64",
"example": 1
},
"is_alive": {
"type": "boolean",
"example": true
},
"name": {
"type": "string",
"example": "poti"
},
"null_int": {
"type": "integer"
},
"pets": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet2"
}
},
"pets2": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet2"
}
},
"photo_urls": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
},
"price": {
"type": "number",
"maximum": 130,
"minimum": 0,
"multipleOf": 0.01,
"example": 3.25
},
"status": {
"type": "string"
},
"tags": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Tag"
}
},
"uuid": {
"type": "string"
}
}
},
"web.Pet2": {
"type": "object",
"properties": {
"deleted_at": {
"type": "string"
},
"id": {
"type": "integer"
},
"middle_name": {
"type": "string"
}
}
},
"web.RevValue": {
"type": "object",
"properties": {
"data": {
"type": "integer"
},
"err": {
"type": "integer"
},
"status": {
"type": "boolean"
}
}
},
"web.Tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"pets": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet"
}
}
}
}
},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
"BasicAuth": {
"type": "basic"
},
"OAuth2AccessCode": {
"type": "oauth2",
"flow": "accessCode",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information"
}
},
"OAuth2Application": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Implicit": {
"type": "oauth2",
"flow": "implicit",
"authorizationUrl": "https://example.com/oauth/authorize",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Password": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"read": " Grants read access",
"write": " Grants write access"
}
}
}
}`
searchDir := "testdata/simple2"
p := New()
p.PropNamingStrategy = SnakeCase
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseSimpleApi_ForLowerCamelcase(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0"
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {
"/file/upload": {
"post": {
"description": "Upload file",
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json"
],
"summary": "Upload file",
"operationId": "file.upload",
"parameters": [
{
"type": "file",
"description": "this is a test file",
"name": "file",
"in": "formData",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
},
"/testapi/get-string-by-int/{some_id}": {
"get": {
"description": "get string by ID",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Add a new pet to the store",
"operationId": "get-string-by-int",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "Some ID",
"name": "some_id",
"in": "path",
"required": true
},
{
"description": "Some ID",
"name": "some_id",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/web.Pet"
}
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
},
"/testapi/get-struct-array-by-string/{some_id}": {
"get": {
"security": [
{
"ApiKeyAuth": []
},
{
"BasicAuth": []
},
{
"OAuth2Application": [
"write"
]
},
{
"OAuth2Implicit": [
"read",
"admin"
]
},
{
"OAuth2AccessCode": [
"read"
]
},
{
"OAuth2Password": [
"admin"
]
}
],
"description": "get struct array by ID",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"operationId": "get-struct-array-by-string",
"parameters": [
{
"type": "string",
"description": "Some ID",
"name": "some_id",
"in": "path",
"required": true
},
{
"enum": [
1,
2,
3
],
"type": "integer",
"description": "Category",
"name": "category",
"in": "query",
"required": true
},
{
"minimum": 0,
"type": "integer",
"default": 0,
"description": "Offset",
"name": "offset",
"in": "query",
"required": true
},
{
"maximum": 50,
"type": "integer",
"default": 10,
"description": "Limit",
"name": "limit",
"in": "query",
"required": true
},
{
"maxLength": 50,
"minLength": 1,
"type": "string",
"default": "\"\"",
"description": "q",
"name": "q",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
}
},
"definitions": {
"web.APIError": {
"type": "object",
"properties": {
"createdAt": {
"type": "string"
},
"errorCode": {
"type": "integer"
},
"errorMessage": {
"type": "string"
}
}
},
"web.Pet": {
"type": "object",
"properties": {
"category": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "category_name"
},
"photoURLs": {
"type": "array",
"items": {
"type": "string",
"format": "url"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
},
"smallCategory": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "detail_category_name"
},
"photoURLs": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
}
}
}
}
},
"data": {},
"decimal": {
"type": "number"
},
"id": {
"type": "integer",
"format": "int64",
"example": 1
},
"isAlive": {
"type": "boolean",
"example": true
},
"name": {
"type": "string",
"example": "poti"
},
"pets": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet2"
}
},
"pets2": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet2"
}
},
"photoURLs": {
"type": "array",
"items": {
"type": "string"
},
"example": [
"http://test/image/1.jpg",
"http://test/image/2.jpg"
]
},
"price": {
"type": "number",
"multipleOf": 0.01,
"example": 3.25
},
"status": {
"type": "string"
},
"tags": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Tag"
}
},
"uuid": {
"type": "string"
}
}
},
"web.Pet2": {
"type": "object",
"properties": {
"deletedAt": {
"type": "string"
},
"id": {
"type": "integer"
},
"middleName": {
"type": "string"
}
}
},
"web.RevValue": {
"type": "object",
"properties": {
"data": {
"type": "integer"
},
"err": {
"type": "integer"
},
"status": {
"type": "boolean"
}
}
},
"web.Tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"pets": {
"type": "array",
"items": {
"$ref": "#/definitions/web.Pet"
}
}
}
}
},
"securityDefinitions": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
},
"BasicAuth": {
"type": "basic"
},
"OAuth2AccessCode": {
"type": "oauth2",
"flow": "accessCode",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information"
}
},
"OAuth2Application": {
"type": "oauth2",
"flow": "application",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Implicit": {
"type": "oauth2",
"flow": "implicit",
"authorizationUrl": "https://example.com/oauth/authorize",
"scopes": {
"admin": " Grants read and write access to administrative information",
"write": " Grants write access"
}
},
"OAuth2Password": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "https://example.com/oauth/token",
"scopes": {
"admin": " Grants read and write access to administrative information",
"read": " Grants read access",
"write": " Grants write access"
}
}
}
}`
searchDir := "testdata/simple3"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseStructComment(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Swagger Example API",
"contact": {},
"version": "1.0"
},
"host": "localhost:4000",
"basePath": "/api",
"paths": {
"/posts/{post_id}": {
"get": {
"description": "get string by ID",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Add a new pet to the store",
"parameters": [
{
"type": "integer",
"format": "int64",
"description": "Some ID",
"name": "post_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
},
"400": {
"description": "We need ID!!",
"schema": {
"$ref": "#/definitions/web.APIError"
}
},
"404": {
"description": "Can not find ID",
"schema": {
"$ref": "#/definitions/web.APIError"
}
}
}
}
}
},
"definitions": {
"web.APIError": {
"type": "object",
"properties": {
"createdAt": {
"description": "Error time",
"type": "string"
},
"error": {
"description": "Error an Api error",
"type": "string"
},
"errorCtx": {
"description": "Error ` + "`" + `context` + "`" + ` tick comment",
"type": "string"
},
"errorNo": {
"description": "Error ` + "`" + `number` + "`" + ` tick comment",
"type": "integer"
}
}
}
}
}`
searchDir := "testdata/struct_comment"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseNonExportedJSONFields(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server.",
"title": "Swagger Example API",
"contact": {},
"version": "1.0"
},
"host": "localhost:4000",
"basePath": "/api",
"paths": {
"/so-something": {
"get": {
"description": "Does something, but internal (non-exported) fields inside a struct won't be marshaled into JSON",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Call DoSomething",
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/main.MyStruct"
}
}
}
}
}
},
"definitions": {
"main.MyStruct": {
"type": "object",
"properties": {
"data": {
"description": "Post data",
"type": "object",
"properties": {
"name": {
"description": "Post tag",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"id": {
"type": "integer",
"format": "int64",
"example": 1
},
"name": {
"description": "Post name",
"type": "string",
"example": "poti"
}
}
}
}
}`
searchDir := "testdata/non_exported_json_fields"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParsePetApi(t *testing.T) {
t.Parallel()
expected := `{
"schemes": [
"http",
"https"
],
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key 'special-key' to test the authorization filters.",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0"
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {}
}`
searchDir := "testdata/pet"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseModelAsTypeAlias(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0"
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {
"/testapi/time-as-time-container": {
"get": {
"description": "test container with time and time alias",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Get container with time and time alias",
"operationId": "time-as-time-container",
"responses": {
"200": {
"description": "ok",
"schema": {
"$ref": "#/definitions/data.TimeContainer"
}
}
}
}
}
},
"definitions": {
"data.TimeContainer": {
"type": "object",
"properties": {
"created_at": {
"type": "string"
},
"name": {
"type": "string"
},
"timestamp": {
"type": "string"
}
}
}
}
}`
searchDir := "testdata/alias_type"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseComposition(t *testing.T) {
t.Parallel()
searchDir := "testdata/composition"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
expected, err := ioutil.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
// windows will fail: \r\n \n
assert.Equal(t, string(expected), string(b))
}
func TestParseImportAliases(t *testing.T) {
t.Parallel()
searchDir := "testdata/alias_import"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
expected, err := ioutil.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
// windows will fail: \r\n \n
assert.Equal(t, string(expected), string(b))
}
func TestParseNested(t *testing.T) {
t.Parallel()
searchDir := "testdata/nested"
p := New()
p.ParseDependency = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
expected, err := ioutil.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, string(expected), string(b))
}
func TestParseDuplicated(t *testing.T) {
t.Parallel()
searchDir := "testdata/duplicated"
p := New()
p.ParseDependency = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.Errorf(t, err, "duplicated @id declarations successfully found")
}
func TestParseDuplicatedOtherMethods(t *testing.T) {
t.Parallel()
searchDir := "testdata/duplicated2"
p := New()
p.ParseDependency = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.Errorf(t, err, "duplicated @id declarations successfully found")
}
func TestParseConflictSchemaName(t *testing.T) {
t.Parallel()
searchDir := "testdata/conflict_name"
p := New()
p.ParseDependency = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
expected, err := ioutil.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
assert.Equal(t, string(expected), string(b))
}
func TestParseExternalModels(t *testing.T) {
searchDir := "testdata/external_models/main"
mainAPIFile := "main.go"
p := New()
p.ParseDependency = true
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
//ioutil.WriteFile("./testdata/external_models/main/expected.json",b,0777)
expected, err := ioutil.ReadFile(filepath.Join(searchDir, "expected.json"))
assert.NoError(t, err)
assert.Equal(t, string(expected), string(b))
}
func TestParser_ParseStructArrayObject(t *testing.T) {
t.Parallel()
src := `
package api
type Response struct {
Code int
Table [][]string
Data []struct{
Field1 uint
Field2 string
}
}
// @Success 200 {object} Response
// @Router /api/{id} [get]
func Test(){
}
`
expected := `{
"api.Response": {
"type": "object",
"properties": {
"code": {
"type": "integer"
},
"data": {
"type": "array",
"items": {
"type": "object",
"properties": {
"field1": {
"type": "integer"
},
"field2": {
"type": "string"
}
}
}
},
"table": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
out, err := json.MarshalIndent(p.swagger.Definitions, "", " ")
assert.NoError(t, err)
assert.Equal(t, expected, string(out))
}
func TestParser_ParseEmbededStruct(t *testing.T) {
t.Parallel()
src := `
package api
type Response struct {
rest.ResponseWrapper
}
// @Success 200 {object} Response
// @Router /api/{id} [get]
func Test(){
}
`
restsrc := `
package rest
type ResponseWrapper struct {
Status string
Code int
Messages []string
Result interface{}
}
`
expected := `{
"api.Response": {
"type": "object",
"properties": {
"code": {
"type": "integer"
},
"messages": {
"type": "array",
"items": {
"type": "string"
}
},
"result": {},
"status": {
"type": "string"
}
}
}
}`
parser := New()
parser.ParseDependency = true
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
_ = parser.packages.CollectAstFile("api", "api/api.go", f)
f2, err := goparser.ParseFile(token.NewFileSet(), "", restsrc, goparser.ParseComments)
assert.NoError(t, err)
_ = parser.packages.CollectAstFile("rest", "rest/rest.go", f2)
_, err = parser.packages.ParseTypes()
assert.NoError(t, err)
err = parser.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
out, err := json.MarshalIndent(parser.swagger.Definitions, "", " ")
assert.NoError(t, err)
assert.Equal(t, expected, string(out))
}
func TestParser_ParseStructPointerMembers(t *testing.T) {
t.Parallel()
src := `
package api
type Child struct {
Name string
}
type Parent struct {
Test1 *string //test1
Test2 *Child //test2
}
// @Success 200 {object} Parent
// @Router /api/{id} [get]
func Test(){
}
`
expected := `{
"api.Child": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"api.Parent": {
"type": "object",
"properties": {
"test1": {
"description": "test1",
"type": "string"
},
"test2": {
"description": "test2",
"$ref": "#/definitions/api.Child"
}
}
}
}`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
out, err := json.MarshalIndent(p.swagger.Definitions, "", " ")
assert.NoError(t, err)
assert.Equal(t, expected, string(out))
}
func TestParser_ParseStructMapMember(t *testing.T) {
t.Parallel()
src := `
package api
type MyMapType map[string]string
type Child struct {
Name string
}
type Parent struct {
Test1 map[string]interface{} //test1
Test2 map[string]string //test2
Test3 map[string]*string //test3
Test4 map[string]Child //test4
Test5 map[string]*Child //test5
Test6 MyMapType //test6
Test7 []Child //test7
Test8 []*Child //test8
Test9 []map[string]string //test9
}
// @Success 200 {object} Parent
// @Router /api/{id} [get]
func Test(){
}
`
expected := `{
"api.Child": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"api.MyMapType": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"api.Parent": {
"type": "object",
"properties": {
"test1": {
"description": "test1",
"type": "object",
"additionalProperties": true
},
"test2": {
"description": "test2",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"test3": {
"description": "test3",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"test4": {
"description": "test4",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/api.Child"
}
},
"test5": {
"description": "test5",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/api.Child"
}
},
"test6": {
"description": "test6",
"$ref": "#/definitions/api.MyMapType"
},
"test7": {
"description": "test7",
"type": "array",
"items": {
"$ref": "#/definitions/api.Child"
}
},
"test8": {
"description": "test8",
"type": "array",
"items": {
"$ref": "#/definitions/api.Child"
}
},
"test9": {
"description": "test9",
"type": "array",
"items": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
}`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
out, err := json.MarshalIndent(p.swagger.Definitions, "", " ")
assert.NoError(t, err)
assert.Equal(t, expected, string(out))
}
func TestParser_ParseRouterApiInfoErr(t *testing.T) {
t.Parallel()
src := `
package test
// @Accept unknown
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.EqualError(t, err, "ParseComment error in file :unknown accept type can't be accepted")
}
func TestParser_ParseRouterApiGet(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [get]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Get)
}
func TestParser_ParseRouterApiPOST(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [post]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Post)
}
func TestParser_ParseRouterApiDELETE(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [delete]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Delete)
}
func TestParser_ParseRouterApiPUT(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [put]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Put)
}
func TestParser_ParseRouterApiPATCH(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [patch]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Patch)
}
func TestParser_ParseRouterApiHead(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [head]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Head)
}
func TestParser_ParseRouterApiOptions(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [options]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Options)
}
func TestParser_ParseRouterApiMultipleRoutesForSameFunction(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/v1/{id} [get]
// @Router /api/v2/{id} [post]
func Test(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/v1/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Get)
val, ok = ps["/api/v2/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Post)
}
func TestParser_ParseRouterApiMultiple(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [get]
func Test1(){
}
// @Router /api/{id} [patch]
func Test2(){
}
// @Router /api/{id} [delete]
func Test3(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
ps := p.swagger.Paths.Paths
val, ok := ps["/api/{id}"]
assert.True(t, ok)
assert.NotNil(t, val.Get)
assert.NotNil(t, val.Patch)
assert.NotNil(t, val.Delete)
}
// func TestParseDeterministic(t *testing.T) {
// mainAPIFile := "main.go"
// for _, searchDir := range []string{
// "testdata/simple",
// "testdata/model_not_under_root/cmd",
// } {
// t.Run(searchDir, func(t *testing.T) {
// var expected string
// // run the same code 100 times and check that the output is the same every time
// for i := 0; i < 100; i++ {
// p := New()
// p.PropNamingStrategy = PascalCase
// err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
// b, _ := json.MarshalIndent(p.swagger, "", " ")
// assert.NotEqual(t, "", string(b))
// if expected == "" {
// expected = string(b)
// }
// assert.Equal(t, expected, string(b))
// }
// })
// }
// }
func TestParser_ParseRouterApiDuplicateRoute(t *testing.T) {
t.Parallel()
src := `
package test
// @Router /api/{id} [get]
func Test1(){
}
// @Router /api/{id} [get]
func Test2(){
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New(SetStrict(true))
err = p.ParseRouterAPIInfo("", f)
assert.EqualError(t, err, "route GET /api/{id} is declared multiple times")
p = New()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
}
func TestApiParseTag(t *testing.T) {
t.Parallel()
searchDir := "testdata/tags"
p := New(SetMarkdownFileDirectory(searchDir))
p.PropNamingStrategy = PascalCase
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
if len(p.swagger.Tags) != 3 {
t.Error("Number of tags did not match")
}
dogs := p.swagger.Tags[0]
if dogs.TagProps.Name != "dogs" || dogs.TagProps.Description != "Dogs are cool" {
t.Error("Failed to parse dogs name or description")
}
cats := p.swagger.Tags[1]
if cats.TagProps.Name != "cats" || cats.TagProps.Description != "Cats are the devil" {
t.Error("Failed to parse cats name or description")
}
if cats.TagProps.ExternalDocs.URL != "https://google.de" || cats.TagProps.ExternalDocs.Description != "google is super useful to find out that cats are evil!" {
t.Error("URL: ", cats.TagProps.ExternalDocs.URL)
t.Error("Description: ", cats.TagProps.ExternalDocs.Description)
t.Error("Failed to parse cats external documentation")
}
}
func TestApiParseTag_NonExistendTag(t *testing.T) {
t.Parallel()
searchDir := "testdata/tags_nonexistend_tag"
p := New(SetMarkdownFileDirectory(searchDir))
p.PropNamingStrategy = PascalCase
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.Error(t, err)
}
func TestParseTagMarkdownDescription(t *testing.T) {
t.Parallel()
searchDir := "testdata/tags"
p := New(SetMarkdownFileDirectory(searchDir))
p.PropNamingStrategy = PascalCase
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
if err != nil {
t.Error("Failed to parse api description: " + err.Error())
}
if len(p.swagger.Tags) != 3 {
t.Error("Number of tags did not match")
}
apes := p.swagger.Tags[2]
if apes.TagProps.Description == "" {
t.Error("Failed to parse tag description markdown file")
}
}
func TestParseApiMarkdownDescription(t *testing.T) {
t.Parallel()
searchDir := "testdata/tags"
p := New(SetMarkdownFileDirectory(searchDir))
p.PropNamingStrategy = PascalCase
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
if err != nil {
t.Error("Failed to parse api description: " + err.Error())
}
if p.swagger.Info.Description == "" {
t.Error("Failed to parse api description: " + err.Error())
}
}
func TestIgnoreInvalidPkg(t *testing.T) {
t.Parallel()
searchDir := "testdata/deps_having_invalid_pkg"
p := New()
if err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth); err != nil {
t.Error("Failed to ignore valid pkg: " + err.Error())
}
}
func TestFixes432(t *testing.T) {
t.Parallel()
searchDir := "testdata/fixes-432"
mainAPIFile := "cmd/main.go"
p := New()
if err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth); err != nil {
t.Error("Failed to ignore valid pkg: " + err.Error())
}
}
func TestParseOutsideDependencies(t *testing.T) {
t.Parallel()
searchDir := "testdata/pare_outside_dependencies"
mainAPIFile := "cmd/main.go"
p := New()
p.ParseDependency = true
if err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth); err != nil {
t.Error("Failed to parse api: " + err.Error())
}
}
func TestParseStructParamCommentByQueryType(t *testing.T) {
t.Parallel()
src := `
package main
type Student struct {
Name string
Age int
Teachers []string
SkipField map[string]string
}
// @Param request query Student true "query params"
// @Success 200
// @Router /test [get]
func Fun() {
}
`
expected := `{
"info": {
"contact": {}
},
"paths": {
"/test": {
"get": {
"parameters": [
{
"type": "integer",
"name": "age",
"in": "query"
},
{
"type": "string",
"name": "name",
"in": "query"
},
{
"type": "array",
"items": {
"type": "string"
},
"name": "teachers",
"in": "query"
}
],
"responses": {
"200": {
"description": ""
}
}
}
}
}
}`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseRenamedStructDefinition(t *testing.T) {
t.Parallel()
src := `
package main
type Child struct {
Name string
}//@name Student
type Parent struct {
Name string
Child Child
}//@name Teacher
// @Param request body Parent true "query params"
// @Success 200 {object} Parent
// @Router /test [get]
func Fun() {
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, err = p.packages.ParseTypes()
assert.NoError(t, err)
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
assert.NoError(t, err)
teacher, ok := p.swagger.Definitions["Teacher"]
assert.True(t, ok)
ref := teacher.Properties["child"].SchemaProps.Ref
assert.Equal(t, "#/definitions/Student", ref.String())
_, ok = p.swagger.Definitions["Student"]
assert.True(t, ok)
path, ok := p.swagger.Paths.Paths["/test"]
assert.True(t, ok)
assert.Equal(t, "#/definitions/Teacher", path.Get.Parameters[0].Schema.Ref.String())
ref = path.Get.Responses.ResponsesProps.StatusCodeResponses[200].ResponseProps.Schema.Ref
assert.Equal(t, "#/definitions/Teacher", ref.String())
}
func TestPackagesDefinitions_CollectAstFileInit(t *testing.T) {
t.Parallel()
src := `
package main
// @Router /test [get]
func Fun() {
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
pkgs := NewPackagesDefinitions()
// unset the .files and .packages and check that they're re-initialized by CollectAstFile
pkgs.packages = nil
pkgs.files = nil
_ = pkgs.CollectAstFile("api", "api/api.go", f)
assert.NotNil(t, pkgs.packages)
assert.NotNil(t, pkgs.files)
}
func TestCollectAstFileMultipleTimes(t *testing.T) {
t.Parallel()
src := `
package main
// @Router /test [get]
func Fun() {
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
assert.NotNil(t, p.packages.files[f])
astFileInfo := p.packages.files[f]
// if we collect the same again nothing should happen
_ = p.packages.CollectAstFile("api", "api/api.go", f)
assert.Equal(t, astFileInfo, p.packages.files[f])
}
func TestParseJSONFieldString(t *testing.T) {
t.Parallel()
expected := `{
"swagger": "2.0",
"info": {
"description": "This is a sample server.",
"title": "Swagger Example API",
"contact": {},
"version": "1.0"
},
"host": "localhost:4000",
"basePath": "/",
"paths": {
"/do-something": {
"post": {
"description": "Does something",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "Call DoSomething",
"parameters": [
{
"description": "My Struct",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/main.MyStruct"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/main.MyStruct"
}
},
"500": {
"description": ""
}
}
}
}
},
"definitions": {
"main.MyStruct": {
"type": "object",
"properties": {
"boolvar": {
"description": "boolean as a string",
"type": "string",
"example": "false"
},
"floatvar": {
"description": "float as a string",
"type": "string",
"example": "0"
},
"id": {
"type": "integer",
"format": "int64",
"example": 1
},
"myint": {
"description": "integer as string",
"type": "string",
"example": "0"
},
"name": {
"type": "string",
"example": "poti"
},
"truebool": {
"description": "boolean as a string",
"type": "string",
"example": "true"
},
"uuids": {
"description": "string array with format",
"type": "array",
"items": {
"type": "string",
"format": "uuid"
}
}
}
}
}
}`
searchDir := "testdata/json_field_string"
p := New()
err := p.ParseAPI(searchDir, mainAPIFile, defaultParseDepth)
assert.NoError(t, err)
b, _ := json.MarshalIndent(p.swagger, "", " ")
assert.Equal(t, expected, string(b))
}
func TestParseSwaggerignoreForEmbedded(t *testing.T) {
t.Parallel()
src := `
package main
type Child struct {
ChildName string
}//@name Student
type Parent struct {
Name string
Child ` + "`swaggerignore:\"true\"`" + `
}//@name Teacher
// @Param request body Parent true "query params"
// @Success 200 {object} Parent
// @Router /test [get]
func Fun() {
}
`
f, err := goparser.ParseFile(token.NewFileSet(), "", src, goparser.ParseComments)
assert.NoError(t, err)
p := New()
_ = p.packages.CollectAstFile("api", "api/api.go", f)
_, _ = p.packages.ParseTypes()
err = p.ParseRouterAPIInfo("", f)
assert.NoError(t, err)
teacher, ok := p.swagger.Definitions["Teacher"]
assert.True(t, ok)
name, ok := teacher.Properties["name"]
assert.True(t, ok)
assert.Len(t, name.Type, 1)
assert.Equal(t, "string", name.Type[0])
childName, ok := teacher.Properties["childName"]
assert.False(t, ok)
assert.Empty(t, childName)
}
func TestDefineTypeOfExample(t *testing.T) {
t.Run("String type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("string", "", "example")
assert.NoError(t, err)
assert.Equal(t, example.(string), "example")
})
t.Run("Number type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("number", "", "12.34")
assert.NoError(t, err)
assert.Equal(t, example.(float64), 12.34)
_, err = defineTypeOfExample("number", "", "two")
assert.Error(t, err)
})
t.Run("Integer type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("integer", "", "12")
assert.NoError(t, err)
assert.Equal(t, example.(int), 12)
_, err = defineTypeOfExample("integer", "", "two")
assert.Error(t, err)
})
t.Run("Boolean type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("boolean", "", "true")
assert.NoError(t, err)
assert.Equal(t, example.(bool), true)
_, err = defineTypeOfExample("boolean", "", "!true")
assert.Error(t, err)
})
t.Run("Array type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("array", "", "one,two,three")
assert.Error(t, err)
assert.Nil(t, example)
example, err = defineTypeOfExample("array", "string", "one,two,three")
assert.NoError(t, err)
arr := []string{}
for _, v := range example.([]interface{}) {
arr = append(arr, v.(string))
}
assert.Equal(t, arr, []string{"one", "two", "three"})
})
t.Run("Object type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("object", "", "key_one:one,key_two:two,key_three:three")
assert.Error(t, err)
assert.Nil(t, example)
example, err = defineTypeOfExample("object", "string", "key_one,key_two,key_three")
assert.Error(t, err)
assert.Nil(t, example)
example, err = defineTypeOfExample("object", "oops", "key_one:one,key_two:two,key_three:three")
assert.Error(t, err)
assert.Nil(t, example)
example, err = defineTypeOfExample("object", "string", "key_one:one,key_two:two,key_three:three")
assert.NoError(t, err)
obj := map[string]string{}
for k, v := range example.(map[string]interface{}) {
obj[k] = v.(string)
}
assert.Equal(t, obj, map[string]string{"key_one": "one", "key_two": "two", "key_three": "three"})
})
t.Run("Invalid type", func(t *testing.T) {
t.Parallel()
example, err := defineTypeOfExample("oops", "", "")
assert.Error(t, err)
assert.Nil(t, example)
})
}
type mockFS struct {
os.FileInfo
FileName string
IsDirectory bool
}
func (fs *mockFS) Name() string {
return fs.FileName
}
func (fs *mockFS) IsDir() bool {
return fs.IsDirectory
}
func TestParser_Skip(t *testing.T) {
t.Parallel()
parser := New()
parser.ParseVendor = true
assert.NoError(t, parser.Skip("", &mockFS{FileName: "vendor"}))
assert.NoError(t, parser.Skip("", &mockFS{FileName: "vendor", IsDirectory: true}))
parser.ParseVendor = false
assert.NoError(t, parser.Skip("", &mockFS{FileName: "vendor"}))
assert.Error(t, parser.Skip("", &mockFS{FileName: "vendor", IsDirectory: true}))
assert.NoError(t, parser.Skip("", &mockFS{FileName: "models", IsDirectory: true}))
assert.NoError(t, parser.Skip("", &mockFS{FileName: "admin", IsDirectory: true}))
assert.NoError(t, parser.Skip("", &mockFS{FileName: "release", IsDirectory: true}))
parser = New(SetExcludedDirsAndFiles("admin/release,admin/models"))
assert.NoError(t, parser.Skip("admin", &mockFS{IsDirectory: true}))
assert.NoError(t, parser.Skip(filepath.Clean("admin/service"), &mockFS{IsDirectory: true}))
assert.Error(t, parser.Skip(filepath.Clean("admin/models"), &mockFS{IsDirectory: true}))
assert.Error(t, parser.Skip(filepath.Clean("admin/release"), &mockFS{IsDirectory: true}))
}
func TestGetFieldType(t *testing.T) {
t.Parallel()
field, err := getFieldType(&ast.Ident{Name: "User"})
assert.NoError(t, err)
assert.Equal(t, "User", field)
_, err = getFieldType(&ast.FuncType{})
assert.Error(t, err)
field, err = getFieldType(&ast.SelectorExpr{X: &ast.Ident{Name: "models"}, Sel: &ast.Ident{Name: "User"}})
assert.NoError(t, err)
assert.Equal(t, "models.User", field)
_, err = getFieldType(&ast.SelectorExpr{X: &ast.FuncType{}, Sel: &ast.Ident{Name: "User"}})
assert.Error(t, err)
field, err = getFieldType(&ast.StarExpr{X: &ast.Ident{Name: "User"}})
assert.NoError(t, err)
assert.Equal(t, "User", field)
field, err = getFieldType(&ast.StarExpr{X: &ast.FuncType{}})
assert.Error(t, err)
field, err = getFieldType(&ast.StarExpr{X: &ast.SelectorExpr{X: &ast.Ident{Name: "models"}, Sel: &ast.Ident{Name: "User"}}})
assert.NoError(t, err)
assert.Equal(t, "models.User", field)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/brucelin-cn/swag.git
git@gitee.com:brucelin-cn/swag.git
brucelin-cn
swag
swag
master

搜索帮助