88 lines
2.0 KiB
Go
88 lines
2.0 KiB
Go
package users
|
|
|
|
import (
|
|
"clortho/lib/db"
|
|
"clortho/lib/utils"
|
|
"fmt"
|
|
"os"
|
|
"testing"
|
|
)
|
|
|
|
func TestMain(m *testing.M) {
|
|
// Global setup
|
|
fmt.Println("Setting up resources...")
|
|
|
|
db.InitDb()
|
|
|
|
exitCode := m.Run() // Run all tests
|
|
|
|
// Global teardown
|
|
fmt.Println("Cleaning up resources...")
|
|
|
|
db.ResetDb()
|
|
|
|
os.Exit(exitCode)
|
|
}
|
|
|
|
// TestHashPassword tests the password hashing and verification.
|
|
func TestHashPassword(t *testing.T) {
|
|
originalPassword := "securepassword123"
|
|
|
|
// Hash the password
|
|
hashedPassword, err := HashPassword(originalPassword)
|
|
if err != nil {
|
|
t.Fatalf("Failed to hash password: %v", err)
|
|
}
|
|
|
|
// Ensure the hash is not the same as the original password
|
|
if hashedPassword == originalPassword {
|
|
t.Fatal("Hashed password should not match the original password")
|
|
}
|
|
|
|
// Check if the password matches the hash
|
|
if !CheckPasswordHash(originalPassword, hashedPassword) {
|
|
t.Fatal("Password does not match the hash")
|
|
}
|
|
|
|
// Ensure incorrect password does not match the hash
|
|
wrongPassword := "wrongpassword"
|
|
if CheckPasswordHash(wrongPassword, hashedPassword) {
|
|
t.Fatal("Wrong password should not match the hash")
|
|
}
|
|
}
|
|
|
|
func TestGetUser(t *testing.T) {
|
|
user1 := db.User{Username: "someUser", DisplayName: utils.Ptr("Some User")}
|
|
user2 := db.User{Username: "someOtherUser", DisplayName: utils.Ptr("Some Other User")}
|
|
db.Connection.Create(&user1)
|
|
db.Connection.Create(&user2)
|
|
|
|
foundUser := GetUser("someUser")
|
|
if foundUser == nil || foundUser.Username != "someUser" {
|
|
t.Fatal("Did not return the right user.")
|
|
}
|
|
}
|
|
|
|
func TestInitAdminUser(t *testing.T) {
|
|
pass, err := InitAdminUser()
|
|
if err != nil {
|
|
t.Fatal("Should not produce an error when first called.", err)
|
|
}
|
|
|
|
if pass == nil || len(*pass) != 32 {
|
|
t.Fatal("Should return a password 32 chars long.", pass)
|
|
}
|
|
|
|
user := GetUser("admin")
|
|
if user == nil {
|
|
t.Fatal("Unable to find user with username 'admin'.")
|
|
}
|
|
|
|
//fmt.Printf("USER: %+v\n", user)
|
|
//fmt.Printf("PASS: %+v\n", pass)
|
|
isValid := CheckPasswordHash(*pass, *user.PasswordHash)
|
|
if !isValid {
|
|
t.Fatal("Password hash not valid.")
|
|
}
|
|
}
|