Skip to content

Commit

Permalink
Testing how to read config file and improve route_matchers tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aperezg committed May 11, 2019
1 parent bd321b5 commit 9de929e
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 20 deletions.
9 changes: 5 additions & 4 deletions internal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ type Config struct {

// ConfigCORS representation of section CORS of the yaml
type ConfigCORS struct {
Methods []string `yaml:"methods"`
Headers []string `yaml:"headers"`
Origins []string `yaml:"origins"`
ExposedHeaders []string `yaml:"exposed_headers"`
Methods []string `yaml:"methods"`
Headers []string `yaml:"headers"`
Origins []string `yaml:"origins"`
ExposedHeaders []string `yaml:"exposed_headers"`
AllowCredentials bool `yaml:"allow_credentials"`
}

// ReadConfigFile unmarshal content of config file to Config struct
Expand Down
55 changes: 55 additions & 0 deletions internal/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package killgrave

import (
"reflect"
"testing"

"github.com/pkg/errors"
)

func TestReadConfigFile(t *testing.T) {
tests := map[string]struct {
input string
expected Config
err error
}{
"valid config file": {"test/testdata/config.yml", validConfig(), nil},
"file not found": {"test/testdata/file.yml", Config{}, errors.New("error")},
"wrong yaml file": {"test/testdata/wrong_config.yml", Config{}, errors.New("error")},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var got Config
err := ReadConfigFile(tc.input, &got)

if err != nil && tc.err == nil {
t.Fatalf("not expected any erros and got %v", err)
}

if err == nil && tc.err != nil {
t.Fatalf("expected an error and got nil")
}

if !reflect.DeepEqual(tc.expected, got) {
t.Fatalf("expected: %v, got: %v", tc.expected, got)
}

})
}
}

func validConfig() Config {
return Config{
ImpostersPath: "imposters",
Port: 3000,
Host: "localhost",
CORS: ConfigCORS{
Methods: []string{"GET"},
Origins: []string{"*"},
Headers: []string{"Content-Type"},
ExposedHeaders: []string{"Cache-Control"},
AllowCredentials: true,
},
}
}
34 changes: 21 additions & 13 deletions internal/route_matchers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import (
"testing"

"github.com/gorilla/mux"
"github.com/pkg/errors"
)

func TestMatcherBySchema(t *testing.T) {
bodyA := ioutil.NopCloser(bytes.NewReader([]byte("{\"type\": \"gopher\"}")))
bodyB := ioutil.NopCloser(bytes.NewReader([]byte("{\"type\": \"cat\"}")))
emptyBody := ioutil.NopCloser(bytes.NewReader([]byte("")))
wrongBody := ioutil.NopCloser(errReader(0))

schemaGopherFile := "test/testdata/imposters/schemas/type_gopher.json"
schemaCatFile := "test/testdata/imposters/schemas/type_cat.json"
Expand Down Expand Up @@ -46,22 +48,22 @@ func TestMatcherBySchema(t *testing.T) {
httpRequestB := &http.Request{Body: bodyB}
okResponse := Response{Status: http.StatusOK}

var matcherData = []struct {
name string
fn mux.MatcherFunc
req *http.Request
res bool
var matcherData = map[string]struct {
fn mux.MatcherFunc
req *http.Request
res bool
}{
{"correct request schema", MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), httpRequestA, true},
{"imposter without request schema", MatcherBySchema(Imposter{Request: requestWithoutSchema, Response: okResponse}), httpRequestA, true},
{"malformatted schema file", MatcherBySchema(Imposter{Request: requestWithWrongSchema, Response: okResponse}), httpRequestA, false},
{"incorrect request schema", MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), httpRequestB, false},
{"non-existing schema file", MatcherBySchema(Imposter{Request: requestWithNonExistingSchema, Response: okResponse}), httpRequestB, false},
{"empty body with required schema file", MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), &http.Request{Body: emptyBody}, false},
"correct request schema": {MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), httpRequestA, true},
"imposter without request schema": {MatcherBySchema(Imposter{Request: requestWithoutSchema, Response: okResponse}), httpRequestA, true},
"malformatted schema file": {MatcherBySchema(Imposter{Request: requestWithWrongSchema, Response: okResponse}), httpRequestA, false},
"incorrect request schema": {MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), httpRequestB, false},
"non-existing schema file": {MatcherBySchema(Imposter{Request: requestWithNonExistingSchema, Response: okResponse}), httpRequestB, false},
"empty body with required schema file": {MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), &http.Request{Body: emptyBody}, false},
"invalid request body": {MatcherBySchema(Imposter{Request: requestWithSchema, Response: okResponse}), &http.Request{Body: wrongBody}, false},
}

for _, tt := range matcherData {
t.Run(tt.name, func(t *testing.T) {
for name, tt := range matcherData {
t.Run(name, func(t *testing.T) {
res := tt.fn(tt.req, nil)
if res != tt.res {
t.Fatalf("error while matching by request schema - expected: %t, given: %t", tt.res, res)
Expand All @@ -70,3 +72,9 @@ func TestMatcherBySchema(t *testing.T) {

}
}

type errReader int

func (errReader) Read(p []byte) (n int, err error) {
return 0, errors.New("test error")
}
13 changes: 11 additions & 2 deletions internal/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package killgrave

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
Expand All @@ -13,8 +14,9 @@ import (
)

var (
defaultCORSMethods = []string{"GET", "HEAD", "POST", "PUT", "OPTIONS", "DELETE", "PATCH", "TRACE", "CONNECT"}
defaultCORSHeaders = []string{"X-Requested-With", "Content-Type", "Authorization", "*"}
defaultCORSMethods = []string{"GET", "HEAD", "POST", "PUT", "OPTIONS", "DELETE", "PATCH", "TRACE", "CONNECT"}
defaultCORSHeaders = []string{"X-Requested-With", "Content-Type", "Authorization"}
defaultCORSExposedHeaders = []string{"Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"}
)

// Server definition of mock server
Expand All @@ -35,6 +37,7 @@ func NewServer(p string, r *mux.Router) *Server {
func (s *Server) AccessControl(config ConfigCORS) (h []handlers.CORSOption) {
h = append(h, handlers.AllowedMethods(defaultCORSMethods))
h = append(h, handlers.AllowedHeaders(defaultCORSHeaders))
h = append(h, handlers.ExposedHeaders(defaultCORSExposedHeaders))

if len(config.Methods) > 0 {
h = append(h, handlers.AllowedMethods(config.Methods))
Expand All @@ -51,6 +54,12 @@ func (s *Server) AccessControl(config ConfigCORS) (h []handlers.CORSOption) {
if len(config.ExposedHeaders) > 0 {
h = append(h, handlers.ExposedHeaders(config.ExposedHeaders))
}

fmt.Println(config)
if config.AllowCredentials {
h = append(h, handlers.AllowCredentials())
}

return
}

Expand Down
15 changes: 14 additions & 1 deletion internal/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,20 @@ func TestRunServer(t *testing.T) {

func TestAccessControl(t *testing.T) {
s := NewServer("test/testdata/imposters", mux.NewRouter())
h := s.AccessControl()
config := Config{
ImpostersPath: "imposters",
Port: 3000,
Host: "localhost",
CORS: ConfigCORS{
Methods: []string{"GET"},
Origins: []string{"*"},
Headers: []string{"Content-Type"},
ExposedHeaders: []string{"Cache-Control"},
AllowCredentials: true,
},
}

h := s.AccessControl(config.CORS)

if len(h) <= 0 {
t.Fatal("Expected any CORS options and got empty")
Expand Down
9 changes: 9 additions & 0 deletions internal/test/testdata/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
imposters_path: "imposters"
port: 3000
host: "localhost"
cors:
methods: ["GET"]
headers: ["Content-Type"]
exposed_headers: ["Cache-Control"]
origins: ["*"]
allow_credentials: true
1 change: 1 addition & 0 deletions internal/test/testdata/wrong_config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
error

0 comments on commit 9de929e

Please sign in to comment.