Update dependencies (#32)

This commit is contained in:
Joona Hoikkala
2018-01-22 11:19:33 +02:00
committed by GitHub
parent 733245fb3d
commit c5337fc841
1727 changed files with 697926 additions and 12716 deletions
+2
View File
@@ -0,0 +1,2 @@
// Package examples demonstrates httpexpect usage.
package examples
+49
View File
@@ -0,0 +1,49 @@
package examples
import (
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
// EchoHandler creates http.Handler using echo framework.
//
// Routes:
// GET /login authenticate user and return JWT token
// GET /restricted/hello return "hello, world!" (requires authentication)
func EchoHandler() http.Handler {
e := echo.New()
e.POST("/login", func(ctx echo.Context) error {
username := ctx.FormValue("username")
password := ctx.FormValue("password")
if username == "ford" && password == "betelgeuse7" {
// create token
token := jwt.New(jwt.SigningMethodHS256)
// generate encoded token and send it as response
t, err := token.SignedString([]byte("secret"))
if err != nil {
return err
}
return ctx.JSON(http.StatusOK, map[string]string{
"token": t,
})
}
return echo.ErrUnauthorized
})
r := e.Group("/restricted")
r.Use(middleware.JWT([]byte("secret")))
r.GET("/hello", func(ctx echo.Context) error {
return ctx.String(http.StatusOK, "hello, world!")
})
return e
}
+87
View File
@@ -0,0 +1,87 @@
package examples
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gavv/httpexpect"
)
// Echo JWT token authentication tests.
//
// This test is executed for the EchoHandler() in two modes:
// - via http client
// - via http.Handler
func testEcho(e *httpexpect.Expect) {
type Login struct {
Username string `form:"username"`
Password string `form:"password"`
}
e.POST("/login").WithForm(Login{"ford", "<bad password>"}).
Expect().
Status(http.StatusUnauthorized)
r := e.POST("/login").WithForm(Login{"ford", "betelgeuse7"}).
Expect().
Status(http.StatusOK).JSON().Object()
r.Keys().ContainsOnly("token")
token := r.Value("token").String().Raw()
e.GET("/restricted/hello").
Expect().
Status(http.StatusBadRequest)
e.GET("/restricted/hello").WithHeader("Authorization", "Bearer <bad token>").
Expect().
Status(http.StatusUnauthorized)
e.GET("/restricted/hello").WithHeader("Authorization", "Bearer "+token).
Expect().
Status(http.StatusOK).Body().Equal("hello, world!")
auth := e.Builder(func(req *httpexpect.Request) {
req.WithHeader("Authorization", "Bearer "+token)
})
auth.GET("/restricted/hello").
Expect().
Status(http.StatusOK).Body().Equal("hello, world!")
}
func TestEchoClient(t *testing.T) {
handler := EchoHandler()
server := httptest.NewServer(handler)
defer server.Close()
e := httpexpect.WithConfig(httpexpect.Config{
BaseURL: server.URL,
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
testEcho(e)
}
func TestEchoHandler(t *testing.T) {
handler := EchoHandler()
e := httpexpect.WithConfig(httpexpect.Config{
Client: &http.Client{
Transport: httpexpect.NewBinder(handler),
Jar: httpexpect.NewJar(),
},
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
testEcho(e)
}
+23
View File
@@ -0,0 +1,23 @@
package examples
import (
"github.com/valyala/fasthttp"
)
// FastHTTPHandler creates fasthttp.RequestHandler.
//
// Routes:
// GET /ping return "pong"
func FastHTTPHandler() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/ping":
ctx.SetStatusCode(fasthttp.StatusOK)
ctx.SetContentType("text/plain")
ctx.SetBody([]byte("pong"))
default:
panic("unsupported path")
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package examples
import (
"net/http"
"testing"
"github.com/gavv/httpexpect"
)
// fastHTTPTester returns a new Expect instance to test FastHTTPHandler().
func fastHTTPTester(t *testing.T) *httpexpect.Expect {
return httpexpect.WithConfig(httpexpect.Config{
// Pass requests directly to FastHTTPHandler.
Client: &http.Client{
Transport: httpexpect.NewFastBinder(FastHTTPHandler()),
Jar: httpexpect.NewJar(),
},
// Report errors using testify.
Reporter: httpexpect.NewAssertReporter(t),
})
}
func TestFastHTTP(t *testing.T) {
e := fastHTTPTester(t)
e.GET("/ping").Expect().
Status(200).
Text().Equal("pong")
}
+85
View File
@@ -0,0 +1,85 @@
package examples
import (
"encoding/json"
"net/http"
"path"
)
type (
fruitMap map[string]interface{}
)
// FruitsHandler creates http.Handler for the fruits server.
//
// Routes:
// GET /fruits get fruit list
// GET /fruits/{name} get fruit
// PUT /fruits/{name} add or update fruit
func FruitsHandler() http.Handler {
fruits := fruitMap{}
mux := http.NewServeMux()
mux.HandleFunc("/fruits", func(w http.ResponseWriter, r *http.Request) {
handleFruitList(fruits, w, r)
})
mux.HandleFunc("/fruits/", func(w http.ResponseWriter, r *http.Request) {
handleFruit(fruits, w, r)
})
return mux
}
func handleFruitList(fruits fruitMap, w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
ret := []string{}
for k := range fruits {
ret = append(ret, k)
}
b, err := json.Marshal(ret)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func handleFruit(fruits fruitMap, w http.ResponseWriter, r *http.Request) {
_, name := path.Split(r.URL.Path)
switch r.Method {
case "GET":
if data, ok := fruits[name]; ok {
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
} else {
w.WriteHeader(http.StatusNotFound)
}
case "PUT":
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
panic(err)
}
fruits[name] = data
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
+68
View File
@@ -0,0 +1,68 @@
package examples
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gavv/httpexpect"
)
func TestFruits(t *testing.T) {
handler := FruitsHandler()
server := httptest.NewServer(handler)
defer server.Close()
e := httpexpect.New(t, server.URL)
e.GET("/fruits").
Expect().
Status(http.StatusOK).JSON().Array().Empty()
orange := map[string]interface{}{
"weight": 100,
}
e.PUT("/fruits/orange").WithJSON(orange).
Expect().
Status(http.StatusNoContent).NoContent()
apple := map[string]interface{}{
"colors": []interface{}{"green", "red"},
"weight": 200,
}
e.PUT("/fruits/apple").WithJSON(apple).
Expect().
Status(http.StatusNoContent).NoContent()
e.GET("/fruits").
Expect().
Status(http.StatusOK).JSON().Array().ContainsOnly("orange", "apple")
e.GET("/fruits/orange").
Expect().
Status(http.StatusOK).JSON().Object().Equal(orange).NotEqual(apple)
e.GET("/fruits/orange").
Expect().
Status(http.StatusOK).
JSON().Object().ContainsKey("weight").ValueEqual("weight", 100)
obj := e.GET("/fruits/apple").
Expect().
Status(http.StatusOK).JSON().Object()
obj.Keys().ContainsOnly("colors", "weight")
obj.Value("colors").Array().Elements("green", "red")
obj.Value("colors").Array().Element(0).String().Equal("green")
obj.Value("colors").Array().Element(1).String().Equal("red")
obj.Value("weight").Number().Equal(200)
e.GET("/fruits/melon").
Expect().
Status(http.StatusNotFound)
}
+22
View File
@@ -0,0 +1,22 @@
package examples
import (
"net/http"
"google.golang.org/appengine"
)
// GaeHandler creates http.Handler to run in the Google App Engine.
//
// Routes:
// GET /ping return "pong"
func GaeHandler() http.Handler {
m := http.NewServeMux()
m.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
_ = appengine.NewContext(r)
w.Write([]byte("pong"))
})
return m
}
+64
View File
@@ -0,0 +1,64 @@
package examples
import (
"net/http"
"os"
"testing"
"github.com/gavv/httpexpect"
"google.golang.org/appengine/aetest"
)
// init() is used by GAE to start serving the app
// added here for illustration purposes
//
// func init() {
// http.Handle("/", GaeHandler())
// }
// gaeInstance is our global dev_appserver instance.
var gaeInstance aetest.Instance
// TestMain is called first to create the gaeInstance.
func TestMain(m *testing.M) {
// INFO: Remove the return to actually run the tests.
// Requires installed Google Appengine SDK.
// https://cloud.google.com/appengine/downloads
return
var err error
gaeInstance, err = aetest.NewInstance(nil)
if err != nil {
panic(err)
}
c := m.Run() // call all actual tests
gaeInstance.Close()
os.Exit(c)
}
// gaeTester returns a new Expect instance to test GaeHandler().
func gaeTester(t *testing.T) *httpexpect.Expect {
return httpexpect.WithConfig(httpexpect.Config{
// Use gaeInstance to create requests.
// aetest.Instance is compatible with httpexpect.RequestFactory.
RequestFactory: gaeInstance,
// Pass requests directly to GaeHandler.
Client: &http.Client{
Transport: httpexpect.NewBinder(GaeHandler()),
Jar: httpexpect.NewJar(),
},
// Report errors using testify.
Reporter: httpexpect.NewAssertReporter(t),
})
}
func TestGae(t *testing.T) {
e := gaeTester(t)
e.GET("/ping").Expect().
Status(200).
Text().Equal("pong")
}
+111
View File
@@ -0,0 +1,111 @@
// +build go1.8
package examples
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/sessions"
"gopkg.in/kataras/iris.v6/middleware/basicauth"
)
// IrisHandler tests iris v6's handler
func IrisHandler() http.Handler {
app := iris.New(iris.Configuration{VHost: "example.com"})
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
app.Adapt(sessions.New(sessions.Config{Cookie: "irissessionid"}))
app.Get("/things", func(c *iris.Context) {
c.JSON(iris.StatusOK, []interface{}{
iris.Map{
"name": "foo",
"description": "foo thing",
},
iris.Map{
"name": "bar",
"description": "bar thing",
},
})
})
app.Post("/redirect", func(c *iris.Context) {
c.Redirect("/things", iris.StatusFound)
})
app.Post("/params/:x/:y", func(c *iris.Context) {
c.JSON(iris.StatusOK, iris.Map{
"x": c.Param("x"),
"y": c.Param("y"),
"q": c.URLParam("q"),
"p1": c.FormValue("p1"),
"p2": c.FormValue("p2"),
})
})
auth := basicauth.Default(map[string]string{
"ford": "betelgeuse7",
})
app.Get("/auth", auth, func(c *iris.Context) {
c.Writef("authenticated!")
})
app.Post("/session/set", func(c *iris.Context) {
sess := iris.Map{}
if err := c.ReadJSON(&sess); err != nil {
panic(err.Error())
}
c.Session().Set("name", sess["name"])
})
app.Get("/session/get", func(c *iris.Context) {
name := c.Session().GetString("name")
c.JSON(iris.StatusOK, iris.Map{
"name": name,
})
})
app.Get("/stream", func(c *iris.Context) {
c.StreamWriter(func(w io.Writer) bool {
for i := 0; i < 10; i++ {
fmt.Fprintf(w, "%d", i)
}
// return true to continue, return false to stop and flush
return false
})
// if we had to write here then the StreamWriter callback should
// return true
})
app.Post("/stream", func(c *iris.Context) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.EmitError(iris.StatusBadRequest)
return
}
c.Write(body)
})
sub := app.Party("subdomain.")
sub.Post("/set", func(c *iris.Context) {
c.Session().Set("message", "hello from subdomain")
})
sub.Get("/get", func(c *iris.Context) {
c.Writef(c.Session().GetString("message"))
})
app.Boot()
return app.Router
}
+161
View File
@@ -0,0 +1,161 @@
// +build go1.8
package examples
import (
"net/http"
"strings"
"testing"
"github.com/gavv/httpexpect"
)
func irisTester(t *testing.T) *httpexpect.Expect {
handler := IrisHandler()
return httpexpect.WithConfig(httpexpect.Config{
BaseURL: "http://example.com",
Client: &http.Client{
Transport: httpexpect.NewBinder(handler),
Jar: httpexpect.NewJar(),
},
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
}
func TestIrisThings(t *testing.T) {
e := irisTester(t)
schema := `{
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"description": {"type": "string"}
},
"required": ["name", "description"]
}
}`
things := e.GET("/things").
Expect().
Status(http.StatusOK).JSON()
things.Schema(schema)
names := things.Path("$[*].name").Array()
names.Elements("foo", "bar")
for n, desc := range things.Path("$..description").Array().Iter() {
m := desc.String().Match("(.+) (.+)")
m.Index(1).Equal(names.Element(n).String().Raw())
m.Index(2).Equal("thing")
}
}
func TestIrisRedirect(t *testing.T) {
e := irisTester(t)
things := e.POST("/redirect").
Expect().
Status(http.StatusOK).JSON().Array()
things.Length().Equal(2)
things.Element(0).Object().ValueEqual("name", "foo")
things.Element(1).Object().ValueEqual("name", "bar")
}
func TestIrisParams(t *testing.T) {
e := irisTester(t)
type Form struct {
P1 string `form:"p1"`
P2 string `form:"p2"`
}
// POST /params/xxx/yyy?q=qqq
// Form: p1=P1&p2=P2
r := e.POST("/params/{x}/{y}", "xxx", "yyy").
WithQuery("q", "qqq").WithForm(Form{P1: "P1", P2: "P2"}).
Expect().
Status(http.StatusOK).JSON().Object()
r.Value("x").Equal("xxx")
r.Value("y").Equal("yyy")
r.Value("q").Equal("qqq")
r.ValueEqual("p1", "P1")
r.ValueEqual("p2", "P2")
}
func TestIrisAuth(t *testing.T) {
e := irisTester(t)
e.GET("/auth").
Expect().
Status(http.StatusUnauthorized)
e.GET("/auth").WithBasicAuth("ford", "<bad password>").
Expect().
Status(http.StatusUnauthorized)
e.GET("/auth").WithBasicAuth("ford", "betelgeuse7").
Expect().
Status(http.StatusOK).Body().Equal("authenticated!")
}
func TestIrisSession(t *testing.T) {
e := irisTester(t)
e.POST("/session/set").WithJSON(map[string]string{"name": "test"}).
Expect().
Status(http.StatusOK).Cookies().NotEmpty()
r := e.GET("/session/get").
Expect().
Status(http.StatusOK).JSON().Object()
r.Equal(map[string]string{
"name": "test",
})
}
func TestIrisStream(t *testing.T) {
e := irisTester(t)
e.GET("/stream").
Expect().
Status(http.StatusOK).
TransferEncoding("chunked"). // ensure server sent chunks
Body().Equal("0123456789")
// send chunks to server
e.POST("/stream").WithChunked(strings.NewReader("<long text>")).
Expect().
Status(http.StatusOK).Body().Equal("<long text>")
}
func TestIrisSubdomain(t *testing.T) {
e := irisTester(t)
sub := e.Builder(func(req *httpexpect.Request) {
req.WithURL("http://subdomain.127.0.0.1")
})
sub.POST("/set").
Expect().
Status(http.StatusOK)
sub.GET("/get").
Expect().
Status(http.StatusOK).
Body().Equal("hello from subdomain")
}