9 "github.com/jinzhu/gorm"
11 "github.com/vapor/database/orm"
13 dbm "github.com/vapor/database/db"
14 _ "github.com/vapor/database/leveldb"
15 _ "github.com/vapor/database/sqlite"
16 "github.com/vapor/errors"
19 func TestCreate(t *testing.T) {
20 testDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
26 testDB.Db().AutoMigrate(&orm.AccessToken{})
28 cs := NewStore(testDB)
35 {"b", "network", nil},
36 {"", "client", ErrBadID},
37 {"bad:id", "client", ErrBadID},
38 {"a", "network", ErrDuplicateID}, // this aborts the transaction, so no tests can follow
41 for _, c := range cases {
42 _, err := cs.Create(c.id, c.typ)
43 if errors.Root(err) != c.want {
44 t.Errorf("Create(%s, %s) error = %s want %s", c.id, c.typ, err, c.want)
49 func TestList(t *testing.T) {
50 ctx := context.Background()
51 testDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
57 testDB.Db().AutoMigrate(&orm.AccessToken{})
58 cs := NewStore(testDB)
60 tokenMap := make(map[string]*Token)
61 tokenMap["ab"] = mustCreateToken(ctx, t, cs, "ab", "test")
62 tokenMap["bc"] = mustCreateToken(ctx, t, cs, "bc", "test")
63 tokenMap["cd"] = mustCreateToken(ctx, t, cs, "cd", "test")
67 t.Errorf("List errored: get list error")
70 if len(got) != len(tokenMap) {
71 t.Error("List errored: get invalid length")
73 for _, v := range got {
74 if v.Token != tokenMap[v.ID].Token {
75 t.Errorf("List error: ID: %s, expected token: %s, DB token: %s", v.ID, *tokenMap[v.ID], v.Token)
81 func TestCheck(t *testing.T) {
82 ctx := context.Background()
83 testDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
89 testDB.Db().AutoMigrate(&orm.AccessToken{})
90 cs := NewStore(testDB)
92 token := mustCreateToken(ctx, t, cs, "x", "client")
93 tokenParts := strings.Split(token.Token, ":")
95 if err := cs.Check(tokenParts[0], tokenParts[1]); err != nil {
99 if err := cs.Check("x", "badsecret"); err != ErrInvalidToken {
100 t.Fatal("invalid token check passed")
104 func TestDelete(t *testing.T) {
105 ctx := context.Background()
106 testDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
112 testDB.Db().AutoMigrate(&orm.AccessToken{})
113 cs := NewStore(testDB)
116 mustCreateToken(ctx, t, cs, id, "client")
123 accessToken := orm.AccessToken{ID: id}
125 err = cs.DB.Db().Where(&accessToken).Find(&accessToken).Error
126 if err != gorm.ErrRecordNotFound {
131 t.Fatal("delete fail")
137 value := cs.DB.Get([]byte(id))
139 t.Fatal("delete fail")
144 func TestDeleteWithInvalidId(t *testing.T) {
145 testDB := dbm.NewSqlDB("sql", "sqlitedb", "temp")
151 testDB.Db().AutoMigrate(&orm.AccessToken{})
152 cs := NewStore(testDB)
154 err := cs.Delete("@")
155 if errors.Root(err) != ErrBadID {
156 t.Errorf("Deletion with invalid id success, while it should not")
160 func mustCreateToken(ctx context.Context, t *testing.T, cs *CredentialStore, id, typ string) *Token {
161 token, err := cs.Create(id, typ)