Added GetAllUsersApplication and corresponding test

This commit is contained in:
dDogge 2024-03-14 16:25:54 +01:00
parent 0e1ea15cc9
commit 676d6637a2
2 changed files with 77 additions and 0 deletions

View file

@ -24,6 +24,7 @@ type Database interface {
AddUserToProject(username string, projectname string, role string) error
ChangeUserRole(username string, projectname string, role string) error
GetAllUsersProject(projectname string) ([]UserProjectMember, error)
GetAllUsersApplication() ([]string, error)
}
// This struct is a wrapper type that holds the database connection
@ -175,6 +176,36 @@ func (d *Db) GetAllUsersProject(projectname string) ([]UserProjectMember, error)
return users, nil
}
// GetAllUsersApplication retrieves all usernames from the database
func (d *Db) GetAllUsersApplication() ([]string, error) {
// Define the SQL query to fetch all usernames
query := `
SELECT username FROM users
`
// Execute the query
rows, err := d.Queryx(query)
if err != nil {
return nil, err
}
defer rows.Close()
// Iterate over the rows and populate the result slice
var usernames []string
for rows.Next() {
var username string
if err := rows.Scan(&username); err != nil {
return nil, err
}
usernames = append(usernames, username)
}
if err := rows.Err(); err != nil {
return nil, err
}
return usernames, nil
}
// Reads a directory of migration files and applies them to the database.
// This will eventually be used on an embedded directory
func (d *Db) Migrate(dirname string) error {

View file

@ -240,3 +240,49 @@ func TestGetAllUsersProject(t *testing.T) {
t.Error("User user not found")
}
}
func TestGetAllUsersApplication(t *testing.T) {
db, err := setupState()
if err != nil {
t.Error("setupState failed:", err)
}
err = db.AddUser("testuser1", "password")
if err != nil {
t.Error("AddUser failed:", err)
}
err = db.AddUser("testuser2", "password")
if err != nil {
t.Error("AddUser failed:", err)
}
users, err := db.GetAllUsersApplication()
if err != nil {
t.Error("GetAllUsersApplication failed:", err)
}
// Check if both users are returned
if len(users) != 2 {
t.Errorf("Expected 2 users, got %d", len(users))
}
// Check if the test users are included in the list
foundTestUser1 := false
foundTestUser2 := false
for _, user := range users {
if user == "testuser1" {
foundTestUser1 = true
}
if user == "testuser2" {
foundTestUser2 = true
}
}
if !foundTestUser1 {
t.Error("testuser1 not found")
}
if !foundTestUser2 {
t.Error("testuser2 not found")
}
}