Skip to content

Commit

Permalink
make tracking made calls disable able
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesse Michael committed Dec 9, 2017
1 parent 0824afb commit c8af462
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 88 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Usage of bin/go-rest-assured:
a port to listen on. default automatically assigns a port.
-preload string
a file to parse preloaded calls from.
-track
a flag to enable the storing of calls made to the service. (default true)
```

### Client
Expand Down
23 changes: 11 additions & 12 deletions assured/bindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,18 @@ import (
"net/http"
"strconv"

kitlog "github.com/go-kit/kit/log"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)

// StartApplicationHTTPListener creates a Go-routine that has an HTTP listener for the application endpoints
func StartApplicationHTTPListener(root context.Context, logger kitlog.Logger, port int, errc chan error) {
func StartApplicationHTTPListener(root context.Context, errc chan error, settings Settings) {
go func() {
ctx, cancel := context.WithCancel(root)
defer cancel()

listen, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", settings.Port))
if err != nil {
panic(err)
}
Expand All @@ -31,16 +30,16 @@ func StartApplicationHTTPListener(root context.Context, logger kitlog.Logger, po
listen.Close()
}()

router := createApplicationRouter(ctx, logger)
logger.Log("message", fmt.Sprintf("starting go rest assured on port %d", listen.Addr().(*net.TCPAddr).Port))
router := createApplicationRouter(ctx, settings)
settings.Logger.Log("message", fmt.Sprintf("starting go rest assured on port %d", listen.Addr().(*net.TCPAddr).Port))
errc <- http.Serve(listen, handlers.RecoveryHandler()(router))
}()
}

// createApplicationRouter sets up the router that will handle all of the application routes
func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Router {
func createApplicationRouter(ctx context.Context, settings Settings) *mux.Router {
router := mux.NewRouter()
e := NewAssuredEndpoints(logger)
e := NewAssuredEndpoints(settings)
assuredMethods := []string{
http.MethodGet,
http.MethodHead,
Expand All @@ -58,7 +57,7 @@ func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Rou
e.WrappedEndpoint(e.GivenEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(logger),
kithttp.ServerErrorLogger(settings.Logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -68,7 +67,7 @@ func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Rou
e.WrappedEndpoint(e.WhenEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(logger),
kithttp.ServerErrorLogger(settings.Logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -78,7 +77,7 @@ func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Rou
e.WrappedEndpoint(e.VerifyEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(logger),
kithttp.ServerErrorLogger(settings.Logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -88,7 +87,7 @@ func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Rou
e.WrappedEndpoint(e.ClearEndpoint),
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(logger),
kithttp.ServerErrorLogger(settings.Logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(assuredMethods...)

Expand All @@ -98,7 +97,7 @@ func createApplicationRouter(ctx context.Context, logger kitlog.Logger) *mux.Rou
e.ClearAllEndpoint,
decodeAssuredCall,
encodeAssuredCall,
kithttp.ServerErrorLogger(logger),
kithttp.ServerErrorLogger(settings.Logger),
kithttp.ServerAfter(kithttp.SetResponseHeader("Access-Control-Allow-Origin", "*"))),
).Methods(http.MethodDelete)

Expand Down
42 changes: 35 additions & 7 deletions assured/bindings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

func TestApplicationRouterGivenBinding(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

for _, verb := range verbs {
req, err := http.NewRequest(verb, "/given/rest/assured", nil)
Expand All @@ -27,7 +27,7 @@ func TestApplicationRouterGivenBinding(t *testing.T) {
}

func TestApplicationRouterWhenBinding(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

for _, verb := range verbs {
req, err := http.NewRequest(verb, "/given/rest/assured", bytes.NewBuffer([]byte(`{"assured": true}`)))
Expand All @@ -45,7 +45,7 @@ func TestApplicationRouterWhenBinding(t *testing.T) {
}

func TestApplicationRouterVerifyBinding(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

for _, verb := range verbs {
req, err := http.NewRequest(verb, "/verify/rest/assured", nil)
Expand All @@ -58,7 +58,7 @@ func TestApplicationRouterVerifyBinding(t *testing.T) {
}

func TestApplicationRouterClearBinding(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

for _, verb := range verbs {
req, err := http.NewRequest(verb, "/clear/rest/assured", nil)
Expand All @@ -71,7 +71,7 @@ func TestApplicationRouterClearBinding(t *testing.T) {
}

func TestApplicationRouterClearAllBinding(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

req, err := http.NewRequest(http.MethodDelete, "/clear", nil)
require.NoError(t, err)
Expand All @@ -82,7 +82,7 @@ func TestApplicationRouterClearAllBinding(t *testing.T) {
}

func TestApplicationRouterFailure(t *testing.T) {
router := createApplicationRouter(ctx, kitlog.NewLogfmtLogger(ioutil.Discard))
router := createApplicationRouter(ctx, testSettings)

req, err := http.NewRequest(http.MethodGet, "/trouble", nil)
require.NoError(t, err)
Expand Down Expand Up @@ -221,9 +221,10 @@ func TestEncodeAssuredCalls(t *testing.T) {

require.NoError(t, err)
require.Equal(t, "application/json", resp.HeaderMap.Get("Content-Type"))
require.Equal(t, `[{"Path":"test/assured","Method":"GET","StatusCode":200,"Response":"eyJhc3N1cmVkIjogdHJ1ZX0="},{"Path":"test/assured","Method":"GET","StatusCode":409,"Response":"ZXJyb3I="}]`+"\n", resp.Body.String())
require.Equal(t, `[{"path":"test/assured","method":"GET","status_code":200,"response":"eyJhc3N1cmVkIjogdHJ1ZX0="},{"path":"test/assured","method":"GET","status_code":409,"response":"ZXJyb3I="}]`+"\n", resp.Body.String())
}

//go-rest-assured test vars
var (
ctx = context.Background()
verbs = []string{
Expand All @@ -236,4 +237,31 @@ var (
http.MethodConnect,
http.MethodOptions,
}
call1 = &Call{
Path: "test/assured",
Method: "GET",
StatusCode: http.StatusOK,
Response: []byte(`{"assured": true}`),
}
call2 = &Call{
Path: "test/assured",
Method: "GET",
StatusCode: http.StatusConflict,
Response: []byte("error"),
}
call3 = &Call{
Path: "teapot/assured",
Method: "POST",
StatusCode: http.StatusTeapot,
}
fullAssuredCalls = &CallStore{
data: map[string][]*Call{
"GET:test/assured": {call1, call2},
"POST:teapot/assured": {call3},
},
}
testSettings = Settings{
Logger: kitlog.NewLogfmtLogger(ioutil.Discard),
TrackMadeCalls: true,
}
)
21 changes: 9 additions & 12 deletions assured/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,42 +16,39 @@ import (
type Client struct {
Errc chan error
Port int
logger kitlog.Logger
ctx context.Context
cancel context.CancelFunc
httpClient *http.Client
}

// NewDefaultClient creates a new go-rest-assured client with default parameters
func NewDefaultClient() *Client {
return NewClient(nil, 0, nil)
settings := Settings{
Logger: kitlog.NewLogfmtLogger(ioutil.Discard),
}
return NewClient(nil, settings)
}

// NewClient creates a new go-rest-assured client
func NewClient(root context.Context, port int, logger *kitlog.Logger) *Client {
func NewClient(root context.Context, settings Settings) *Client {
if root == nil {
root = context.Background()
}
if logger == nil {
l := kitlog.NewLogfmtLogger(ioutil.Discard)
logger = &l
}
if port == 0 {
if settings.Port == 0 {
if listen, err := net.Listen("tcp", ":0"); err == nil {
port = listen.Addr().(*net.TCPAddr).Port
settings.Port = listen.Addr().(*net.TCPAddr).Port
listen.Close()
}
}
ctx, cancel := context.WithCancel(root)
c := Client{
Errc: make(chan error),
logger: *logger,
Port: port,
Port: settings.Port,
ctx: ctx,
cancel: cancel,
httpClient: &http.Client{},
}
StartApplicationHTTPListener(c.ctx, c.logger, c.Port, c.Errc)
StartApplicationHTTPListener(c.ctx, c.Errc, settings)
return &c
}

Expand Down
8 changes: 6 additions & 2 deletions assured/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ import (

func TestClient(t *testing.T) {
httpClient := &http.Client{}
logger := kitlog.NewLogfmtLogger(ioutil.Discard)
ctx := context.Background()
client := NewClient(ctx, 9091, &logger)
settings := Settings{
Logger: kitlog.NewLogfmtLogger(ioutil.Discard),
Port: 9091,
TrackMadeCalls: true,
}
client := NewClient(ctx, settings)

url := client.URL()
require.Equal(t, "http://localhost:9091/when", url)
Expand Down
34 changes: 25 additions & 9 deletions assured/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,26 @@ import (

// AssuredEndpoints
type AssuredEndpoints struct {
logger kitlog.Logger
assuredCalls *CallStore
madeCalls *CallStore
logger kitlog.Logger
assuredCalls *CallStore
madeCalls *CallStore
trackMadeCalls bool
}

// Settings
type Settings struct {
Logger kitlog.Logger
Port int
TrackMadeCalls bool
}

// NewAssuredEndpoints creates a new instance of assured endpoints
func NewAssuredEndpoints(l kitlog.Logger) *AssuredEndpoints {
func NewAssuredEndpoints(settings Settings) *AssuredEndpoints {
return &AssuredEndpoints{
logger: l,
assuredCalls: NewCallStore(),
madeCalls: NewCallStore(),
assuredCalls: NewCallStore(),
madeCalls: NewCallStore(),
logger: settings.Logger,
trackMadeCalls: settings.TrackMadeCalls,
}
}

Expand All @@ -31,6 +40,7 @@ func (a *AssuredEndpoints) WrappedEndpoint(handler func(context.Context, *Call)
if !ok {
return nil, errors.New("unable to convert request to assured Call")
}

return handler(ctx, a)
}
}
Expand All @@ -51,16 +61,22 @@ func (a *AssuredEndpoints) WhenEndpoint(ctx context.Context, call *Call) (interf
return nil, errors.New("No assured calls")
}

a.madeCalls.Add(call)
if a.trackMadeCalls {
a.madeCalls.Add(call)
}
assured := calls[0]
a.assuredCalls.Rotate(assured)

a.logger.Log("message", "assured call responded", "path", call.ID())
return assured, nil
}

// VerifyEndpoint is used to verify a particular call
func (a *AssuredEndpoints) VerifyEndpoint(ctx context.Context, call *Call) (interface{}, error) {
return a.madeCalls.Get(call.ID()), nil
if a.trackMadeCalls {
return a.madeCalls.Get(call.ID()), nil
}
return nil, errors.New("Tracking made calls is disabled")
}

//ClearEndpoint is used to clear a specific assured call
Expand Down
Loading

0 comments on commit c8af462

Please sign in to comment.