Skip to content

Commit

Permalink
added some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
e-nikolov committed Jan 8, 2022
1 parent 4d2620a commit 89a2158
Show file tree
Hide file tree
Showing 12 changed files with 392 additions and 158 deletions.
100 changes: 100 additions & 0 deletions chai/chai_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package chai_test

import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chai/chai/chai"
"github.com/go-chai/chai/internal/tests"
"github.com/stretchr/testify/require"
)

func newRes() *tests.TestResponse {
return &tests.TestResponse{
Foo: "f",
Bar: "b",
TestInnerResponse: tests.TestInnerResponse{
FooFoo: 123,
BarBar: 12,
},
}
}

func newReq() io.Reader {
buf := new(bytes.Buffer)

json.NewEncoder(buf).Encode(&tests.TestRequest{
Foo: "312",
Bar: "31321",
TestInnerResponse: tests.TestInnerResponse{
FooFoo: 4432,
BarBar: 321,
},
})

return buf
}

func TestReqResHandler(t *testing.T) {
tests := []struct {
name string
makeHandler func(t *testing.T) http.Handler
response string
}{
{
name: "req res handler",
makeHandler: func(t *testing.T) http.Handler {
return chai.NewReqResHandler(func(req *tests.TestRequest, w http.ResponseWriter, r *http.Request) (*tests.TestResponse, int, error) {
return newRes(), http.StatusOK, nil
})
},
response: `{"foo":"f","bar":"b","test_inner_response":{"foo_foo":123,"bar_bar":12}}`,
},
{
name: "req res handler with error",
makeHandler: func(t *testing.T) http.Handler {
return chai.NewReqResHandler(func(req *tests.TestRequest, w http.ResponseWriter, r *http.Request) (*tests.TestResponse, int, error) {
return nil, http.StatusInternalServerError, errors.New("zz")
})
},
response: `{"error":"zz", "status_code":500}`,
},
{
name: "res handler",
makeHandler: func(t *testing.T) http.Handler {
return chai.NewResHandler(func(w http.ResponseWriter, r *http.Request) (*tests.TestResponse, int, error) {
return newRes(), http.StatusOK, nil
})
},
response: `{"foo":"f","bar":"b","test_inner_response":{"foo_foo":123,"bar_bar":12}}`,
},
{
name: "req res handler with error",
makeHandler: func(t *testing.T) http.Handler {
return chai.NewResHandler(func(w http.ResponseWriter, r *http.Request) (*tests.TestResponse, int, error) {
return nil, http.StatusInternalServerError, errors.New("zz")
})
},
response: `{"error":"zz", "status_code":500}`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.NotPanics(t, func() {
h := tt.makeHandler(t)

w := httptest.NewRecorder()

h.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/", newReq()))

require.JSONEq(t, tt.response, w.Body.String())
})
})
}
}
83 changes: 0 additions & 83 deletions chai/generics_test.go

This file was deleted.

58 changes: 1 addition & 57 deletions examples/chi/celler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import (
"errors"
"fmt"
"net/http"
"strconv"

"github.com/ghodss/yaml"

chai "github.com/go-chai/chai/chi"
"github.com/go-chai/chai/examples/shared/controller"
"github.com/go-chai/chai/examples/shared/model"

_ "github.com/go-chai/chai/examples/docs/celler" // This is required to be able to serve the stored swagger spec in prod
"github.com/go-chai/chai/examples/shared/httputil"
Expand All @@ -25,61 +23,7 @@ func main() {

c := controller.NewController()

r.Route("/api/v1", func(r chi.Router) {
r.Route("/accounts", func(r chi.Router) {
chai.Get(r, "/{id}", c.ShowAccount)
chai.Get(r, "/", c.ListAccounts)
chai.Post(r, "/", c.AddAccount)
r.Delete("/{id:[0-9]+}", c.DeleteAccount)
r.Patch("/{id}", c.UpdateAccount)
r.Post("/{id}/images", c.UploadAccountImage)
})

r.Route("/bottles", func(r chi.Router) {
// ShowBottle godoc
// @Summary Show a bottle
// @Description get string by ID
// @ID get-string-by-int
// @Tags bottles
// @Accept json
// @Produce json
// @Param id path int true "Bottle ID"
// @Success 200 {object} model.Bottle
// @Failure 400 {object} httputil.Error
// @Failure 404 {object} httputil.Error
// @Failure 500 {object} httputil.Error
chai.Get(r, "/{id}", func(w http.ResponseWriter, r *http.Request) (*model.Bottle, int, error) {
id := chi.URLParam(r, "id")
bid, err := strconv.Atoi(id)
if err != nil {
return nil, http.StatusBadRequest, err
}
bottle, err := model.BottleOne(bid)
if err != nil {
return nil, http.StatusNotFound, err
}
return bottle, http.StatusOK, nil
})
chai.Get(r, "/", c.ListBottles)
})

r.Route("/admin", func(r chi.Router) {
r.Use(auth)

chai.Post(r, "/auth", c.Auth)
})

r.Route("/examples", func(r chi.Router) {
chai.Get(r, "/ping", c.PingExample)
chai.Get(r, "/calc", c.CalcExample)
// chai.Get(r, "/group{s/{gro}up_id}/accounts/{account_id}", c.PathParamsExample)
chai.Get(r, "/groups/{group_id}/accounts/{account_id}", c.PathParamsExample)
chai.Get(r, "/header", c.HeaderExample)
chai.Get(r, "/securities", c.SecuritiesExample)
chai.Get(r, "/attribute", c.AttributeExample)
chai.Post(r, "/attribute", c.PostExample)
})
})
r.Mount("/", c.ChiRoutes())

// This must be used only during development to generate the swagger spec
docs, err := chai.OpenAPI2(r)
Expand Down
83 changes: 83 additions & 0 deletions examples/shared/controller/controller.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
package controller

import (
"errors"
"net/http"
"strconv"

chai "github.com/go-chai/chai/chi"
"github.com/go-chai/chai/examples/shared/httputil"
"github.com/go-chai/chai/examples/shared/model"
"github.com/go-chi/chi/v5"
)

// Controller example
type Controller struct {
}
Expand All @@ -9,6 +20,78 @@ func NewController() *Controller {
return &Controller{}
}

func (c *Controller) ChiRoutes() chi.Router {
r := chi.NewRouter()

r.Route("/api/v1", func(r chi.Router) {
r.Route("/accounts", func(r chi.Router) {
chai.Get(r, "/{id}", c.ShowAccount)
chai.Get(r, "/", c.ListAccounts)
chai.Post(r, "/", c.AddAccount)
r.Delete("/{id:[0-9]+}", c.DeleteAccount)
r.Patch("/{id}", c.UpdateAccount)
r.Post("/{id}/images", c.UploadAccountImage)
})

r.Route("/bottles", func(r chi.Router) {
// ShowBottle godoc
// @Summary Show a bottle
// @Description get string by ID
// @ID get-string-by-int
// @Tags bottles
// @Accept json
// @Produce json
// @Param id path int true "Bottle ID"
// @Success 200 {object} model.Bottle
// @Failure 400 {object} httputil.Error
// @Failure 404 {object} httputil.Error
// @Failure 500 {object} httputil.Error
chai.Get(r, "/{id}", func(w http.ResponseWriter, r *http.Request) (*model.Bottle, int, error) {
id := chi.URLParam(r, "id")
bid, err := strconv.Atoi(id)
if err != nil {
return nil, http.StatusBadRequest, err
}
bottle, err := model.BottleOne(bid)
if err != nil {
return nil, http.StatusNotFound, err
}
return bottle, http.StatusOK, nil
})
chai.Get(r, "/", c.ListBottles)
})

r.Route("/admin", func(r chi.Router) {
r.Use(auth)

chai.Post(r, "/auth", c.Auth)
})

r.Route("/examples", func(r chi.Router) {
chai.Get(r, "/ping", c.PingExample)
chai.Get(r, "/calc", c.CalcExample)
// chai.Get(r, "/group{s/{gro}up_id}/accounts/{account_id}", c.PathParamsExample)
chai.Get(r, "/groups/{group_id}/accounts/{account_id}", c.PathParamsExample)
chai.Get(r, "/header", c.HeaderExample)
chai.Get(r, "/securities", c.SecuritiesExample)
chai.Get(r, "/attribute", c.AttributeExample)
chai.Post(r, "/attribute", c.PostExample)
})
})

return r
}

func auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.Header.Get("Authorization")) == 0 {
httputil.NewError(w, http.StatusUnauthorized, errors.New("Authorization is required Header"))
return
}
next.ServeHTTP(w, r)
})
}

// Message example
type Message struct {
Message string `json:"message" example:"message"`
Expand Down
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ module github.com/go-chai/chai
go 1.18

require (
github.com/davecgh/go-spew v1.1.1
github.com/getkin/kin-openapi v0.88.0
github.com/ghodss/yaml v1.0.0
github.com/go-chai/swag v1.7.8-fork2
github.com/go-chi/chi/v5 v5.0.7
github.com/go-chi/docgen v1.2.0
github.com/go-chi/render v1.0.1
github.com/go-openapi/spec v0.20.4
github.com/gofrs/uuid v4.2.0+incompatible
Expand All @@ -23,6 +21,7 @@ require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
Expand Down
3 changes: 0 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@ github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-chai/swag v1.7.8-fork2 h1:ijgxBjnbrjRK1XAqLor+FvMLpdST7MEk2MGw3V+Zz0I=
github.com/go-chai/swag v1.7.8-fork2/go.mod h1:7osfZ2yWVpvxjKkjueEGIi5GIltebBc7YsfN8JtRURc=
github.com/go-chi/chi/v5 v5.0.1/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/docgen v1.2.0 h1:da0Nq2PKU9W9pSOTUfVrKI1vIgTGpauo9cfh4Iwivek=
github.com/go-chi/docgen v1.2.0/go.mod h1:G9W0G551cs2BFMSn/cnGwX+JBHEloAgo17MBhyrnhPI=
github.com/go-chi/render v1.0.1 h1:4/5tis2cKaNdnv9zFLfXzcquC9HbeZgCnxGnKrltBS8=
github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1OvJns=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
Expand Down
File renamed without changes.
Loading

0 comments on commit 89a2158

Please sign in to comment.