OSDN Git Service

Modify access token db to sqldb
[bytom/vapor.git] / net / http / authn / authn_test.go
1 package authn
2
3 import (
4         "net/http"
5         "os"
6         "strings"
7         "testing"
8
9         "github.com/vapor/accesstoken"
10         dbm "github.com/vapor/database/db"
11         _ "github.com/vapor/database/leveldb"
12         "github.com/vapor/database/orm"
13         _ "github.com/vapor/database/sqlite"
14         "github.com/vapor/errors"
15 )
16
17 func TestAuthenticate(t *testing.T) {
18         tokenDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
19         defer func() {
20                 tokenDB.Db().Close()
21                 os.RemoveAll("temp")
22         }()
23
24         tokenDB.Db().AutoMigrate(&orm.AccessToken{})
25         tokenStore := accesstoken.NewStore(tokenDB)
26         token, err := tokenStore.Create("alice", "test")
27         if err != nil {
28                 t.Errorf("create token error")
29         }
30
31         cases := []struct {
32                 id, tok string
33                 want    error
34         }{
35                 {"alice", token.Token, nil},
36                 {"alice", "alice:abcsdsdfassdfsefsfsfesfesfefsefa", ErrInvalidToken},
37         }
38
39         api := NewAPI(tokenStore, false)
40
41         for _, c := range cases {
42                 var username, password string
43                 toks := strings.SplitN(c.tok, ":", 2)
44                 if len(toks) > 0 {
45                         username = toks[0]
46                 }
47                 if len(toks) > 1 {
48                         password = toks[1]
49                 }
50
51                 req, _ := http.NewRequest("GET", "/", nil)
52                 req.SetBasicAuth(username, password)
53
54                 _, err := api.Authenticate(req)
55                 if errors.Root(err) != c.want {
56                         t.Errorf("Authenticate(%s) error = %s want %s", c.id, err, c.want)
57                 }
58         }
59 }