github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/accesstoken/accesstoken_test.go (about) 1 package accesstoken 2 3 import ( 4 "context" 5 "os" 6 "strings" 7 "testing" 8 9 dbm "github.com/bytom/bytom/database/leveldb" 10 "github.com/bytom/bytom/errors" 11 ) 12 13 func TestCreate(t *testing.T) { 14 testDB := dbm.NewDB("testdb", "leveldb", "temp") 15 defer os.RemoveAll("temp") 16 cs := NewStore(testDB) 17 18 cases := []struct { 19 id, typ string 20 want error 21 }{ 22 {"a", "client", nil}, 23 {"b", "network", nil}, 24 {"", "client", ErrBadID}, 25 {"bad:id", "client", ErrBadID}, 26 {"a", "network", ErrDuplicateID}, // this aborts the transaction, so no tests can follow 27 } 28 29 for _, c := range cases { 30 _, err := cs.Create(c.id, c.typ) 31 if errors.Root(err) != c.want { 32 t.Errorf("Create(%s, %s) error = %s want %s", c.id, c.typ, err, c.want) 33 } 34 } 35 } 36 37 func TestList(t *testing.T) { 38 ctx := context.Background() 39 testDB := dbm.NewDB("testdb", "leveldb", "temp") 40 defer os.RemoveAll("temp") 41 cs := NewStore(testDB) 42 43 tokenMap := make(map[string]*Token) 44 tokenMap["ab"] = mustCreateToken(ctx, t, cs, "ab", "test") 45 tokenMap["bc"] = mustCreateToken(ctx, t, cs, "bc", "test") 46 tokenMap["cd"] = mustCreateToken(ctx, t, cs, "cd", "test") 47 48 got, err := cs.List() 49 if err != nil { 50 t.Errorf("List errored: get list error") 51 } 52 53 if len(got) != len(tokenMap) { 54 t.Error("List errored: get invalid length") 55 } 56 for _, v := range got { 57 if v.Token != tokenMap[v.ID].Token { 58 t.Errorf("List error: ID: %s, expected token: %s, DB token: %s", v.ID, *tokenMap[v.ID], v.Token) 59 } 60 continue 61 } 62 } 63 64 func TestCheck(t *testing.T) { 65 ctx := context.Background() 66 testDB := dbm.NewDB("testdb", "leveldb", "temp") 67 defer os.RemoveAll("temp") 68 cs := NewStore(testDB) 69 70 token := mustCreateToken(ctx, t, cs, "x", "client") 71 tokenParts := strings.Split(token.Token, ":") 72 73 if err := cs.Check(tokenParts[0], tokenParts[1]); err != nil { 74 t.Fatal(err) 75 } 76 77 if err := cs.Check("x", "badsecret"); err != ErrInvalidToken { 78 t.Fatal("invalid token check passed") 79 } 80 } 81 82 func mustCreateToken(ctx context.Context, t *testing.T, cs *CredentialStore, id, typ string) *Token { 83 token, err := cs.Create(id, typ) 84 if err != nil { 85 t.Fatal(err) 86 } 87 return token 88 }