From 90c7e1466c5876b4d8b043a340735729ce6cfa3d Mon Sep 17 00:00:00 2001 From: Makis Maropoulos Date: Sat, 2 Jul 2016 18:53:36 +0200 Subject: [PATCH] Add test for basic auth --- .travis.yml | 4 +- test/a_tester.go | 37 ++++++----- test/context_binder_test.go | 6 +- test/middleware/middleware_basicauth_test.go | 69 +++++++++++++++++++ test/mux_test.go | 70 +++++++++++++++++--- test/render_test.go | 2 +- test/sessions_test.go | 12 ++-- 7 files changed, 160 insertions(+), 40 deletions(-) create mode 100644 test/middleware/middleware_basicauth_test.go diff --git a/.travis.yml b/.travis.yml index 2a364551..1462ac0c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,9 +3,11 @@ language: go go: - go1.6 - tip +before_install: + - go get github.com/iris-contrib/middleware/basicauth script: - - go test -v ./test + - go test -v ./test/... -coverprofile=coverage.txt -covermode=atomic after_success: - bash <(curl -s https://codecov.io/bash) diff --git a/test/a_tester.go b/test/a_tester.go index c47cf329..0e270f9a 100644 --- a/test/a_tester.go +++ b/test/a_tester.go @@ -1,4 +1,4 @@ -//Package test | cd $GOPATH/src/github.com/kataras/iris/test && go test -v +//Package test | cd $GOPATH/src/github.com/kataras/iris/test && go test -v ./test/... package test import ( @@ -13,32 +13,33 @@ import ( // Configuration const ( - scheme = "http://" - domain = "mydomain.com" - port = 8080 // this will go as test flag some day. + Scheme = "http://" + Domain = "mydomain.com" + Port = 8080 // this will go as test flag some day. // will start the server to real listen , this is useful ONLY WHEN TEST (AND) SUBDOMAINS, // the hosts file (on windows) must be setted as '127.0.0.1 mydomain.com' & '127.0.0.1 mysubdomain.mydomain.com' - enable_subdomain_tests = false // this will go as test flag some day also. - subdomain = "mysubdomain" - enable_debug = false // this will go as test flag some day also. + EnableSubdomainTests = false // this will go as test flag some day also. + Subdomain = "mysubdomain" + EnableDebug = false // this will go as test flag some day also. ) +// shared values var ( - host = domain + ":" + strconv.Itoa(port) - subdomainHost = subdomain + domain + "." + host - hostURL = scheme + host - subdomainURL = scheme + subdomainHost + Host = Domain + ":" + strconv.Itoa(Port) + SubdomainHost = Subdomain + Domain + "." + Host + HostURL = Scheme + Host + SubdomainURL = Scheme + SubdomainHost ) -// Prepare the test framework based on the Configuration -func tester(api *iris.Framework, t *testing.T) *httpexpect.Expect { +// Tester Prepares the test framework based on the Configuration +func Tester(api *iris.Framework, t *testing.T) *httpexpect.Expect { api.Config.DisableBanner = true go func() { // no need goroutine here, we could just add go api.Listen(addr) but newcomers can see easier that these will run in a non-blocking way - if enable_subdomain_tests { - api.Listen(host) + if EnableSubdomainTests { + api.Listen(Host) } else { - api.NoListen(host) + api.NoListen(Host) } }() @@ -50,7 +51,7 @@ func tester(api *iris.Framework, t *testing.T) *httpexpect.Expect { handler := api.HTTPServer.Handler testConfiguration := httpexpect.Config{ - BaseURL: hostURL, + BaseURL: HostURL, Client: &http.Client{ Transport: httpexpect.NewFastBinder(handler), Jar: httpexpect.NewJar(), @@ -58,7 +59,7 @@ func tester(api *iris.Framework, t *testing.T) *httpexpect.Expect { Reporter: httpexpect.NewAssertReporter(t), } - if enable_debug { + if EnableDebug { testConfiguration.Printers = []httpexpect.Printer{ httpexpect.NewDebugPrinter(t, true), } diff --git a/test/context_binder_test.go b/test/context_binder_test.go index 951bd260..9fdd5f98 100644 --- a/test/context_binder_test.go +++ b/test/context_binder_test.go @@ -37,7 +37,7 @@ func TestBindForm(t *testing.T) { ctx.JSON(iris.StatusOK, obj) }) - e := tester(api, t) + e := Tester(api, t) passed := map[string]interface{}{"Username": "myusername", "Mail": "mymail@iris-go.com", "mydata": url.Values{"[0]": []string{"mydata1"}, "[1]": []string{"mydata2"}}} @@ -57,7 +57,7 @@ func TestBindJSON(t *testing.T) { ctx.JSON(iris.StatusOK, obj) }) - e := tester(api, t) + e := Tester(api, t) passed := map[string]interface{}{"Username": "myusername", "Mail": "mymail@iris-go.com", "mydata": []string{"mydata1", "mydata2"}} expectedObject := testBinderData{Username: "myusername", Mail: "mymail@iris-go.com", Data: []string{"mydata1", "mydata2"}} @@ -75,7 +75,7 @@ func TestBindXML(t *testing.T) { ctx.XML(iris.StatusOK, obj) }) - e := tester(api, t) + e := Tester(api, t) expectedObj := testBinderXMLData{ XMLName: xml.Name{Local: "info", Space: "info"}, FirstAttr: "this is the first attr", diff --git a/test/middleware/middleware_basicauth_test.go b/test/middleware/middleware_basicauth_test.go new file mode 100644 index 00000000..2755cff3 --- /dev/null +++ b/test/middleware/middleware_basicauth_test.go @@ -0,0 +1,69 @@ +package middleware + +import ( + "testing" + + "github.com/iris-contrib/middleware/basicauth" + "github.com/kataras/iris" + . "github.com/kataras/iris/test" +) + +/* Yes, middleware front-end tests also here, so if you want to test you have to go get at least one middleware */ + +func TestMiddlewareBasicAuth(t *testing.T) { + var ( + api = iris.New() + user1 = "myusername" + user1pass = "mypassword" + user2 = "mySecondusername" + user2pass = "mySecondpassword" + users = map[string]string{user1: user1pass, user2: user2pass} + config = basicauth.Config{ // default configuration, same as .Default(users) + Users: users, + Realm: "Authorization Required", + ContextKey: "user", + } + + authentication = basicauth.New(config) + ) + + // for global api.Use(authentication) + h := func(ctx *iris.Context) { + // username := ctx.GetString(config.ContextKey) + // or + username := config.User(ctx) + ctx.Write("%s", username) + } + + api.Get("/secret", authentication, h) + api.Get("/secret/profile", authentication, h) + api.Get("/othersecret", authentication, h) + api.Get("/no_authenticate", h) // the body should be empty here + + e := Tester(api, t) + + testBasicAuth := func(path, username, password string) { + e.GET(path).WithBasicAuth(username, password).Expect().Status(iris.StatusOK).Body().Equal(username) + } + testBasicAuthInvalid := func(path, username, password string) { + e.GET(path).WithBasicAuth(username, password).Expect().Status(iris.StatusUnauthorized) + } + + // valid auth + testBasicAuth("/secret", user1, user1pass) + testBasicAuth("/secret", user2, user2pass) + testBasicAuth("/secret/profile", user1, user1pass) + testBasicAuth("/secret/profile", user2, user2pass) + testBasicAuth("/othersecret", user1, user1pass) + testBasicAuth("/othersecret", user2, user2pass) + // invalid auth + testBasicAuthInvalid("/secret", user1+"invalid", user1pass) + testBasicAuthInvalid("/secret", user2, user2pass+"invalid") + testBasicAuthInvalid("/secret/profile", user1+"invalid", user1pass+"c") + testBasicAuthInvalid("/secret/profile", user2, user2pass+"invalid") + testBasicAuthInvalid("/othersecret", user1+"invalid", user1pass) + testBasicAuthInvalid("/othersecret", user2, user2pass+"invalid") + // no auth + e.GET("/no_authenticate").Expect().Status(iris.StatusOK).Body().Empty() + +} diff --git a/test/mux_test.go b/test/mux_test.go index 60cdf8ac..06ba87c0 100644 --- a/test/mux_test.go +++ b/test/mux_test.go @@ -87,7 +87,7 @@ func TestMuxSimple(t *testing.T) { } } - e := tester(api, t) + e := Tester(api, t) // run the tests (1) for idx := range routes { @@ -105,8 +105,8 @@ func TestMuxSimpleParty(t *testing.T) { h := func(c *iris.Context) { c.WriteString(c.HostString() + c.PathString()) } - if enable_subdomain_tests { - subdomainParty := api.Party(subdomain + ".") + if EnableSubdomainTests { + subdomainParty := api.Party(Subdomain + ".") { subdomainParty.Get("/", h) subdomainParty.Get("/path1", h) @@ -126,12 +126,12 @@ func TestMuxSimpleParty(t *testing.T) { p.Get("/namedpath/:param1/something/:param2/else", h) } - e := tester(api, t) + e := Tester(api, t) request := func(reqPath string) { e.Request("GET", reqPath). Expect(). - Status(iris.StatusOK).Body().Equal(host + reqPath) + Status(iris.StatusOK).Body().Equal(Host + reqPath) } // run the tests @@ -141,11 +141,11 @@ func TestMuxSimpleParty(t *testing.T) { request("/party1/namedpath/theparam1/something/theparam2") request("/party1/namedpath/theparam1/something/theparam2/else") - if enable_subdomain_tests { + if EnableSubdomainTests { subdomainRequest := func(reqPath string) { - e.Request("GET", subdomainURL+reqPath). + e.Request("GET", SubdomainURL+reqPath). Expect(). - Status(iris.StatusOK).Body().Equal(subdomainHost + reqPath) + Status(iris.StatusOK).Body().Equal(SubdomainHost + reqPath) } subdomainRequest("/") @@ -165,7 +165,7 @@ func TestMuxPathEscape(t *testing.T) { ctx.Text(iris.StatusOK, fmt.Sprintf("name=%s,highlight=%s", name, highlight)) }) - e := tester(api, t) + e := Tester(api, t) e.GET("/details/Sakamoto desu ga"). WithQuery("highlight", "text"). @@ -220,7 +220,7 @@ func TestMuxCustomErrors(t *testing.T) { }) // create httpexpect instance that will call fasthtpp.RequestHandler directly - e := tester(api, t) + e := Tester(api, t) // run the tests for _, r := range routesCustomErrors { @@ -276,7 +276,7 @@ func TestMuxAPI(t *testing.T) { } }) - e := tester(api, t) + e := Tester(api, t) userID := "4077" formname := "kataras" @@ -287,3 +287,51 @@ func TestMuxAPI(t *testing.T) { e.POST("/users/"+userID).WithFormField("name", formname).Expect().Status(iris.StatusOK).Body().Equal(middlewareResponseText + "Post By " + userID + ", name: " + formname + "\n") e.DELETE("/users/" + userID).Expect().Status(iris.StatusOK).Body().Equal(middlewareResponseText + "Delete By " + userID + "\n") } + +type myTestHandlerData struct { + Sysname string // this will be the same for all requests + Version int // this will be the same for all requests + DynamicPathParameter string // this will be different for each request +} + +type myTestCustomHandler struct { + data myTestHandlerData +} + +func (m *myTestCustomHandler) Serve(ctx *iris.Context) { + data := &m.data + data.DynamicPathParameter = ctx.Param("myparam") + ctx.JSON(iris.StatusOK, data) +} + +func TestMuxCustomHandler(t *testing.T) { + api := iris.New() + myData := myTestHandlerData{ + Sysname: "Redhat", + Version: 1, + } + api.Handle("GET", "/custom_handler_1/:myparam", &myTestCustomHandler{myData}) + api.Handle("GET", "/custom_handler_2/:myparam", &myTestCustomHandler{myData}) + + e := Tester(api, t) + // two times per route + param1 := "thisimyparam1" + expectedData1 := myData + expectedData1.DynamicPathParameter = param1 + e.GET("/custom_handler_1/" + param1).Expect().Status(iris.StatusOK).JSON().Equal(expectedData1) + + param2 := "thisimyparam2" + expectedData2 := myData + expectedData2.DynamicPathParameter = param2 + e.GET("/custom_handler_1/" + param2).Expect().Status(iris.StatusOK).JSON().Equal(expectedData2) + + param3 := "thisimyparam3" + expectedData3 := myData + expectedData3.DynamicPathParameter = param3 + e.GET("/custom_handler_2/" + param3).Expect().Status(iris.StatusOK).JSON().Equal(expectedData3) + + param4 := "thisimyparam4" + expectedData4 := myData + expectedData4.DynamicPathParameter = param4 + e.GET("/custom_handler_2/" + param4).Expect().Status(iris.StatusOK).JSON().Equal(expectedData4) +} diff --git a/test/render_test.go b/test/render_test.go index b491110d..a618d8c9 100644 --- a/test/render_test.go +++ b/test/render_test.go @@ -59,7 +59,7 @@ func TestRenderRest(t *testing.T) { ctx.Markdown(iris.StatusOK, markdownContents) }) - e := tester(api, t) + e := Tester(api, t) dataT := e.GET("/data").Expect().Status(iris.StatusOK) dataT.Header("Content-Type").Equal("application/octet-stream") dataT.Body().Equal(string(dataContents)) diff --git a/test/sessions_test.go b/test/sessions_test.go index 52eaebd0..1bdb7c02 100644 --- a/test/sessions_test.go +++ b/test/sessions_test.go @@ -25,8 +25,8 @@ func TestSessions(t *testing.T) { ctx.JSON(iris.StatusOK, sessValues) } - if enable_subdomain_tests { - api.Party(subdomain+".").Get("/get", func(ctx *iris.Context) { + if EnableSubdomainTests { + api.Party(Subdomain+".").Get("/get", func(ctx *iris.Context) { writeValues(ctx) }) } @@ -56,12 +56,12 @@ func TestSessions(t *testing.T) { // the cookie and all values should be empty }) - e := tester(api, t) + e := Tester(api, t) e.POST("/set").WithJSON(values).Expect().Status(iris.StatusOK).Cookies().NotEmpty() e.GET("/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values) - if enable_subdomain_tests { - e.Request("GET", subdomainURL+"/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values) + if EnableSubdomainTests { + e.Request("GET", SubdomainURL+"/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values) } // test destory which also clears first @@ -108,7 +108,7 @@ func FlashMessagesTest(t *testing.T) { ctx.JSON(iris.StatusOK, kv) }) - e := tester(api, t) + e := Tester(api, t) e.PUT("/set").Expect().Status(iris.StatusOK).Cookies().NotEmpty() // just a request which does not use the flash message, so flash messages should be available on the next request e.GET("/get_no_getflash").Expect().Status(iris.StatusOK).Cookies().NotEmpty()