MCPcopy Index your code
hub / github.com/oapi-codegen/oapi-codegen / TestPetStore

Function TestPetStore

examples/petstore-expanded/echo/petstore_test.go:31–152  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

29)
30
31func TestPetStore(t *testing.T) {
32 var err error
33 // Here, we Initialize echo
34 e := echo.New()
35
36 // Now, we create our empty pet store
37 store := api.NewPetStore()
38
39 // Get the swagger description of our API
40 swagger, err := api.GetSpec()
41 require.NoError(t, err)
42
43 // This disables swagger server name validation. It seems to work poorly,
44 // and requires our test server to be in that list.
45 swagger.Servers = nil
46
47 // Validate requests against the OpenAPI spec
48 e.Use(middleware.OapiRequestValidator(swagger))
49
50 // We register the autogenerated boilerplate and bind our PetStore to this
51 // echo router.
52 api.RegisterHandlers(e, store)
53
54 // At this point, we can start sending simulated Http requests, and record
55 // the HTTP responses to check for validity. This exercises every part of
56 // the stack except the well-tested HTTP system in Go, which there is no
57 // point for us to test.
58 tag := "TagOfSpot"
59 newPet := models.NewPet{
60 Name: "Spot",
61 Tag: &tag,
62 }
63 result := testutil.NewRequest().Post("/pets").WithJsonBody(newPet).GoWithHTTPHandler(t, e)
64 // We expect 201 code on successful pet insertion
65 assert.Equal(t, http.StatusCreated, result.Code())
66
67 // We should have gotten a response from the server with the new pet. Make
68 // sure that its fields match.
69 var resultPet models.Pet
70 err = result.UnmarshalBodyToObject(&resultPet)
71 assert.NoError(t, err, "error unmarshaling response")
72 assert.Equal(t, newPet.Name, resultPet.Name)
73 assert.Equal(t, *newPet.Tag, *resultPet.Tag)
74
75 // This is the Id of the pet we inserted.
76 petId := resultPet.Id
77
78 // Test the getter function.
79 result = testutil.NewRequest().Get(fmt.Sprintf("/pets/%d", petId)).WithAcceptJson().GoWithHTTPHandler(t, e)
80 var resultPet2 models.Pet
81 err = result.UnmarshalBodyToObject(&resultPet2)
82 assert.NoError(t, err, "error getting pet")
83 assert.Equal(t, resultPet, resultPet2)
84
85 // We should get a 404 on invalid ID
86 result = testutil.NewRequest().Get("/pets/27179095781").WithAcceptJson().GoWithHTTPHandler(t, e)
87 assert.Equal(t, http.StatusNotFound, result.Code())
88 var petError models.Error

Callers

nothing calls this directly

Calls 4

NewPetStoreFunction · 0.92
GetSpecFunction · 0.92
RegisterHandlersFunction · 0.92
GetMethod · 0.45

Tested by

no test coverage detected