基本认证

未匹配的标注

引子

Iris 提供了一个web应用的测试框架 httpexpect ,给予了极大的支持。子包 iris/httptest 是 Iris + httpexpect. 这一组合的有力助手。

若你偏爱 Go 标准测试 net/http/httptest 包, 你依然可用它. 几乎每个类似Iris这样HTTP Web框架都与任何外部测试工具兼容,终究还是 HTTP。套路一句俗话,你大爷还是你大爷。

基础认证

首例是一个使用iris/httptest 进行基本认证的测试,主要分三个步骤

  1. 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"))
}
  1. 创建一个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)

}
  1. 命令行测试
$ go test -v

效果

=== RUN   TestNewApp
--- PASS: TestNewApp (0.00s)
PASS
ok      main      0.133s

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
pardon110
讨论数量: 0
发起讨论 只看当前版本


暂无话题~