package main import ( "testing" "github.com/tidwall/buntdb" ) func TestStoreUserHandling(t *testing.T) { store, err := NewDBStore(":memory:") if err != nil { t.Fatalf("cannot create store: %v", err) } defer store.Close() t.Run("store should be empty initially", func(t *testing.T) { users, err := store.GetUsers() if err != nil { t.Errorf("no error should have been returned: %v", err) } if len(users) != 0 { t.Errorf("there should be no users") } }) t.Run("user that doesn't exist should return error", func(t *testing.T) { _, err := store.GetUser("someuser") if err != ErrUserNotFound { t.Errorf("unexpected error: %v", err) } }) t.Run("adding users should work", func(t *testing.T) { if err := store.AddUser(User{Username: "myuser", Password: "mypass", Role: GlobalRoleUser}); err != nil { t.Errorf("cannot add user: %v", err) } t.Run("retrieving that single user should work", func(t *testing.T) { user, err := store.GetUser("myuser") if err != nil { t.Errorf("cannot retrieve user: %v", err) } if user.Username != "myuser" { t.Errorf("retrieved user contains unexpected username") } if user.Role != GlobalRoleUser { t.Errorf("retrieved user contains unexpected role") } }) t.Run("retrieving multiple users should work", func(t *testing.T) { users, err := store.GetUsers() if err != nil { t.Errorf("cannot retrieve user list: %v", err) } if len(users) != 1 { t.Errorf("there should be only one user") } if users[0].Username != "myuser" { t.Errorf("retrieved user contains unexpected username") } if users[0].Role != GlobalRoleUser { t.Errorf("retrieved user contains unexpected role") } }) t.Run("deleting that user should work", func(t *testing.T) { err := store.RemoveUser("myuser") if err != nil { t.Errorf("cannot delete user: %v", err) } t.Run("user should no longer be found", func(t *testing.T) { _, err := store.GetUser("myuser") if err != ErrUserNotFound { t.Errorf("unexpected error: %v", err) } }) t.Run("user should no longer be listed", func(t *testing.T) { users, err := store.GetUsers() if err != nil { t.Errorf("unexpected error: %v", err) } if len(users) != 0 { t.Errorf("there should be no users") } }) }) }) t.Run("database should be empty now", func(t *testing.T) { // checks that we properly deleted all keys if err := store.db.View(func(tx *buntdb.Tx) error { return tx.Ascend("", func(key, value string) bool { t.Errorf("there should be no keys left") return false }) }); err != nil { t.Errorf("iterating keys failed: %v", err) } }) }