Skip to content

Commit

Permalink
feat(api) port api tests to go-restful
Browse files Browse the repository at this point in the history
  • Loading branch information
lukepatrick committed Jul 11, 2018
1 parent 912df59 commit 035b89c
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 70 deletions.
6 changes: 3 additions & 3 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@

[[constraint]]
name = "github.com/emicklei/go-restful"
version = "2.6.1"
version = "2.7.1"

[[constraint]]
name = "github.com/emicklei/go-restful-openapi"
version = "0.9.1"
version = "0.11.0"
23 changes: 11 additions & 12 deletions brigade-api/cmd/brigade-api/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ var (
disableColor = false
)

var logger *log.Logger = log.New(os.Stdout, "", 0)
var logger = log.New(os.Stdout, "", 0)

// NCSACommonLogFormatLogger Create a filter that produces log lines
// according to the Common Log Format, also known as the NCSA standard.
// Coloring inspired by gin
// Coloring inspired by ansi
func NCSACommonLogFormatLogger() restful.FilterFunction {
return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
var username = "-"
Expand All @@ -40,10 +40,16 @@ func NCSACommonLogFormatLogger() restful.FilterFunction {
if err != nil {
return
}
isTerm := true
if disableColor {
isTerm = false
}
var statusColor, methodColor, resetColor string
methodColor = colorForMethod(req.Request.Method)
resetColor = reset
statusColor = colorForStatus(resp.StatusCode())
if isTerm {
methodColor = colorForMethod(req.Request.Method)
resetColor = reset
statusColor = colorForStatus(resp.StatusCode())
}
logger.Printf("%15s - %s [%s] \"%s %7s %s %s %s\" %s %3d %s %d",
ip,
username,
Expand All @@ -57,13 +63,6 @@ func NCSACommonLogFormatLogger() restful.FilterFunction {
}
}

// MeasureTime web-service (post-process) Filter (as a struct that defines a FilterFunction)
func MeasureTime(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
now := time.Now()
chain.ProcessFilter(req, resp)
logger.Printf("[webservice-filter (timer)] %v\n", time.Now().Sub(now))
}

func colorForMethod(method string) string {
switch method {
case "GET":
Expand Down
35 changes: 11 additions & 24 deletions brigade-api/cmd/brigade-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import (
"net/http"
"os"

"github.com/Azure/brigade/pkg/api"
"github.com/Azure/brigade/pkg/brigade"
"github.com/Azure/brigade/pkg/storage/kube"

"github.com/emicklei/go-restful"
restfulspec "github.com/emicklei/go-restful-openapi"

"github.com/Azure/brigade/pkg/api"
"github.com/go-openapi/spec"

"k8s.io/api/core/v1"
)

Expand Down Expand Up @@ -49,8 +51,7 @@ type healthService struct {
func (js jobService) WebService() *restful.WebService {
ws := new(restful.WebService)
j := js.server.Job()
// rest.GET("/job/:id", j.Get)
// rest.GET("/job/:id/logs", j.Logs)

ws.
Path("/v1/job").
Consumes(restful.MIME_JSON).
Expand Down Expand Up @@ -80,9 +81,7 @@ func (js jobService) WebService() *restful.WebService {
func (bs buildService) WebService() *restful.WebService {
ws := new(restful.WebService)
b := bs.server.Build()
// rest.GET("/build/:id", b.Get)
// rest.GET("/build/:id/jobs", b.Jobs)
// rest.GET("/build/:id/logs", b.Logs)

ws.
Path("/v1/build").
Consumes(restful.MIME_JSON).
Expand Down Expand Up @@ -120,10 +119,7 @@ func (bs buildService) WebService() *restful.WebService {
func (ps projectService) WebService() *restful.WebService {
ws := new(restful.WebService)
p := ps.server.Project()
// rest.GET("/projects", p.List)
// rest.GET("/project/:id", p.Get)
// rest.GET("/project/:id/builds", p.Builds)
// rest.GET("/projects-build", p.ListWithLatestBuild)

ws.
Path("/v1").
Consumes(restful.MIME_JSON).
Expand Down Expand Up @@ -193,11 +189,11 @@ func main() {
}

storage := kube.New(clientset, namespace)
server := api.New(storage)
storageServer := api.New(storage)

j := jobService{server}
b := buildService{server}
p := projectService{server}
j := jobService{server: storageServer}
b := buildService{server: storageServer}
p := projectService{server: storageServer}
h := healthService{}

restful.DefaultContainer.Add(j.WebService())
Expand All @@ -207,17 +203,11 @@ func main() {
restful.DefaultContainer.Filter(NCSACommonLogFormatLogger())

config := restfulspec.Config{
WebServices: restful.RegisteredWebServices(), // you control what services are visible
WebServices: restful.RegisteredWebServices(),
APIPath: "/apidocs.json",
PostBuildSwaggerObjectHandler: enrichSwaggerObject}
restful.DefaultContainer.Add(restfulspec.NewOpenAPIService(config))

// Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API
// You need to download the Swagger HTML5 assets and change the FilePath location in the config below.
// Open http://localhost:8080/apidocs/?url=http://localhost:8080/apidocs.json
//http.Handle("/apidocs/", http.StripPrefix("/apidocs/", http.FileServer(http.Dir("/swagger-ui/dist"))))

// Optionally, you may need to enable CORS for the UI to work.
cors := restful.CrossOriginResourceSharing{
AllowedHeaders: []string{"Content-Type", "Accept"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
Expand Down Expand Up @@ -258,7 +248,4 @@ func enrichSwaggerObject(swo *spec.Swagger) {
Version: "1.0.0",
},
}
swo.Tags = []spec.Tag{spec.Tag{TagProps: spec.TagProps{
Name: "brigade",
Description: "Brigade"}}}
}
40 changes: 24 additions & 16 deletions pkg/api/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,59 @@ package api
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"gopkg.in/gin-gonic/gin.v1"
restful "github.com/emicklei/go-restful"

"github.com/Azure/brigade/pkg/storage/mock"
)

func TestBuildLogs(t *testing.T) {
store := mock.New()
mockAPI := New(store)
rw := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rw)

//ctx, _ := gin.CreateTestContext(rw)

// There is a bug in Gin that will cause a panic if we don't send a request
// that has a query param.
ctx.Request = httptest.NewRequest("GET", "/?foo=bar", bytes.NewBuffer(nil))

mockAPI.Build().Logs(ctx)
logLines := rw.Body.String()
httpRequest, _ := http.NewRequest("GET", "/?foo=bar", bytes.NewBuffer(nil))
req := restful.NewRequest(httpRequest)
httpWriter := httptest.NewRecorder()
respo := restful.NewResponse(httpWriter)
respo.SetRequestAccepts("application/json")

mockAPI.Build().Logs(req, respo)
logLines := httpWriter.Body.String()
expect := fmt.Sprintf("%q", mock.StubLogData)
if logLines != expect {
t.Errorf("Expected %q, got %q", expect, logLines)
}

// Retest with streaming on, which should return line data instead of JSON data.
rw = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(rw)
ctx.Request = httptest.NewRequest("GET", "/?stream=true", bytes.NewBuffer(nil))
httpWriter = httptest.NewRecorder()
httpRequest = httptest.NewRequest("GET", "/?stream=true", bytes.NewBuffer(nil))
respo = restful.NewResponse(httpWriter)
req = restful.NewRequest(httpRequest)

mockAPI.Build().Logs(ctx)
logLines = rw.Body.String()
mockAPI.Build().Logs(req, respo)
logLines = httpWriter.Body.String()
if logLines != mock.StubLogData {
t.Errorf("Expected %q, got %q", mock.StubLogData, logLines)
}

// Check that we get a 204 for no content.
// Retest with streaming on, which should return line data instead of JSON data.
store.LogData = ""
rw = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(rw)
ctx.Request = httptest.NewRequest("GET", "/?a=b", bytes.NewBuffer(nil))
httpWriter = httptest.NewRecorder()
respo = restful.NewResponse(httpWriter)
httpRequest = httptest.NewRequest("GET", "/?a=b", bytes.NewBuffer(nil))
req = restful.NewRequest(httpRequest)

mockAPI.Build().Logs(ctx)
if rw.Code != 204 {
mockAPI.Build().Logs(req, respo)
if httpWriter.Code != 204 {
t.Errorf("Expected %q, got %q", mock.StubLogData, logLines)
}

Expand Down
1 change: 1 addition & 0 deletions pkg/api/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"

"github.com/Azure/brigade/pkg/storage"

restful "github.com/emicklei/go-restful"
)

Expand Down
31 changes: 18 additions & 13 deletions pkg/api/job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@ import (
"net/http/httptest"
"testing"

"gopkg.in/gin-gonic/gin.v1"

"github.com/Azure/brigade/pkg/storage/mock"

restful "github.com/emicklei/go-restful"
)

func TestJobLogs(t *testing.T) {
store := mock.New()
mockAPI := New(store)
rw := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rw)

// There is a bug in Gin that will cause a panic if we don't send a request
// that has a query param.
ctx.Request = httptest.NewRequest("GET", "/?foo=bar", bytes.NewBuffer(nil))
httpRequest := httptest.NewRequest("GET", "/?foo=bar", bytes.NewBuffer(nil))
req := restful.NewRequest(httpRequest)

respo := restful.NewResponse(rw)
respo.SetRequestAccepts("application/json")

mockAPI.Job().Logs(ctx)
mockAPI.Job().Logs(req, respo)
logLines := rw.Body.String()
expect := fmt.Sprintf("%q", mock.StubLogData)
if logLines != expect {
Expand All @@ -30,10 +31,12 @@ func TestJobLogs(t *testing.T) {

// Retest with streaming on, which should return line data instead of JSON data.
rw = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(rw)
ctx.Request = httptest.NewRequest("GET", "/?stream=true", bytes.NewBuffer(nil))
httpRequest = httptest.NewRequest("GET", "/?stream=true", bytes.NewBuffer(nil))
req = restful.NewRequest(httpRequest)

mockAPI.Job().Logs(ctx)
respo = restful.NewResponse(rw)

mockAPI.Job().Logs(req, respo)
logLines = rw.Body.String()
if logLines != mock.StubLogData {
t.Errorf("Expected %q, got %q", mock.StubLogData, logLines)
Expand All @@ -43,10 +46,12 @@ func TestJobLogs(t *testing.T) {
// Retest with streaming on, which should return line data instead of JSON data.
store.LogData = ""
rw = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(rw)
ctx.Request = httptest.NewRequest("GET", "/?a=b", bytes.NewBuffer(nil))
httpRequest = httptest.NewRequest("GET", "/?a=b", bytes.NewBuffer(nil))
req = restful.NewRequest(httpRequest)

respo = restful.NewResponse(rw)

mockAPI.Job().Logs(ctx)
mockAPI.Job().Logs(req, respo)
if rw.Code != 204 {
t.Errorf("Expected %q, got %q", mock.StubLogData, logLines)
}
Expand Down

0 comments on commit 035b89c

Please sign in to comment.