How to use parseComment method of ast Package

Best Syzkaller code snippet using ast.parseComment

operation_test.go

Source:operation_test.go Github

copy

Full Screen

1package swag2import (3 "encoding/json"4 "go/ast"5 goparser "go/parser"6 "go/token"7 "testing"8 "github.com/go-openapi/spec"9 "github.com/stretchr/testify/assert"10)11func TestParseEmptyComment(t *testing.T) {12 operation := NewOperation()13 err := operation.ParseComment("//", nil)14 assert.NoError(t, err)15}16func TestParseTagsComment(t *testing.T) {17 expected := `{18 "tags": [19 "pet",20 "store",21 "user"22 ]23}`24 comment := `/@Tags pet, store,user`25 operation := NewOperation()26 err := operation.ParseComment(comment, nil)27 assert.NoError(t, err)28 b, _ := json.MarshalIndent(operation, "", " ")29 assert.Equal(t, expected, string(b))30}31func TestParseAcceptComment(t *testing.T) {32 expected := `{33 "consumes": [34 "application/json",35 "text/xml",36 "text/plain",37 "text/html",38 "multipart/form-data",39 "application/x-www-form-urlencoded",40 "application/vnd.api+json",41 "application/x-json-stream",42 "application/octet-stream",43 "image/png",44 "image/jpeg",45 "image/gif",46 "application/xhtml+xml",47 "application/health+json"48 ]49}`50 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`51 operation := NewOperation()52 err := operation.ParseComment(comment, nil)53 assert.NoError(t, err)54 b, _ := json.MarshalIndent(operation, "", " ")55 assert.JSONEq(t, expected, string(b))56}57func TestParseAcceptCommentErr(t *testing.T) {58 comment := `/@Accept unknown`59 operation := NewOperation()60 err := operation.ParseComment(comment, nil)61 assert.Error(t, err)62}63func TestParseProduceComment(t *testing.T) {64 expected := `{65 "produces": [66 "application/json",67 "text/xml",68 "text/plain",69 "text/html",70 "multipart/form-data",71 "application/x-www-form-urlencoded",72 "application/vnd.api+json",73 "application/x-json-stream",74 "application/octet-stream",75 "image/png",76 "image/jpeg",77 "image/gif",78 "application/health+json"79 ]80}`81 comment := `/@Produce json,xml,plain,html,mpfd,x-www-form-urlencoded,json-api,json-stream,octet-stream,png,jpeg,gif,application/health+json`82 operation := new(Operation)83 err := operation.ParseComment(comment, nil)84 assert.NoError(t, err, "ParseComment should not fail")85 b, _ := json.MarshalIndent(operation, "", " ")86 assert.JSONEq(t, expected, string(b))87}88func TestParseProduceCommentErr(t *testing.T) {89 comment := `/@Produce foo`90 operation := new(Operation)91 err := operation.ParseComment(comment, nil)92 assert.Error(t, err)93}94func TestParseRouterComment(t *testing.T) {95 comment := `/@Router /customer/get-wishlist/{wishlist_id} [get]`96 operation := NewOperation()97 err := operation.ParseComment(comment, nil)98 assert.NoError(t, err)99 assert.Equal(t, "/customer/get-wishlist/{wishlist_id}", operation.Path)100 assert.Equal(t, "GET", operation.HTTPMethod)101}102func TestParseRouterOnlySlash(t *testing.T) {103 comment := `// @Router / [get]`104 operation := NewOperation()105 err := operation.ParseComment(comment, nil)106 assert.NoError(t, err)107 assert.Equal(t, "/", operation.Path)108 assert.Equal(t, "GET", operation.HTTPMethod)109}110func TestParseRouterCommentWithPlusSign(t *testing.T) {111 comment := `/@Router /customer/get-wishlist/{proxy+} [post]`112 operation := NewOperation()113 err := operation.ParseComment(comment, nil)114 assert.NoError(t, err)115 assert.Equal(t, "/customer/get-wishlist/{proxy+}", operation.Path)116 assert.Equal(t, "POST", operation.HTTPMethod)117}118func TestParseRouterCommentWithColonSign(t *testing.T) {119 comment := `/@Router /customer/get-wishlist/{wishlist_id}:move [post]`120 operation := NewOperation()121 err := operation.ParseComment(comment, nil)122 assert.NoError(t, err)123 assert.Equal(t, "/customer/get-wishlist/{wishlist_id}:move", operation.Path)124 assert.Equal(t, "POST", operation.HTTPMethod)125}126func TestParseRouterCommentNoColonSignAtPathStartErr(t *testing.T) {127 comment := `/@Router :customer/get-wishlist/{wishlist_id}:move [post]`128 operation := NewOperation()129 err := operation.ParseComment(comment, nil)130 assert.Error(t, err)131}132func TestParseRouterCommentMethodSeparationErr(t *testing.T) {133 comment := `/@Router /api/{id}|,*[get`134 operation := NewOperation()135 err := operation.ParseComment(comment, nil)136 assert.Error(t, err)137}138func TestParseRouterCommentMethodMissingErr(t *testing.T) {139 comment := `/@Router /customer/get-wishlist/{wishlist_id}`140 operation := NewOperation()141 err := operation.ParseComment(comment, nil)142 assert.Error(t, err)143}144func TestParseResponseCommentWithObjectType(t *testing.T) {145 comment := `@Success 200 {object} model.OrderRow "Error message, if code != 200`146 operation := NewOperation()147 operation.parser = New()148 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)149 operation.parser.TypeDefinitions["model"]["OrderRow"] = &ast.TypeSpec{}150 err := operation.ParseComment(comment, nil)151 assert.NoError(t, err)152 response := operation.Responses.StatusCodeResponses[200]153 assert.Equal(t, `Error message, if code != 200`, response.Description)154 b, _ := json.MarshalIndent(operation, "", " ")155 expected := `{156 "responses": {157 "200": {158 "description": "Error message, if code != 200",159 "schema": {160 "$ref": "#/definitions/model.OrderRow"161 }162 }163 }164}`165 assert.Equal(t, expected, string(b))166}167func TestParseResponseCommentWithNestedPrimitiveType(t *testing.T) {168 comment := `@Success 200 {object} model.CommonHeader{data=string,data2=int} "Error message, if code != 200`169 operation := NewOperation()170 operation.parser = New()171 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)172 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}173 err := operation.ParseComment(comment, nil)174 assert.NoError(t, err)175 response := operation.Responses.StatusCodeResponses[200]176 assert.Equal(t, `Error message, if code != 200`, response.Description)177 b, _ := json.MarshalIndent(operation, "", " ")178 expected := `{179 "responses": {180 "200": {181 "description": "Error message, if code != 200",182 "schema": {183 "allOf": [184 {185 "$ref": "#/definitions/model.CommonHeader"186 },187 {188 "type": "object",189 "properties": {190 "data": {191 "type": "string"192 },193 "data2": {194 "type": "integer"195 }196 }197 }198 ]199 }200 }201 }202}`203 assert.Equal(t, expected, string(b))204}205func TestParseResponseCommentWithNestedPrimitiveArrayType(t *testing.T) {206 comment := `@Success 200 {object} model.CommonHeader{data=[]string,data2=[]int} "Error message, if code != 200`207 operation := NewOperation()208 operation.parser = New()209 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)210 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}211 err := operation.ParseComment(comment, nil)212 assert.NoError(t, err)213 response := operation.Responses.StatusCodeResponses[200]214 assert.Equal(t, `Error message, if code != 200`, response.Description)215 b, _ := json.MarshalIndent(operation, "", " ")216 expected := `{217 "responses": {218 "200": {219 "description": "Error message, if code != 200",220 "schema": {221 "allOf": [222 {223 "$ref": "#/definitions/model.CommonHeader"224 },225 {226 "type": "object",227 "properties": {228 "data": {229 "type": "array",230 "items": {231 "type": "string"232 }233 },234 "data2": {235 "type": "array",236 "items": {237 "type": "integer"238 }239 }240 }241 }242 ]243 }244 }245 }246}`247 assert.Equal(t, expected, string(b))248}249func TestParseResponseCommentWithNestedObjectType(t *testing.T) {250 comment := `@Success 200 {object} model.CommonHeader{data=model.Payload,data2=model.Payload2} "Error message, if code != 200`251 operation := NewOperation()252 operation.parser = New()253 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)254 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}255 operation.parser.TypeDefinitions["model"]["Payload"] = &ast.TypeSpec{}256 operation.parser.TypeDefinitions["model"]["Payload2"] = &ast.TypeSpec{}257 err := operation.ParseComment(comment, nil)258 assert.NoError(t, err)259 response := operation.Responses.StatusCodeResponses[200]260 assert.Equal(t, `Error message, if code != 200`, response.Description)261 b, _ := json.MarshalIndent(operation, "", " ")262 expected := `{263 "responses": {264 "200": {265 "description": "Error message, if code != 200",266 "schema": {267 "allOf": [268 {269 "$ref": "#/definitions/model.CommonHeader"270 },271 {272 "type": "object",273 "properties": {274 "data": {275 "$ref": "#/definitions/model.Payload"276 },277 "data2": {278 "$ref": "#/definitions/model.Payload2"279 }280 }281 }282 ]283 }284 }285 }286}`287 assert.Equal(t, expected, string(b))288}289func TestParseResponseCommentWithNestedArrayObjectType(t *testing.T) {290 comment := `@Success 200 {object} model.CommonHeader{data=[]model.Payload,data2=[]model.Payload2} "Error message, if code != 200`291 operation := NewOperation()292 operation.parser = New()293 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)294 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}295 operation.parser.TypeDefinitions["model"]["Payload"] = &ast.TypeSpec{}296 operation.parser.TypeDefinitions["model"]["Payload2"] = &ast.TypeSpec{}297 err := operation.ParseComment(comment, nil)298 assert.NoError(t, err)299 response := operation.Responses.StatusCodeResponses[200]300 assert.Equal(t, `Error message, if code != 200`, response.Description)301 b, _ := json.MarshalIndent(operation, "", " ")302 expected := `{303 "responses": {304 "200": {305 "description": "Error message, if code != 200",306 "schema": {307 "allOf": [308 {309 "$ref": "#/definitions/model.CommonHeader"310 },311 {312 "type": "object",313 "properties": {314 "data": {315 "type": "array",316 "items": {317 "$ref": "#/definitions/model.Payload"318 }319 },320 "data2": {321 "type": "array",322 "items": {323 "$ref": "#/definitions/model.Payload2"324 }325 }326 }327 }328 ]329 }330 }331 }332}`333 assert.Equal(t, expected, string(b))334}335func TestParseResponseCommentWithNestedFields(t *testing.T) {336 comment := `@Success 200 {object} model.CommonHeader{data1=int,data2=[]int,data3=model.Payload,data4=[]model.Payload} "Error message, if code != 200`337 operation := NewOperation()338 operation.parser = New()339 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)340 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}341 operation.parser.TypeDefinitions["model"]["Payload"] = &ast.TypeSpec{}342 err := operation.ParseComment(comment, nil)343 assert.NoError(t, err)344 response := operation.Responses.StatusCodeResponses[200]345 assert.Equal(t, `Error message, if code != 200`, response.Description)346 b, _ := json.MarshalIndent(operation, "", " ")347 expected := `{348 "responses": {349 "200": {350 "description": "Error message, if code != 200",351 "schema": {352 "allOf": [353 {354 "$ref": "#/definitions/model.CommonHeader"355 },356 {357 "type": "object",358 "properties": {359 "data1": {360 "type": "integer"361 },362 "data2": {363 "type": "array",364 "items": {365 "type": "integer"366 }367 },368 "data3": {369 "$ref": "#/definitions/model.Payload"370 },371 "data4": {372 "type": "array",373 "items": {374 "$ref": "#/definitions/model.Payload"375 }376 }377 }378 }379 ]380 }381 }382 }383}`384 assert.Equal(t, expected, string(b))385}386func TestParseResponseCommentWithDeepNestedFields(t *testing.T) {387 comment := `@Success 200 {object} model.CommonHeader{data1=int,data2=[]int,data3=model.Payload{data1=int,data2=model.DeepPayload},data4=[]model.Payload{data1=[]int,data2=[]model.DeepPayload}} "Error message, if code != 200`388 operation := NewOperation()389 operation.parser = New()390 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)391 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}392 operation.parser.TypeDefinitions["model"]["Payload"] = &ast.TypeSpec{}393 operation.parser.TypeDefinitions["model"]["DeepPayload"] = &ast.TypeSpec{}394 err := operation.ParseComment(comment, nil)395 assert.NoError(t, err)396 response := operation.Responses.StatusCodeResponses[200]397 assert.Equal(t, `Error message, if code != 200`, response.Description)398 b, _ := json.MarshalIndent(operation, "", " ")399 expected := `{400 "responses": {401 "200": {402 "description": "Error message, if code != 200",403 "schema": {404 "allOf": [405 {406 "$ref": "#/definitions/model.CommonHeader"407 },408 {409 "type": "object",410 "properties": {411 "data1": {412 "type": "integer"413 },414 "data2": {415 "type": "array",416 "items": {417 "type": "integer"418 }419 },420 "data3": {421 "allOf": [422 {423 "$ref": "#/definitions/model.Payload"424 },425 {426 "type": "object",427 "properties": {428 "data1": {429 "type": "integer"430 },431 "data2": {432 "$ref": "#/definitions/model.DeepPayload"433 }434 }435 }436 ]437 },438 "data4": {439 "type": "array",440 "items": {441 "allOf": [442 {443 "$ref": "#/definitions/model.Payload"444 },445 {446 "type": "object",447 "properties": {448 "data1": {449 "type": "array",450 "items": {451 "type": "integer"452 }453 },454 "data2": {455 "type": "array",456 "items": {457 "$ref": "#/definitions/model.DeepPayload"458 }459 }460 }461 }462 ]463 }464 }465 }466 }467 ]468 }469 }470 }471}`472 assert.Equal(t, expected, string(b))473}474func TestParseResponseCommentWithNestedArrayMapFields(t *testing.T) {475 comment := `@Success 200 {object} []map[string]model.CommonHeader{data1=[]map[string]model.Payload,data2=map[string][]int} "Error message, if code != 200`476 operation := NewOperation()477 operation.parser = New()478 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)479 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}480 operation.parser.TypeDefinitions["model"]["Payload"] = &ast.TypeSpec{}481 err := operation.ParseComment(comment, nil)482 assert.NoError(t, err)483 response := operation.Responses.StatusCodeResponses[200]484 assert.Equal(t, `Error message, if code != 200`, response.Description)485 b, _ := json.MarshalIndent(operation, "", " ")486 expected := `{487 "responses": {488 "200": {489 "description": "Error message, if code != 200",490 "schema": {491 "type": "array",492 "items": {493 "type": "object",494 "additionalProperties": {495 "allOf": [496 {497 "$ref": "#/definitions/model.CommonHeader"498 },499 {500 "type": "object",501 "properties": {502 "data1": {503 "type": "array",504 "items": {505 "type": "object",506 "additionalProperties": {507 "$ref": "#/definitions/model.Payload"508 }509 }510 },511 "data2": {512 "type": "object",513 "additionalProperties": {514 "type": "array",515 "items": {516 "type": "integer"517 }518 }519 }520 }521 }522 ]523 }524 }525 }526 }527 }528}`529 assert.Equal(t, expected, string(b))530}531func TestParseResponseCommentWithObjectTypeInSameFile(t *testing.T) {532 comment := `@Success 200 {object} testOwner "Error message, if code != 200"`533 operation := NewOperation()534 operation.parser = New()535 operation.parser.TypeDefinitions["swag"] = make(map[string]*ast.TypeSpec)536 operation.parser.TypeDefinitions["swag"]["testOwner"] = &ast.TypeSpec{}537 fset := token.NewFileSet()538 astFile, err := goparser.ParseFile(fset, "operation_test.go", `package swag539 type testOwner struct {540 541 }542 `, goparser.ParseComments)543 assert.NoError(t, err)544 err = operation.ParseComment(comment, astFile)545 assert.NoError(t, err)546 response := operation.Responses.StatusCodeResponses[200]547 assert.Equal(t, `Error message, if code != 200`, response.Description)548 b, _ := json.MarshalIndent(operation, "", " ")549 expected := `{550 "responses": {551 "200": {552 "description": "Error message, if code != 200",553 "schema": {554 "$ref": "#/definitions/swag.testOwner"555 }556 }557 }558}`559 assert.Equal(t, expected, string(b))560}561func TestParseResponseCommentWithObjectTypeAnonymousField(t *testing.T) {562 //TODO: test Anonymous563}564func TestParseResponseCommentWithObjectTypeErr(t *testing.T) {565 comment := `@Success 200 {object} model.OrderRow "Error message, if code != 200"`566 operation := NewOperation()567 operation.parser = New()568 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)569 operation.parser.TypeDefinitions["model"]["notexist"] = &ast.TypeSpec{}570 err := operation.ParseComment(comment, nil)571 assert.Error(t, err)572}573func TestParseResponseCommentWithArrayType(t *testing.T) {574 comment := `@Success 200 {array} model.OrderRow "Error message, if code != 200`575 operation := NewOperation()576 err := operation.ParseComment(comment, nil)577 assert.NoError(t, err)578 response := operation.Responses.StatusCodeResponses[200]579 assert.Equal(t, `Error message, if code != 200`, response.Description)580 assert.Equal(t, spec.StringOrArray{"array"}, response.Schema.Type)581 b, _ := json.MarshalIndent(operation, "", " ")582 expected := `{583 "responses": {584 "200": {585 "description": "Error message, if code != 200",586 "schema": {587 "type": "array",588 "items": {589 "$ref": "#/definitions/model.OrderRow"590 }591 }592 }593 }594}`595 assert.Equal(t, expected, string(b))596}597func TestParseResponseCommentWithBasicType(t *testing.T) {598 comment := `@Success 200 {string} string "it's ok'"`599 operation := NewOperation()600 err := operation.ParseComment(comment, nil)601 assert.NoError(t, err, "ParseComment should not fail")602 b, _ := json.MarshalIndent(operation, "", " ")603 expected := `{604 "responses": {605 "200": {606 "description": "it's ok'",607 "schema": {608 "type": "string"609 }610 }611 }612}`613 assert.Equal(t, expected, string(b))614}615func TestParseEmptyResponseComment(t *testing.T) {616 comment := `@Success 200 "it's ok"`617 operation := NewOperation()618 err := operation.ParseComment(comment, nil)619 assert.NoError(t, err, "ParseComment should not fail")620 b, _ := json.MarshalIndent(operation, "", " ")621 expected := `{622 "responses": {623 "200": {624 "description": "it's ok"625 }626 }627}`628 assert.Equal(t, expected, string(b))629}630func TestParseResponseCommentWithHeader(t *testing.T) {631 comment := `@Success 200 "it's ok"`632 operation := NewOperation()633 err := operation.ParseComment(comment, nil)634 assert.NoError(t, err, "ParseComment should not fail")635 comment = `@Header 200 {string} Token "qwerty"`636 err = operation.ParseComment(comment, nil)637 assert.NoError(t, err, "ParseComment should not fail")638 b, err := json.MarshalIndent(operation, "", " ")639 assert.NoError(t, err)640 expected := `{641 "responses": {642 "200": {643 "description": "it's ok",644 "headers": {645 "Token": {646 "type": "string",647 "description": "qwerty"648 }649 }650 }651 }652}`653 assert.Equal(t, expected, string(b))654 comment = `@Header 200 "Mallformed"`655 err = operation.ParseComment(comment, nil)656 assert.Error(t, err, "ParseComment should not fail")657}658func TestParseEmptyResponseOnlyCode(t *testing.T) {659 comment := `@Success 200`660 operation := NewOperation()661 err := operation.ParseComment(comment, nil)662 assert.NoError(t, err, "ParseComment should not fail")663 b, _ := json.MarshalIndent(operation, "", " ")664 expected := `{665 "responses": {666 "200": {}667 }668}`669 assert.Equal(t, expected, string(b))670}671func TestParseResponseCommentParamMissing(t *testing.T) {672 operation := NewOperation()673 paramLenErrComment := `@Success notIntCode {string}`674 paramLenErr := operation.ParseComment(paramLenErrComment, nil)675 assert.EqualError(t, paramLenErr, `can not parse response comment "notIntCode {string}"`)676}677// Test ParseParamComment678func TestParseParamCommentByPathType(t *testing.T) {679 comment := `@Param some_id path int true "Some ID"`680 operation := NewOperation()681 err := operation.ParseComment(comment, nil)682 assert.NoError(t, err)683 b, _ := json.MarshalIndent(operation, "", " ")684 expected := `{685 "parameters": [686 {687 "type": "integer",688 "description": "Some ID",689 "name": "some_id",690 "in": "path",691 "required": true692 }693 ]694}`695 assert.Equal(t, expected, string(b))696}697// Test ParseParamComment Query Params698func TestParseParamCommentBodyArray(t *testing.T) {699 comment := `@Param names body []string true "Users List"`700 operation := NewOperation()701 err := operation.ParseComment(comment, nil)702 assert.NoError(t, err)703 b, _ := json.MarshalIndent(operation, "", " ")704 expected := `{705 "parameters": [706 {707 "description": "Users List",708 "name": "names",709 "in": "body",710 "required": true,711 "schema": {712 "type": "array",713 "items": {714 "type": "string"715 }716 }717 }718 ]719}`720 assert.Equal(t, expected, string(b))721}722// Test ParseParamComment Query Params723func TestParseParamCommentQueryArray(t *testing.T) {724 comment := `@Param names query []string true "Users List"`725 operation := NewOperation()726 err := operation.ParseComment(comment, nil)727 assert.NoError(t, err)728 b, _ := json.MarshalIndent(operation, "", " ")729 expected := `{730 "parameters": [731 {732 "type": "array",733 "items": {734 "type": "string"735 },736 "description": "Users List",737 "name": "names",738 "in": "query",739 "required": true740 }741 ]742}`743 assert.Equal(t, expected, string(b))744}745// Test ParseParamComment Query Params746func TestParseParamCommentQueryArrayFormat(t *testing.T) {747 comment := `@Param names query []string true "Users List" collectionFormat(multi)`748 operation := NewOperation()749 err := operation.ParseComment(comment, nil)750 assert.NoError(t, err)751 b, _ := json.MarshalIndent(operation, "", " ")752 expected := `{753 "parameters": [754 {755 "type": "array",756 "items": {757 "type": "string"758 },759 "collectionFormat": "multi",760 "description": "Users List",761 "name": "names",762 "in": "query",763 "required": true764 }765 ]766}`767 assert.Equal(t, expected, string(b))768}769func TestParseParamCommentByID(t *testing.T) {770 comment := `@Param unsafe_id[lte] query int true "Unsafe query param"`771 operation := NewOperation()772 err := operation.ParseComment(comment, nil)773 assert.NoError(t, err)774 b, _ := json.MarshalIndent(operation, "", " ")775 expected := `{776 "parameters": [777 {778 "type": "integer",779 "description": "Unsafe query param",780 "name": "unsafe_id[lte]",781 "in": "query",782 "required": true783 }784 ]785}`786 assert.Equal(t, expected, string(b))787}788func TestParseParamCommentByQueryType(t *testing.T) {789 comment := `@Param some_id query int true "Some ID"`790 operation := NewOperation()791 err := operation.ParseComment(comment, nil)792 assert.NoError(t, err)793 b, _ := json.MarshalIndent(operation, "", " ")794 expected := `{795 "parameters": [796 {797 "type": "integer",798 "description": "Some ID",799 "name": "some_id",800 "in": "query",801 "required": true802 }803 ]804}`805 assert.Equal(t, expected, string(b))806}807func TestParseParamCommentByBodyType(t *testing.T) {808 comment := `@Param some_id body model.OrderRow true "Some ID"`809 operation := NewOperation()810 operation.parser = New()811 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)812 operation.parser.TypeDefinitions["model"]["OrderRow"] = &ast.TypeSpec{}813 err := operation.ParseComment(comment, nil)814 assert.NoError(t, err)815 b, _ := json.MarshalIndent(operation, "", " ")816 expected := `{817 "parameters": [818 {819 "description": "Some ID",820 "name": "some_id",821 "in": "body",822 "required": true,823 "schema": {824 "$ref": "#/definitions/model.OrderRow"825 }826 }827 ]828}`829 assert.Equal(t, expected, string(b))830}831func TestParseParamCommentByBodyTypeWithDeepNestedFields(t *testing.T) {832 comment := `@Param body body model.CommonHeader{data=string,data2=int} true "test deep"`833 operation := NewOperation()834 operation.parser = New()835 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)836 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}837 err := operation.ParseComment(comment, nil)838 assert.NoError(t, err)839 assert.Len(t, operation.Parameters, 1)840 assert.Equal(t, "test deep", operation.Parameters[0].Description)841 assert.True(t, operation.Parameters[0].Required)842 b, err := json.MarshalIndent(operation, "", " ")843 assert.NoError(t, err)844 expected := `{845 "parameters": [846 {847 "description": "test deep",848 "name": "body",849 "in": "body",850 "required": true,851 "schema": {852 "allOf": [853 {854 "$ref": "#/definitions/model.CommonHeader"855 },856 {857 "type": "object",858 "properties": {859 "data": {860 "type": "string"861 },862 "data2": {863 "type": "integer"864 }865 }866 }867 ]868 }869 }870 ]871}`872 assert.Equal(t, expected, string(b))873}874func TestParseParamCommentByBodyTypeArrayOfPrimitiveGo(t *testing.T) {875 comment := `@Param some_id body []int true "Some ID"`876 operation := NewOperation()877 operation.parser = New()878 err := operation.ParseComment(comment, nil)879 assert.NoError(t, err)880 b, _ := json.MarshalIndent(operation, "", " ")881 expected := `{882 "parameters": [883 {884 "description": "Some ID",885 "name": "some_id",886 "in": "body",887 "required": true,888 "schema": {889 "type": "array",890 "items": {891 "type": "integer"892 }893 }894 }895 ]896}`897 assert.Equal(t, expected, string(b))898}899func TestParseParamCommentByBodyTypeArrayOfPrimitiveGoWithDeepNestedFields(t *testing.T) {900 comment := `@Param body body []model.CommonHeader{data=string,data2=int} true "test deep"`901 operation := NewOperation()902 operation.parser = New()903 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)904 operation.parser.TypeDefinitions["model"]["CommonHeader"] = &ast.TypeSpec{}905 err := operation.ParseComment(comment, nil)906 assert.NoError(t, err)907 assert.Len(t, operation.Parameters, 1)908 assert.Equal(t, "test deep", operation.Parameters[0].Description)909 assert.True(t, operation.Parameters[0].Required)910 b, err := json.MarshalIndent(operation, "", " ")911 assert.NoError(t, err)912 expected := `{913 "parameters": [914 {915 "description": "test deep",916 "name": "body",917 "in": "body",918 "required": true,919 "schema": {920 "type": "array",921 "items": {922 "allOf": [923 {924 "$ref": "#/definitions/model.CommonHeader"925 },926 {927 "type": "object",928 "properties": {929 "data": {930 "type": "string"931 },932 "data2": {933 "type": "integer"934 }935 }936 }937 ]938 }939 }940 }941 ]942}`943 assert.Equal(t, expected, string(b))944}945func TestParseParamCommentByBodyTypeErr(t *testing.T) {946 comment := `@Param some_id body model.OrderRow true "Some ID"`947 operation := NewOperation()948 operation.parser = New()949 operation.parser.TypeDefinitions["model"] = make(map[string]*ast.TypeSpec)950 operation.parser.TypeDefinitions["model"]["notexist"] = &ast.TypeSpec{}951 err := operation.ParseComment(comment, nil)952 assert.Error(t, err)953}954func TestParseParamCommentByFormDataType(t *testing.T) {955 comment := `@Param file formData file true "this is a test file"`956 operation := NewOperation()957 operation.parser = New()958 err := operation.ParseComment(comment, nil)959 assert.NoError(t, err)960 b, _ := json.MarshalIndent(operation, "", " ")961 expected := `{962 "parameters": [963 {964 "type": "file",965 "description": "this is a test file",966 "name": "file",967 "in": "formData",968 "required": true969 }970 ]971}`972 assert.Equal(t, expected, string(b))973}974func TestParseParamCommentByFormDataTypeUint64(t *testing.T) {975 comment := `@Param file formData uint64 true "this is a test file"`976 operation := NewOperation()977 operation.parser = New()978 err := operation.ParseComment(comment, nil)979 assert.NoError(t, err)980 b, _ := json.MarshalIndent(operation, "", " ")981 expected := `{982 "parameters": [983 {984 "type": "integer",985 "description": "this is a test file",986 "name": "file",987 "in": "formData",988 "required": true989 }990 ]991}`992 assert.Equal(t, expected, string(b))993}994func TestParseParamCommentByNotSupportedType(t *testing.T) {995 comment := `@Param some_id not_supported int true "Some ID"`996 operation := NewOperation()997 err := operation.ParseComment(comment, nil)998 assert.Error(t, err)999}1000func TestParseParamCommentNotMatch(t *testing.T) {1001 comment := `@Param some_id body mock true`1002 operation := NewOperation()1003 err := operation.ParseComment(comment, nil)1004 assert.Error(t, err)1005}1006func TestParseParamCommentByEnums(t *testing.T) {1007 comment := `@Param some_id query string true "Some ID" Enums(A, B, C)`1008 operation := NewOperation()1009 err := operation.ParseComment(comment, nil)1010 assert.NoError(t, err)1011 b, _ := json.MarshalIndent(operation, "", " ")1012 expected := `{1013 "parameters": [1014 {1015 "enum": [1016 "A",1017 "B",1018 "C"1019 ],1020 "type": "string",1021 "description": "Some ID",1022 "name": "some_id",1023 "in": "query",1024 "required": true1025 }1026 ]1027}`1028 assert.Equal(t, expected, string(b))1029 comment = `@Param some_id query int true "Some ID" Enums(1, 2, 3)`1030 operation = NewOperation()1031 err = operation.ParseComment(comment, nil)1032 assert.NoError(t, err)1033 b, _ = json.MarshalIndent(operation, "", " ")1034 expected = `{1035 "parameters": [1036 {1037 "enum": [1038 1,1039 2,1040 31041 ],1042 "type": "integer",1043 "description": "Some ID",1044 "name": "some_id",1045 "in": "query",1046 "required": true1047 }1048 ]1049}`1050 assert.Equal(t, expected, string(b))1051 comment = `@Param some_id query number true "Some ID" Enums(1.1, 2.2, 3.3)`1052 operation = NewOperation()1053 err = operation.ParseComment(comment, nil)1054 assert.NoError(t, err)1055 b, _ = json.MarshalIndent(operation, "", " ")1056 expected = `{1057 "parameters": [1058 {1059 "enum": [1060 1.1,1061 2.2,1062 3.31063 ],1064 "type": "number",1065 "description": "Some ID",1066 "name": "some_id",1067 "in": "query",1068 "required": true1069 }1070 ]1071}`1072 assert.Equal(t, expected, string(b))1073 comment = `@Param some_id query bool true "Some ID" Enums(true, false)`1074 operation = NewOperation()1075 err = operation.ParseComment(comment, nil)1076 assert.NoError(t, err)1077 b, _ = json.MarshalIndent(operation, "", " ")1078 expected = `{1079 "parameters": [1080 {1081 "enum": [1082 true,1083 false1084 ],1085 "type": "boolean",1086 "description": "Some ID",1087 "name": "some_id",1088 "in": "query",1089 "required": true1090 }1091 ]1092}`1093 assert.Equal(t, expected, string(b))1094 operation = NewOperation()1095 comment = `@Param some_id query int true "Some ID" Enums(A, B, C)`1096 assert.Error(t, operation.ParseComment(comment, nil))1097 comment = `@Param some_id query number true "Some ID" Enums(A, B, C)`1098 assert.Error(t, operation.ParseComment(comment, nil))1099 comment = `@Param some_id query boolean true "Some ID" Enums(A, B, C)`1100 assert.Error(t, operation.ParseComment(comment, nil))1101 comment = `@Param some_id query Document true "Some ID" Enums(A, B, C)`1102 assert.Error(t, operation.ParseComment(comment, nil))1103}1104func TestParseParamCommentByMaxLength(t *testing.T) {1105 comment := `@Param some_id query string true "Some ID" MaxLength(10)`1106 operation := NewOperation()1107 err := operation.ParseComment(comment, nil)1108 assert.NoError(t, err)1109 b, _ := json.MarshalIndent(operation, "", " ")1110 expected := `{1111 "parameters": [1112 {1113 "maxLength": 10,1114 "type": "string",1115 "description": "Some ID",1116 "name": "some_id",1117 "in": "query",1118 "required": true1119 }1120 ]1121}`1122 assert.Equal(t, expected, string(b))1123 comment = `@Param some_id query int true "Some ID" MaxLength(10)`1124 assert.Error(t, operation.ParseComment(comment, nil))1125 comment = `@Param some_id query string true "Some ID" MaxLength(Goopher)`1126 assert.Error(t, operation.ParseComment(comment, nil))1127}1128func TestParseParamCommentByMinLength(t *testing.T) {1129 comment := `@Param some_id query string true "Some ID" MinLength(10)`1130 operation := NewOperation()1131 err := operation.ParseComment(comment, nil)1132 assert.NoError(t, err)1133 b, _ := json.MarshalIndent(operation, "", " ")1134 expected := `{1135 "parameters": [1136 {1137 "minLength": 10,1138 "type": "string",1139 "description": "Some ID",1140 "name": "some_id",1141 "in": "query",1142 "required": true1143 }1144 ]1145}`1146 assert.Equal(t, expected, string(b))1147 comment = `@Param some_id query int true "Some ID" MinLength(10)`1148 assert.Error(t, operation.ParseComment(comment, nil))1149 comment = `@Param some_id query string true "Some ID" MinLength(Goopher)`1150 assert.Error(t, operation.ParseComment(comment, nil))1151}1152func TestParseParamCommentByMininum(t *testing.T) {1153 comment := `@Param some_id query int true "Some ID" Mininum(10)`1154 operation := NewOperation()1155 err := operation.ParseComment(comment, nil)1156 assert.NoError(t, err)1157 b, _ := json.MarshalIndent(operation, "", " ")1158 expected := `{1159 "parameters": [1160 {1161 "minimum": 10,1162 "type": "integer",1163 "description": "Some ID",1164 "name": "some_id",1165 "in": "query",1166 "required": true1167 }1168 ]1169}`1170 assert.Equal(t, expected, string(b))1171 comment = `@Param some_id query string true "Some ID" Mininum(10)`1172 assert.Error(t, operation.ParseComment(comment, nil))1173 comment = `@Param some_id query integer true "Some ID" Mininum(Goopher)`1174 assert.Error(t, operation.ParseComment(comment, nil))1175}1176func TestParseParamCommentByMaxinum(t *testing.T) {1177 comment := `@Param some_id query int true "Some ID" Maxinum(10)`1178 operation := NewOperation()1179 err := operation.ParseComment(comment, nil)1180 assert.NoError(t, err)1181 b, _ := json.MarshalIndent(operation, "", " ")1182 expected := `{1183 "parameters": [1184 {1185 "maximum": 10,1186 "type": "integer",1187 "description": "Some ID",1188 "name": "some_id",1189 "in": "query",1190 "required": true1191 }1192 ]1193}`1194 assert.Equal(t, expected, string(b))1195 comment = `@Param some_id query string true "Some ID" Maxinum(10)`1196 assert.Error(t, operation.ParseComment(comment, nil))1197 comment = `@Param some_id query integer true "Some ID" Maxinum(Goopher)`1198 assert.Error(t, operation.ParseComment(comment, nil))1199}1200func TestParseParamCommentByDefault(t *testing.T) {1201 comment := `@Param some_id query int true "Some ID" Default(10)`1202 operation := NewOperation()1203 err := operation.ParseComment(comment, nil)1204 assert.NoError(t, err)1205 b, _ := json.MarshalIndent(operation, "", " ")1206 expected := `{1207 "parameters": [1208 {1209 "type": "integer",1210 "default": 10,1211 "description": "Some ID",1212 "name": "some_id",1213 "in": "query",1214 "required": true1215 }1216 ]1217}`1218 assert.Equal(t, expected, string(b))1219}1220func TestParseIdComment(t *testing.T) {1221 comment := `@Id myOperationId`1222 operation := NewOperation()1223 err := operation.ParseComment(comment, nil)1224 assert.NoError(t, err)1225 assert.Equal(t, "myOperationId", operation.ID)1226}1227func TestFindTypeDefCoreLib(t *testing.T) {1228 spec, err := findTypeDef("net/http", "Request")1229 assert.NoError(t, err)1230 assert.NotNil(t, spec)1231}1232func TestFindTypeDefExternalPkg(t *testing.T) {1233 spec, err := findTypeDef("github.com/KyleBanks/depth", "Tree")1234 assert.NoError(t, err)1235 assert.NotNil(t, spec)1236}1237func TestFindTypeDefInvalidPkg(t *testing.T) {1238 spec, err := findTypeDef("does-not-exist", "foo")1239 assert.Error(t, err)1240 assert.Nil(t, spec)1241}1242func TestParseSecurityComment(t *testing.T) {1243 comment := `@Security OAuth2Implicit[read, write]`1244 operation := NewOperation()1245 operation.parser = New()1246 err := operation.ParseComment(comment, nil)1247 assert.NoError(t, err)1248 b, _ := json.MarshalIndent(operation, "", " ")1249 expected := `{1250 "security": [1251 {1252 "OAuth2Implicit": [1253 "read",1254 "write"1255 ]1256 }1257 ]1258}`1259 assert.Equal(t, expected, string(b))1260}1261func TestParseMultiDescription(t *testing.T) {1262 comment := `@Description line one`1263 operation := NewOperation()1264 operation.parser = New()1265 err := operation.ParseComment(comment, nil)1266 assert.NoError(t, err)1267 comment = `@Tags multi`1268 err = operation.ParseComment(comment, nil)1269 assert.NoError(t, err)1270 comment = `@Description line two x`1271 err = operation.ParseComment(comment, nil)1272 assert.NoError(t, err)1273 b, _ := json.MarshalIndent(operation, "", " ")1274 expected := `"description": "line one\nline two x"`1275 assert.Contains(t, string(b), expected)1276}1277func TestParseSummary(t *testing.T) {1278 comment := `@summary line one`1279 operation := NewOperation()1280 operation.parser = New()1281 err := operation.ParseComment(comment, nil)1282 assert.NoError(t, err)1283 comment = `@Summary line one`1284 err = operation.ParseComment(comment, nil)1285 assert.NoError(t, err)1286}1287func TestParseDeprecationDescription(t *testing.T) {1288 comment := `@Deprecated`1289 operation := NewOperation()1290 operation.parser = New()1291 err := operation.ParseComment(comment, nil)1292 assert.NoError(t, err)1293 if !operation.Deprecated {1294 t.Error("Failed to parse @deprecated comment")1295 }1296}1297func TestRegisterSchemaType(t *testing.T) {1298 operation := NewOperation()1299 fset := token.NewFileSet()1300 astFile, err := goparser.ParseFile(fset, "main.go", `package main1301 import "timer"1302`, goparser.ParseComments)1303 assert.NoError(t, err)1304 operation.parser = New()1305 _, _, err = operation.registerSchemaType("timer.Location", astFile)1306 assert.Error(t, err)1307}1308func TestParseExtentions(t *testing.T) {1309 // Fail if there are no args for attributes.1310 {1311 comment := `@x-amazon-apigateway-integration`1312 operation := NewOperation()1313 operation.parser = New()1314 err := operation.ParseComment(comment, nil)1315 assert.EqualError(t, err, "annotation @x-amazon-apigateway-integration need a value")1316 }1317 // Fail if args of attributes are broken.1318 {1319 comment := `@x-amazon-apigateway-integration ["broken"}]`1320 operation := NewOperation()1321 operation.parser = New()1322 err := operation.ParseComment(comment, nil)1323 assert.EqualError(t, err, "annotation @x-amazon-apigateway-integration need a valid json value")1324 }1325 // OK1326 {1327 comment := `@x-amazon-apigateway-integration {"uri": "${some_arn}", "passthroughBehavior": "when_no_match", "httpMethod": "POST", "type": "aws_proxy"}`1328 operation := NewOperation()1329 operation.parser = New()1330 err := operation.ParseComment(comment, nil)1331 assert.NoError(t, err)1332 expected := `{1333 "x-amazon-apigateway-integration": {1334 "httpMethod": "POST",1335 "passthroughBehavior": "when_no_match",1336 "type": "aws_proxy",1337 "uri": "${some_arn}"1338 }1339}`1340 b, _ := json.MarshalIndent(operation, "", " ")1341 assert.Equal(t, expected, string(b))1342 }1343}...

Full Screen

Full Screen

parseComment

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 log.Fatal(err)6 }7 ast.Inspect(f, func(n ast.Node) bool {8 switch x := n.(type) {9 for _, spec := range x.Specs {10 if t, ok := spec.(*ast.TypeSpec); ok {11 if s, ok := t.Type.(*ast.StructType); ok {12 for _, field := range s.Fields.List {13 if field.Comment != nil {14 fmt.Println(field.Comment.Text())15 }16 }17 }18 }19 }20 }21 })22}23import (24func main() {25 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)26 if err != nil {27 log.Fatal(err)28 }29 ast.Inspect(f, func(n ast.Node) bool {30 switch x := n.(type) {31 for _, spec := range x.Specs {32 if t, ok := spec.(*ast.TypeSpec); ok {33 if s, ok := t.Type.(*ast.StructType); ok {34 for _, field := range s.Fields.List {35 if field.Doc != nil {36 fmt.Println(field.Doc.Text())37 }38 }39 }40 }41 }42 }43 })44}45import (46func main() {47 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)48 if err != nil {49 log.Fatal(err)50 }

Full Screen

Full Screen

parseComment

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)5 if err != nil {6 panic(err)7 }8 for _, cg := range f.Comments {9 fmt.Println("comment:", cg.Text())10 }11}

Full Screen

Full Screen

parseComment

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fs := token.NewFileSet()4 f, err := parser.ParseFile(fs, "1.go", nil, parser.ParseComments)5 if err != nil {6 panic(err)7 }8 for _, d := range f.Decls {9 if gd, ok := d.(*ast.GenDecl); ok {10 for _, s := range gd.Specs {11 if ts, ok := s.(*ast.TypeSpec); ok {12 if st, ok := ts.Type.(*ast.StructType); ok {13 for _, field := range st.Fields.List {14 if field.Tag != nil {15 fmt.Println(field.Tag.Value)16 }17 }18 }19 }20 }21 }22 }23}

Full Screen

Full Screen

parseComment

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 src, err := ioutil.ReadFile(os.Args[1])4 if err != nil {5 log.Fatal(err)6 }7 f, err := parser.ParseFile(fset, "", src, parser.ParseComments)8 if err != nil {9 log.Fatal(err)10 }11 for _, cg := range f.Decls[0].(*ast.FuncDecl).Type.Results.List[0].Names[0].Comments {12 for _, c := range cg.List {13 fmt.Println(c.Text)14 }15 }16}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful