mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 15:30:36 +01:00
Remove all tests from here and transfer them to iris-contrib/tests
This commit is contained in:
parent
93ddb7f3b4
commit
9e2eaec2a2
|
@ -3,11 +3,3 @@ language: go
|
|||
go:
|
||||
- go1.6
|
||||
- tip
|
||||
before_install:
|
||||
- go get github.com/iris-contrib/middleware/basicauth
|
||||
|
||||
script:
|
||||
- go test -v ./test -coverprofile=coverage.txt -covermode=atomic
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
|
101
test/a_tester.go
101
test/a_tester.go
|
@ -1,101 +0,0 @@
|
|||
//Package test | cd $GOPATH/src/github.com/kataras/iris/test && go test -v ./test/...
|
||||
package test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"testing"
|
||||
|
||||
"github.com/gavv/httpexpect"
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
// Configuration
|
||||
const (
|
||||
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'
|
||||
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
|
||||
)
|
||||
|
||||
// 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 EnableSubdomainTests {
|
||||
api.Listen(Host)
|
||||
} else {
|
||||
api.NoListen(Host)
|
||||
}
|
||||
}()
|
||||
|
||||
if ok := <-api.Available; !ok {
|
||||
t.Fatal("Unexpected error: server cannot start, please report this as bug!!")
|
||||
}
|
||||
close(api.Available)
|
||||
|
||||
handler := api.HTTPServer.Handler
|
||||
|
||||
testConfiguration := httpexpect.Config{
|
||||
BaseURL: HostURL,
|
||||
Client: &http.Client{
|
||||
Transport: httpexpect.NewFastBinder(handler),
|
||||
Jar: httpexpect.NewJar(),
|
||||
},
|
||||
Reporter: httpexpect.NewAssertReporter(t),
|
||||
}
|
||||
|
||||
if EnableDebug {
|
||||
testConfiguration.Printers = []httpexpect.Printer{
|
||||
httpexpect.NewDebugPrinter(t, true),
|
||||
}
|
||||
}
|
||||
|
||||
return httpexpect.WithConfig(testConfiguration)
|
||||
}
|
||||
|
||||
// hosts[windows]
|
||||
/*
|
||||
|
||||
# Copyright (c) 1993-2009 Microsoft Corp.
|
||||
#
|
||||
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
|
||||
#
|
||||
# This file contains the mappings of IP addresses to host names. Each
|
||||
# entry should be kept on an individual line. The IP address should
|
||||
# be placed in the first column followed by the corresponding host name.
|
||||
# The IP address and the host name should be separated by at least one
|
||||
# space.
|
||||
#
|
||||
# Additionally, comments (such as these) may be inserted on individual
|
||||
# lines or following the machine name denoted by a '#' symbol.
|
||||
#
|
||||
# For example:
|
||||
#
|
||||
# 102.54.94.97 rhino.acme.com # source server
|
||||
# 38.25.63.10 x.acme.com # x client host
|
||||
|
||||
# localhost name resolution is handled within DNS itself.
|
||||
127.0.0.1 localhost
|
||||
::1 localhost
|
||||
# for custom domain and subdomains
|
||||
127.0.0.1 mydomain.com
|
||||
127.0.0.1 mysubdomain.mydomain.com
|
||||
127.0.0.1 kataras.mydomain.com
|
||||
127.0.0.1 username1.mydomain.com
|
||||
127.0.0.1 username2.mydomain.com
|
||||
*/
|
|
@ -1,90 +0,0 @@
|
|||
package test
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
/* Contains tests for context.ReadJSON/ReadXML/ReadFORM */
|
||||
|
||||
type testBinderData struct {
|
||||
Username string
|
||||
Mail string
|
||||
Data []string `form:"mydata" json:"mydata"`
|
||||
}
|
||||
|
||||
type testBinderXMLData struct {
|
||||
XMLName xml.Name `xml:"info"`
|
||||
FirstAttr string `xml:"first,attr"`
|
||||
SecondAttr string `xml:"second,attr"`
|
||||
Name string `xml:"name",json:"name"`
|
||||
Birth string `xml:"birth",json:"birth"`
|
||||
Stars int `xml:"stars",json:"stars"`
|
||||
}
|
||||
|
||||
func TestBindForm(t *testing.T) {
|
||||
api := iris.New()
|
||||
api.Post("/form", func(ctx *iris.Context) {
|
||||
obj := testBinderData{}
|
||||
err := ctx.ReadForm(&obj)
|
||||
if err != nil {
|
||||
t.Fatalf("Error when parsing the FORM: %s", err.Error())
|
||||
}
|
||||
ctx.JSON(iris.StatusOK, obj)
|
||||
})
|
||||
|
||||
e := Tester(api, t)
|
||||
passed := map[string]interface{}{"Username": "myusername", "Mail": "mymail@iris-go.com", "mydata": url.Values{"[0]": []string{"mydata1"},
|
||||
"[1]": []string{"mydata2"}}}
|
||||
|
||||
expectedObject := testBinderData{Username: "myusername", Mail: "mymail@iris-go.com", Data: []string{"mydata1", "mydata2"}}
|
||||
|
||||
e.POST("/form").WithForm(passed).Expect().Status(iris.StatusOK).JSON().Object().Equal(expectedObject)
|
||||
}
|
||||
|
||||
func TestBindJSON(t *testing.T) {
|
||||
api := iris.New()
|
||||
api.Post("/json", func(ctx *iris.Context) {
|
||||
obj := testBinderData{}
|
||||
err := ctx.ReadJSON(&obj)
|
||||
if err != nil {
|
||||
t.Fatalf("Error when parsing the JSON body: %s", err.Error())
|
||||
}
|
||||
ctx.JSON(iris.StatusOK, obj)
|
||||
})
|
||||
|
||||
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"}}
|
||||
|
||||
e.POST("/json").WithJSON(passed).Expect().Status(iris.StatusOK).JSON().Object().Equal(expectedObject)
|
||||
}
|
||||
|
||||
func TestBindXML(t *testing.T) {
|
||||
api := iris.New()
|
||||
api.Post("/xml", func(ctx *iris.Context) {
|
||||
obj := testBinderXMLData{}
|
||||
err := ctx.ReadXML(&obj)
|
||||
if err != nil {
|
||||
t.Fatalf("Error when parsing the XML body: %s", err.Error())
|
||||
}
|
||||
ctx.XML(iris.StatusOK, obj)
|
||||
})
|
||||
|
||||
e := Tester(api, t)
|
||||
expectedObj := testBinderXMLData{
|
||||
XMLName: xml.Name{Local: "info", Space: "info"},
|
||||
FirstAttr: "this is the first attr",
|
||||
SecondAttr: "this is the second attr",
|
||||
Name: "Iris web framework",
|
||||
Birth: "13 March 2016",
|
||||
Stars: 4064,
|
||||
}
|
||||
// so far no WithXML or .XML like WithJSON and .JSON on httpexpect I added a feature request as post issue and we're waiting
|
||||
expectedBody := `<` + expectedObj.XMLName.Local + ` first="` + expectedObj.FirstAttr + `" second="` + expectedObj.SecondAttr + `"><name>` + expectedObj.Name + `</name><birth>` + expectedObj.Birth + `</birth><stars>` + strconv.Itoa(expectedObj.Stars) + `</stars></info>`
|
||||
e.POST("/xml").WithText(expectedBody).Expect().Status(iris.StatusOK).Body().Equal(expectedBody)
|
||||
}
|
|
@ -1,68 +0,0 @@
|
|||
package test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/iris-contrib/middleware/basicauth"
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
/* 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()
|
||||
|
||||
}
|
337
test/mux_test.go
337
test/mux_test.go
|
@ -1,337 +0,0 @@
|
|||
package test
|
||||
|
||||
// Contains tests for the mux(router)
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
type param struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
type route struct {
|
||||
Method string
|
||||
Path string
|
||||
RequestPath string
|
||||
RequestQuery string
|
||||
Body string
|
||||
Status int
|
||||
Register bool
|
||||
Params []param
|
||||
URLParams []param
|
||||
}
|
||||
|
||||
func TestMuxSimple(t *testing.T) {
|
||||
api := iris.New()
|
||||
routes := []route{
|
||||
// FOUND - registed
|
||||
{"GET", "/test_get", "/test_get", "", "hello, get!", 200, true, nil, nil},
|
||||
{"POST", "/test_post", "/test_post", "", "hello, post!", 200, true, nil, nil},
|
||||
{"PUT", "/test_put", "/test_put", "", "hello, put!", 200, true, nil, nil},
|
||||
{"DELETE", "/test_delete", "/test_delete", "", "hello, delete!", 200, true, nil, nil},
|
||||
{"HEAD", "/test_head", "/test_head", "", "hello, head!", 200, true, nil, nil},
|
||||
{"OPTIONS", "/test_options", "/test_options", "", "hello, options!", 200, true, nil, nil},
|
||||
{"CONNECT", "/test_connect", "/test_connect", "", "hello, connect!", 200, true, nil, nil},
|
||||
{"PATCH", "/test_patch", "/test_patch", "", "hello, patch!", 200, true, nil, nil},
|
||||
{"TRACE", "/test_trace", "/test_trace", "", "hello, trace!", 200, true, nil, nil},
|
||||
// NOT FOUND - not registed
|
||||
{"GET", "/test_get_nofound", "/test_get_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"POST", "/test_post_nofound", "/test_post_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"PUT", "/test_put_nofound", "/test_put_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"DELETE", "/test_delete_nofound", "/test_delete_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"HEAD", "/test_head_nofound", "/test_head_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"OPTIONS", "/test_options_nofound", "/test_options_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"CONNECT", "/test_connect_nofound", "/test_connect_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"PATCH", "/test_patch_nofound", "/test_patch_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
{"TRACE", "/test_trace_nofound", "/test_trace_nofound", "", "Not Found", 404, false, nil, nil},
|
||||
// Parameters
|
||||
{"GET", "/test_get_parameter1/:name", "/test_get_parameter1/iris", "", "name=iris", 200, true, []param{{"name", "iris"}}, nil},
|
||||
{"GET", "/test_get_parameter2/:name/details/:something", "/test_get_parameter2/iris/details/anything", "", "name=iris,something=anything", 200, true, []param{{"name", "iris"}, {"something", "anything"}}, nil},
|
||||
{"GET", "/test_get_parameter2/:name/details/:something/*else", "/test_get_parameter2/iris/details/anything/elsehere", "", "name=iris,something=anything,else=/elsehere", 200, true, []param{{"name", "iris"}, {"something", "anything"}, {"else", "elsehere"}}, nil},
|
||||
// URL Parameters
|
||||
{"GET", "/test_get_urlparameter1/first", "/test_get_urlparameter1/first", "name=irisurl", "name=irisurl", 200, true, nil, []param{{"name", "irisurl"}}},
|
||||
{"GET", "/test_get_urlparameter2/second", "/test_get_urlparameter2/second", "name=irisurl&something=anything", "name=irisurl,something=anything", 200, true, nil, []param{{"name", "irisurl"}, {"something", "anything"}}},
|
||||
{"GET", "/test_get_urlparameter2/first/second/third", "/test_get_urlparameter2/first/second/third", "name=irisurl&something=anything&else=elsehere", "name=irisurl,something=anything,else=elsehere", 200, true, nil, []param{{"name", "irisurl"}, {"something", "anything"}, {"else", "elsehere"}}},
|
||||
}
|
||||
|
||||
for idx := range routes {
|
||||
r := routes[idx]
|
||||
if r.Register {
|
||||
api.HandleFunc(r.Method, r.Path, func(ctx *iris.Context) {
|
||||
ctx.SetStatusCode(r.Status)
|
||||
if r.Params != nil && len(r.Params) > 0 {
|
||||
ctx.SetBodyString(ctx.Params.String())
|
||||
} else if r.URLParams != nil && len(r.URLParams) > 0 {
|
||||
if len(r.URLParams) != len(ctx.URLParams()) {
|
||||
t.Fatalf("Error when comparing length of url parameters %d != %d", len(r.URLParams), len(ctx.URLParams()))
|
||||
}
|
||||
paramsKeyVal := ""
|
||||
for idxp, p := range r.URLParams {
|
||||
val := ctx.URLParam(p.Key)
|
||||
paramsKeyVal += p.Key + "=" + val + ","
|
||||
if idxp == len(r.URLParams)-1 {
|
||||
paramsKeyVal = paramsKeyVal[0 : len(paramsKeyVal)-1]
|
||||
}
|
||||
}
|
||||
ctx.SetBodyString(paramsKeyVal)
|
||||
} else {
|
||||
ctx.SetBodyString(r.Body)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
e := Tester(api, t)
|
||||
|
||||
// run the tests (1)
|
||||
for idx := range routes {
|
||||
r := routes[idx]
|
||||
e.Request(r.Method, r.RequestPath).WithQueryString(r.RequestQuery).
|
||||
Expect().
|
||||
Status(r.Status).Body().Equal(r.Body)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestMuxSimpleParty(t *testing.T) {
|
||||
|
||||
api := iris.New()
|
||||
|
||||
h := func(c *iris.Context) { c.WriteString(c.HostString() + c.PathString()) }
|
||||
|
||||
if EnableSubdomainTests {
|
||||
subdomainParty := api.Party(Subdomain + ".")
|
||||
{
|
||||
subdomainParty.Get("/", h)
|
||||
subdomainParty.Get("/path1", h)
|
||||
subdomainParty.Get("/path2", h)
|
||||
subdomainParty.Get("/namedpath/:param1/something/:param2", h)
|
||||
subdomainParty.Get("/namedpath/:param1/something/:param2/else", h)
|
||||
}
|
||||
}
|
||||
|
||||
// simple
|
||||
p := api.Party("/party1")
|
||||
{
|
||||
p.Get("/", h)
|
||||
p.Get("/path1", h)
|
||||
p.Get("/path2", h)
|
||||
p.Get("/namedpath/:param1/something/:param2", h)
|
||||
p.Get("/namedpath/:param1/something/:param2/else", h)
|
||||
}
|
||||
|
||||
e := Tester(api, t)
|
||||
|
||||
request := func(reqPath string) {
|
||||
e.Request("GET", reqPath).
|
||||
Expect().
|
||||
Status(iris.StatusOK).Body().Equal(Host + reqPath)
|
||||
}
|
||||
|
||||
// run the tests
|
||||
request("/party1/")
|
||||
request("/party1/path1")
|
||||
request("/party1/path2")
|
||||
request("/party1/namedpath/theparam1/something/theparam2")
|
||||
request("/party1/namedpath/theparam1/something/theparam2/else")
|
||||
|
||||
if EnableSubdomainTests {
|
||||
subdomainRequest := func(reqPath string) {
|
||||
e.Request("GET", SubdomainURL+reqPath).
|
||||
Expect().
|
||||
Status(iris.StatusOK).Body().Equal(SubdomainHost + reqPath)
|
||||
}
|
||||
|
||||
subdomainRequest("/")
|
||||
subdomainRequest("/path1")
|
||||
subdomainRequest("/path2")
|
||||
subdomainRequest("/namedpath/theparam1/something/theparam2")
|
||||
subdomainRequest("/namedpath/theparam1/something/theparam2/else")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMuxPathEscape(t *testing.T) {
|
||||
api := iris.New()
|
||||
|
||||
api.Get("/details/:name", func(ctx *iris.Context) {
|
||||
name := ctx.Param("name")
|
||||
highlight := ctx.URLParam("highlight")
|
||||
ctx.Text(iris.StatusOK, fmt.Sprintf("name=%s,highlight=%s", name, highlight))
|
||||
})
|
||||
|
||||
e := Tester(api, t)
|
||||
|
||||
e.GET("/details/Sakamoto desu ga").
|
||||
WithQuery("highlight", "text").
|
||||
Expect().Status(iris.StatusOK).Body().Equal("name=Sakamoto desu ga,highlight=text")
|
||||
}
|
||||
|
||||
func TestMuxCustomErrors(t *testing.T) {
|
||||
var (
|
||||
notFoundMessage = "Iris custom message for 404 not found"
|
||||
internalServerMessage = "Iris custom message for 500 internal server error"
|
||||
routesCustomErrors = []route{
|
||||
// NOT FOUND CUSTOM ERRORS - not registed
|
||||
{"GET", "/test_get_nofound_custom", "/test_get_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"POST", "/test_post_nofound_custom", "/test_post_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"PUT", "/test_put_nofound_custom", "/test_put_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"DELETE", "/test_delete_nofound_custom", "/test_delete_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"HEAD", "/test_head_nofound_custom", "/test_head_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"OPTIONS", "/test_options_nofound_custom", "/test_options_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"CONNECT", "/test_connect_nofound_custom", "/test_connect_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"PATCH", "/test_patch_nofound_custom", "/test_patch_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
{"TRACE", "/test_trace_nofound_custom", "/test_trace_nofound_custom", "", notFoundMessage, 404, false, nil, nil},
|
||||
// SERVER INTERNAL ERROR 500 PANIC CUSTOM ERRORS - registed
|
||||
{"GET", "/test_get_panic_custom", "/test_get_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"POST", "/test_post_panic_custom", "/test_post_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"PUT", "/test_put_panic_custom", "/test_put_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"DELETE", "/test_delete_panic_custom", "/test_delete_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"HEAD", "/test_head_panic_custom", "/test_head_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"OPTIONS", "/test_options_panic_custom", "/test_options_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"CONNECT", "/test_connect_panic_custom", "/test_connect_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"PATCH", "/test_patch_panic_custom", "/test_patch_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
{"TRACE", "/test_trace_panic_custom", "/test_trace_panic_custom", "", internalServerMessage, 500, true, nil, nil},
|
||||
}
|
||||
api = iris.New()
|
||||
)
|
||||
|
||||
// first register the routes needed
|
||||
for _, r := range routesCustomErrors {
|
||||
if r.Register {
|
||||
api.HandleFunc(r.Method, r.Path, func(ctx *iris.Context) {
|
||||
ctx.EmitError(r.Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// register the custom errors
|
||||
api.OnError(404, func(ctx *iris.Context) {
|
||||
ctx.Write("%s", notFoundMessage)
|
||||
})
|
||||
|
||||
api.OnError(500, func(ctx *iris.Context) {
|
||||
ctx.Write("%s", internalServerMessage)
|
||||
})
|
||||
|
||||
// create httpexpect instance that will call fasthtpp.RequestHandler directly
|
||||
e := Tester(api, t)
|
||||
|
||||
// run the tests
|
||||
for _, r := range routesCustomErrors {
|
||||
e.Request(r.Method, r.RequestPath).
|
||||
Expect().
|
||||
Status(r.Status).Body().Equal(r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
type testUserAPI struct {
|
||||
*iris.Context
|
||||
}
|
||||
|
||||
// GET /users
|
||||
func (u testUserAPI) Get() {
|
||||
u.Write("Get Users\n")
|
||||
}
|
||||
|
||||
// GET /users/:param1 which its value passed to the id argument
|
||||
func (u testUserAPI) GetBy(id string) { // id equals to u.Param("param1")
|
||||
u.Write("Get By %s\n", id)
|
||||
}
|
||||
|
||||
// PUT /users
|
||||
func (u testUserAPI) Put() {
|
||||
u.Write("Put, name: %s\n", u.FormValue("name"))
|
||||
}
|
||||
|
||||
// POST /users/:param1
|
||||
func (u testUserAPI) PostBy(id string) {
|
||||
u.Write("Post By %s, name: %s\n", id, u.FormValue("name"))
|
||||
}
|
||||
|
||||
// DELETE /users/:param1
|
||||
func (u testUserAPI) DeleteBy(id string) {
|
||||
u.Write("Delete By %s\n", id)
|
||||
}
|
||||
|
||||
func TestMuxAPI(t *testing.T) {
|
||||
api := iris.New()
|
||||
|
||||
middlewareResponseText := "I assume that you are authenticated\n"
|
||||
api.API("/users", testUserAPI{}, func(ctx *iris.Context) { // optional middleware for .API
|
||||
// do your work here, or render a login window if not logged in, get the user and send it to the next middleware, or do all here
|
||||
ctx.Set("user", "username")
|
||||
ctx.Next()
|
||||
}, func(ctx *iris.Context) {
|
||||
if ctx.Get("user") == "username" {
|
||||
ctx.Write(middlewareResponseText)
|
||||
ctx.Next()
|
||||
} else {
|
||||
ctx.SetStatusCode(iris.StatusUnauthorized)
|
||||
}
|
||||
})
|
||||
|
||||
e := Tester(api, t)
|
||||
|
||||
userID := "4077"
|
||||
formname := "kataras"
|
||||
|
||||
e.GET("/users").Expect().Status(iris.StatusOK).Body().Equal(middlewareResponseText + "Get Users\n")
|
||||
e.GET("/users/" + userID).Expect().Status(iris.StatusOK).Body().Equal(middlewareResponseText + "Get By " + userID + "\n")
|
||||
e.PUT("/users").WithFormField("name", formname).Expect().Status(iris.StatusOK).Body().Equal(middlewareResponseText + "Put, 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")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
|
@ -1,87 +0,0 @@
|
|||
package test
|
||||
|
||||
// Contains tests for render/rest & render/template
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
type renderTestInformationType struct {
|
||||
XMLName xml.Name `xml:"info"`
|
||||
FirstAttr string `xml:"first,attr"`
|
||||
SecondAttr string `xml:"second,attr"`
|
||||
Name string `xml:"name",json:"name"`
|
||||
Birth string `xml:"birth",json:"birth"`
|
||||
Stars int `xml:"stars",json:"stars"`
|
||||
}
|
||||
|
||||
func TestRenderRest(t *testing.T) {
|
||||
api := iris.New()
|
||||
|
||||
dataContents := []byte("Some binary data here.")
|
||||
textContents := "Plain text here"
|
||||
JSONPContents := map[string]string{"hello": "jsonp"}
|
||||
JSONPCallback := "callbackName"
|
||||
JSONXMLContents := renderTestInformationType{
|
||||
XMLName: xml.Name{Local: "info", Space: "info"}, // only need to verify that later
|
||||
FirstAttr: "this is the first attr",
|
||||
SecondAttr: "this is the second attr",
|
||||
Name: "Iris web framework",
|
||||
Birth: "13 March 2016",
|
||||
Stars: 4064,
|
||||
}
|
||||
markdownContents := "# Hello dynamic markdown from Iris"
|
||||
|
||||
api.Get("/data", func(ctx *iris.Context) {
|
||||
ctx.Data(iris.StatusOK, dataContents)
|
||||
})
|
||||
|
||||
api.Get("/text", func(ctx *iris.Context) {
|
||||
ctx.Text(iris.StatusOK, textContents)
|
||||
})
|
||||
|
||||
api.Get("/jsonp", func(ctx *iris.Context) {
|
||||
ctx.JSONP(iris.StatusOK, JSONPCallback, JSONPContents)
|
||||
})
|
||||
|
||||
api.Get("/json", func(ctx *iris.Context) {
|
||||
ctx.JSON(iris.StatusOK, JSONXMLContents)
|
||||
})
|
||||
api.Get("/xml", func(ctx *iris.Context) {
|
||||
ctx.XML(iris.StatusOK, JSONXMLContents)
|
||||
})
|
||||
|
||||
api.Get("/markdown", func(ctx *iris.Context) {
|
||||
ctx.Markdown(iris.StatusOK, markdownContents)
|
||||
})
|
||||
|
||||
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))
|
||||
|
||||
textT := e.GET("/text").Expect().Status(iris.StatusOK)
|
||||
textT.Header("Content-Type").Equal("text/plain; charset=UTF-8")
|
||||
textT.Body().Equal(textContents)
|
||||
|
||||
JSONPT := e.GET("/jsonp").Expect().Status(iris.StatusOK)
|
||||
JSONPT.Header("Content-Type").Equal("application/javascript; charset=UTF-8")
|
||||
JSONPT.Body().Equal(JSONPCallback + `({"hello":"jsonp"});`)
|
||||
|
||||
JSONT := e.GET("/json").Expect().Status(iris.StatusOK)
|
||||
JSONT.Header("Content-Type").Equal("application/json; charset=UTF-8")
|
||||
JSONT.JSON().Object().Equal(JSONXMLContents)
|
||||
|
||||
XMLT := e.GET("/xml").Expect().Status(iris.StatusOK)
|
||||
XMLT.Header("Content-Type").Equal("text/xml; charset=UTF-8")
|
||||
XMLT.Body().Equal(`<` + JSONXMLContents.XMLName.Local + ` first="` + JSONXMLContents.FirstAttr + `" second="` + JSONXMLContents.SecondAttr + `"><name>` + JSONXMLContents.Name + `</name><birth>` + JSONXMLContents.Birth + `</birth><stars>` + strconv.Itoa(JSONXMLContents.Stars) + `</stars></info>`)
|
||||
|
||||
markdownT := e.GET("/markdown").Expect().Status(iris.StatusOK)
|
||||
markdownT.Header("Content-Type").Equal("text/html; charset=UTF-8")
|
||||
markdownT.Body().Equal("<h1>" + markdownContents[2:] + "</h1>\n")
|
||||
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
//Package test -v ./... builds all tests
|
||||
package test
|
||||
|
||||
// Contains tests for sessions(sessions package) & flash messages(context)
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func TestSessions(t *testing.T) {
|
||||
|
||||
values := map[string]interface{}{
|
||||
"Name": "iris",
|
||||
"Months": "4",
|
||||
"Secret": "dsads£2132215£%%Ssdsa",
|
||||
}
|
||||
|
||||
api := iris.New()
|
||||
api.Config.Sessions.Cookie = "mycustomsessionid"
|
||||
|
||||
writeValues := func(ctx *iris.Context) {
|
||||
sessValues := ctx.Session().GetAll()
|
||||
ctx.JSON(iris.StatusOK, sessValues)
|
||||
}
|
||||
|
||||
if EnableSubdomainTests {
|
||||
api.Party(Subdomain+".").Get("/get", func(ctx *iris.Context) {
|
||||
writeValues(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
api.Post("set", func(ctx *iris.Context) {
|
||||
vals := make(map[string]interface{}, 0)
|
||||
if err := ctx.ReadJSON(&vals); err != nil {
|
||||
t.Fatalf("Cannot readjson. Trace %s", err.Error())
|
||||
}
|
||||
for k, v := range vals {
|
||||
ctx.Session().Set(k, v)
|
||||
}
|
||||
})
|
||||
|
||||
api.Get("/get", func(ctx *iris.Context) {
|
||||
writeValues(ctx)
|
||||
})
|
||||
|
||||
api.Get("/clear", func(ctx *iris.Context) {
|
||||
ctx.Session().Clear()
|
||||
writeValues(ctx)
|
||||
})
|
||||
|
||||
api.Get("/destroy", func(ctx *iris.Context) {
|
||||
ctx.SessionDestroy()
|
||||
writeValues(ctx)
|
||||
// the cookie and all values should be empty
|
||||
})
|
||||
|
||||
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 EnableSubdomainTests {
|
||||
e.Request("GET", SubdomainURL+"/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values)
|
||||
}
|
||||
|
||||
// test destory which also clears first
|
||||
d := e.GET("/destroy").Expect().Status(iris.StatusOK)
|
||||
d.JSON().Object().Empty()
|
||||
d.Cookies().ContainsOnly(api.Config.Sessions.Cookie)
|
||||
// set and clear again
|
||||
e.POST("/set").WithJSON(values).Expect().Status(iris.StatusOK).Cookies().NotEmpty()
|
||||
e.GET("/clear").Expect().Status(iris.StatusOK).JSON().Object().Empty()
|
||||
}
|
||||
|
||||
func FlashMessagesTest(t *testing.T) {
|
||||
api := iris.New()
|
||||
values := map[string]string{"name": "kataras", "package": "iris"}
|
||||
|
||||
api.Put("/set", func(ctx *iris.Context) {
|
||||
for k, v := range values {
|
||||
ctx.SetFlash(k, v)
|
||||
}
|
||||
})
|
||||
|
||||
//we don't get the flash so on the next request the flash messages should be available.
|
||||
api.Get("/get_no_getflash", func(ctx *iris.Context) {})
|
||||
|
||||
api.Get("/get", func(ctx *iris.Context) {
|
||||
// one time one handler
|
||||
kv := make(map[string]string)
|
||||
for k := range values {
|
||||
kv[k], _ = ctx.GetFlash(k)
|
||||
}
|
||||
//second time on the same handler
|
||||
for k := range values {
|
||||
kv[k], _ = ctx.GetFlash(k)
|
||||
}
|
||||
|
||||
}, func(ctx *iris.Context) {
|
||||
// third time on a next handler
|
||||
// test the if next handler has access to them(must) because flash are request lifetime now.
|
||||
kv := make(map[string]string)
|
||||
for k := range values {
|
||||
kv[k], _ = ctx.GetFlash(k)
|
||||
}
|
||||
// print them to the client for test the response also
|
||||
ctx.JSON(iris.StatusOK, kv)
|
||||
})
|
||||
|
||||
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()
|
||||
e.GET("/get").Expect().Status(iris.StatusOK).JSON().Object().Equal(values)
|
||||
// second request ,the flash messages here should be not available and cookie has been removed
|
||||
// (the true is that the cookie is removed from the first GetFlash, but is available though the whole request saved on context's values for faster get, keep that secret!)*
|
||||
g := e.GET("/get").Expect().Status(iris.StatusOK)
|
||||
g.JSON().Object().Empty()
|
||||
g.Cookies().Empty()
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user