Add test for basic auth

This commit is contained in:
Makis Maropoulos 2016-07-02 18:53:36 +02:00
parent 263fc77e5c
commit 90c7e1466c
7 changed files with 160 additions and 40 deletions

View File

@ -3,9 +3,11 @@ language: go
go: go:
- go1.6 - go1.6
- tip - tip
before_install:
- go get github.com/iris-contrib/middleware/basicauth
script: script:
- go test -v ./test - go test -v ./test/... -coverprofile=coverage.txt -covermode=atomic
after_success: after_success:
- bash <(curl -s https://codecov.io/bash) - bash <(curl -s https://codecov.io/bash)

View File

@ -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 package test
import ( import (
@ -13,32 +13,33 @@ import (
// Configuration // Configuration
const ( const (
scheme = "http://" Scheme = "http://"
domain = "mydomain.com" Domain = "mydomain.com"
port = 8080 // this will go as test flag some day. 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, // 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' // 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. EnableSubdomainTests = false // this will go as test flag some day also.
subdomain = "mysubdomain" Subdomain = "mysubdomain"
enable_debug = false // this will go as test flag some day also. EnableDebug = false // this will go as test flag some day also.
) )
// shared values
var ( var (
host = domain + ":" + strconv.Itoa(port) Host = Domain + ":" + strconv.Itoa(Port)
subdomainHost = subdomain + domain + "." + host SubdomainHost = Subdomain + Domain + "." + Host
hostURL = scheme + host HostURL = Scheme + Host
subdomainURL = scheme + subdomainHost SubdomainURL = Scheme + SubdomainHost
) )
// Prepare the test framework based on the Configuration // Tester Prepares the test framework based on the Configuration
func tester(api *iris.Framework, t *testing.T) *httpexpect.Expect { func Tester(api *iris.Framework, t *testing.T) *httpexpect.Expect {
api.Config.DisableBanner = true 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 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 { if EnableSubdomainTests {
api.Listen(host) api.Listen(Host)
} else { } 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 handler := api.HTTPServer.Handler
testConfiguration := httpexpect.Config{ testConfiguration := httpexpect.Config{
BaseURL: hostURL, BaseURL: HostURL,
Client: &http.Client{ Client: &http.Client{
Transport: httpexpect.NewFastBinder(handler), Transport: httpexpect.NewFastBinder(handler),
Jar: httpexpect.NewJar(), Jar: httpexpect.NewJar(),
@ -58,7 +59,7 @@ func tester(api *iris.Framework, t *testing.T) *httpexpect.Expect {
Reporter: httpexpect.NewAssertReporter(t), Reporter: httpexpect.NewAssertReporter(t),
} }
if enable_debug { if EnableDebug {
testConfiguration.Printers = []httpexpect.Printer{ testConfiguration.Printers = []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true), httpexpect.NewDebugPrinter(t, true),
} }

View File

@ -37,7 +37,7 @@ func TestBindForm(t *testing.T) {
ctx.JSON(iris.StatusOK, obj) 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"}, passed := map[string]interface{}{"Username": "myusername", "Mail": "mymail@iris-go.com", "mydata": url.Values{"[0]": []string{"mydata1"},
"[1]": []string{"mydata2"}}} "[1]": []string{"mydata2"}}}
@ -57,7 +57,7 @@ func TestBindJSON(t *testing.T) {
ctx.JSON(iris.StatusOK, obj) 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"}} 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"}} 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) ctx.XML(iris.StatusOK, obj)
}) })
e := tester(api, t) e := Tester(api, t)
expectedObj := testBinderXMLData{ expectedObj := testBinderXMLData{
XMLName: xml.Name{Local: "info", Space: "info"}, XMLName: xml.Name{Local: "info", Space: "info"},
FirstAttr: "this is the first attr", FirstAttr: "this is the first attr",

View File

@ -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()
}

View File

@ -87,7 +87,7 @@ func TestMuxSimple(t *testing.T) {
} }
} }
e := tester(api, t) e := Tester(api, t)
// run the tests (1) // run the tests (1)
for idx := range routes { for idx := range routes {
@ -105,8 +105,8 @@ func TestMuxSimpleParty(t *testing.T) {
h := func(c *iris.Context) { c.WriteString(c.HostString() + c.PathString()) } h := func(c *iris.Context) { c.WriteString(c.HostString() + c.PathString()) }
if enable_subdomain_tests { if EnableSubdomainTests {
subdomainParty := api.Party(subdomain + ".") subdomainParty := api.Party(Subdomain + ".")
{ {
subdomainParty.Get("/", h) subdomainParty.Get("/", h)
subdomainParty.Get("/path1", h) subdomainParty.Get("/path1", h)
@ -126,12 +126,12 @@ func TestMuxSimpleParty(t *testing.T) {
p.Get("/namedpath/:param1/something/:param2/else", h) p.Get("/namedpath/:param1/something/:param2/else", h)
} }
e := tester(api, t) e := Tester(api, t)
request := func(reqPath string) { request := func(reqPath string) {
e.Request("GET", reqPath). e.Request("GET", reqPath).
Expect(). Expect().
Status(iris.StatusOK).Body().Equal(host + reqPath) Status(iris.StatusOK).Body().Equal(Host + reqPath)
} }
// run the tests // run the tests
@ -141,11 +141,11 @@ func TestMuxSimpleParty(t *testing.T) {
request("/party1/namedpath/theparam1/something/theparam2") request("/party1/namedpath/theparam1/something/theparam2")
request("/party1/namedpath/theparam1/something/theparam2/else") request("/party1/namedpath/theparam1/something/theparam2/else")
if enable_subdomain_tests { if EnableSubdomainTests {
subdomainRequest := func(reqPath string) { subdomainRequest := func(reqPath string) {
e.Request("GET", subdomainURL+reqPath). e.Request("GET", SubdomainURL+reqPath).
Expect(). Expect().
Status(iris.StatusOK).Body().Equal(subdomainHost + reqPath) Status(iris.StatusOK).Body().Equal(SubdomainHost + reqPath)
} }
subdomainRequest("/") subdomainRequest("/")
@ -165,7 +165,7 @@ func TestMuxPathEscape(t *testing.T) {
ctx.Text(iris.StatusOK, fmt.Sprintf("name=%s,highlight=%s", name, highlight)) 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"). e.GET("/details/Sakamoto desu ga").
WithQuery("highlight", "text"). WithQuery("highlight", "text").
@ -220,7 +220,7 @@ func TestMuxCustomErrors(t *testing.T) {
}) })
// create httpexpect instance that will call fasthtpp.RequestHandler directly // create httpexpect instance that will call fasthtpp.RequestHandler directly
e := tester(api, t) e := Tester(api, t)
// run the tests // run the tests
for _, r := range routesCustomErrors { for _, r := range routesCustomErrors {
@ -276,7 +276,7 @@ func TestMuxAPI(t *testing.T) {
} }
}) })
e := tester(api, t) e := Tester(api, t)
userID := "4077" userID := "4077"
formname := "kataras" 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.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") 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)
}

View File

@ -59,7 +59,7 @@ func TestRenderRest(t *testing.T) {
ctx.Markdown(iris.StatusOK, markdownContents) ctx.Markdown(iris.StatusOK, markdownContents)
}) })
e := tester(api, t) e := Tester(api, t)
dataT := e.GET("/data").Expect().Status(iris.StatusOK) dataT := e.GET("/data").Expect().Status(iris.StatusOK)
dataT.Header("Content-Type").Equal("application/octet-stream") dataT.Header("Content-Type").Equal("application/octet-stream")
dataT.Body().Equal(string(dataContents)) dataT.Body().Equal(string(dataContents))

View File

@ -25,8 +25,8 @@ func TestSessions(t *testing.T) {
ctx.JSON(iris.StatusOK, sessValues) ctx.JSON(iris.StatusOK, sessValues)
} }
if enable_subdomain_tests { if EnableSubdomainTests {
api.Party(subdomain+".").Get("/get", func(ctx *iris.Context) { api.Party(Subdomain+".").Get("/get", func(ctx *iris.Context) {
writeValues(ctx) writeValues(ctx)
}) })
} }
@ -56,12 +56,12 @@ func TestSessions(t *testing.T) {
// the cookie and all values should be empty // 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.POST("/set").WithJSON(values).Expect().Status(iris.StatusOK).Cookies().NotEmpty()
e.GET("/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values) e.GET("/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values)
if enable_subdomain_tests { if EnableSubdomainTests {
e.Request("GET", subdomainURL+"/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values) e.Request("GET", SubdomainURL+"/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values)
} }
// test destory which also clears first // test destory which also clears first
@ -108,7 +108,7 @@ func FlashMessagesTest(t *testing.T) {
ctx.JSON(iris.StatusOK, kv) ctx.JSON(iris.StatusOK, kv)
}) })
e := tester(api, t) e := Tester(api, t)
e.PUT("/set").Expect().Status(iris.StatusOK).Cookies().NotEmpty() 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 // 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() e.GET("/get_no_getflash").Expect().Status(iris.StatusOK).Cookies().NotEmpty()