基本认证
引子
Iris 提供了一个web应用的测试框架 httpexpect ,给予了极大的支持。子包 iris/httptest
是 Iris + httpexpect.
这一组合的有力助手。
若你偏爱 Go 标准测试 net/http/httptest 包, 你依然可用它. 几乎每个类似Iris这样HTTP Web框架都与任何外部测试工具兼容,终究还是 HTTP。套路一句俗话,你大爷还是你大爷。
基础认证
首例是一个使用iris/httptest
进行基本认证的测试,主要分三个步骤
main.go
源码如下
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/basicauth"
)
func newApp() *iris.Application {
app := iris.New()
authConfig := basicauth.Config{
Users: map[string]string{"myusername": "mypassword"},
}
authentication := basicauth.New(authConfig)
app.Get("/", func(ctx iris.Context) { ctx.Redirect("/admin") })
needAuth := app.Party("/admin", authentication)
{
//http://localhost:8080/admin
needAuth.Get("/", h)
// http://localhost:8080/admin/profile
needAuth.Get("/profile", h)
// http://localhost:8080/admin/settings
needAuth.Get("/settings", h)
}
return app
}
func h(ctx iris.Context) {
username, password, _ := ctx.Request().BasicAuth()
// 上行第三个参数 ^ 必须为true, 中间件对此做了保证,否则当前handler将不会被执行
ctx.Writef("%s %s:%s", ctx.Path(), username, password)
}
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}
- 创建一个
main_test.go
文件
package main
import (
"testing"
"github.com/kataras/iris/httptest"
)
func TestNewApp(t *testing.T) {
app := newApp()
e := httptest.New(t, app)
// 未使用基础认证重定向到 /admin
e.GET("/").Expect().Status(httptest.StatusUnauthorized)
//未使用基础认证
e.GET("/admin").Expect().Status(httptest.StatusUnauthorized)
// 使用有效认证
e.GET("/admin").WithBasicAuth("myusername", "mypassword").Expect().
Status(httptest.StatusOK).Body().Equal("/admin myusername:mypassword")
e.GET("/admin/profile").WithBasicAuth("myusername", "mypassword").Expect().
Status(httptest.StatusOK).Body().Equal("/admin/profile myusername:mypassword")
e.GET("/admin/settings").WithBasicAuth("myusername", "mypassword").Expect().
Status(httptest.StatusOK).Body().Equal("/admin/settings myusername:mypassword")
// 使用无效认证
e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword").
Expect().Status(httptest.StatusUnauthorized)
}
- 命令行测试
$ go test -v
效果
=== RUN TestNewApp
--- PASS: TestNewApp (0.00s)
PASS
ok main 0.133s