110 lines
2.3 KiB
Go
110 lines
2.3 KiB
Go
package keys
|
|
|
|
import (
|
|
"clortho/lib/db"
|
|
"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)
|
|
}
|
|
|
|
func TestGetKeys(t *testing.T) {
|
|
// Create a test user
|
|
user := db.User{Username: "testuser"}
|
|
db.Connection.Create(&user)
|
|
|
|
// Create test keys
|
|
key1 := db.Key{UserID: user.ID, Content: "test-key-1"}
|
|
key2 := db.Key{UserID: user.ID, Content: "test-key-2"}
|
|
db.Connection.Create(&key1)
|
|
db.Connection.Create(&key2)
|
|
|
|
// Test GetKeys
|
|
keys := GetKeys()
|
|
if len(keys) != 2 {
|
|
t.Errorf("Expected 2 keys, got %d", len(keys))
|
|
}
|
|
|
|
// Test GetKeysByUser
|
|
userKeys := GetKeysByUser(user.ID)
|
|
if len(userKeys) != 2 {
|
|
t.Errorf("Expected 2 keys for user, got %d", len(userKeys))
|
|
}
|
|
|
|
// Test GetKey
|
|
key, err := GetKey(key1.ID)
|
|
if err != nil {
|
|
t.Errorf("Error getting key: %v", err)
|
|
}
|
|
if key.Content != "test-key-1" {
|
|
t.Errorf("Expected key content to be 'test-key-1', got '%s'", key.Content)
|
|
}
|
|
|
|
// Test CanAccessKey
|
|
canAccess, err := CanAccessKey(user.ID, key1.ID)
|
|
if err != nil {
|
|
t.Errorf("Error checking access: %v", err)
|
|
}
|
|
if !canAccess {
|
|
t.Errorf("Expected user to have access to their own key")
|
|
}
|
|
|
|
// Create admin user
|
|
admin := db.User{Username: "admin", Admin: true}
|
|
db.Connection.Create(&admin)
|
|
|
|
// Test admin access
|
|
canAccess, err = CanAccessKey(admin.ID, key1.ID)
|
|
if err != nil {
|
|
t.Errorf("Error checking access: %v", err)
|
|
}
|
|
if !canAccess {
|
|
t.Errorf("Expected admin to have access to any key")
|
|
}
|
|
|
|
// Test CreateKey
|
|
newKey, err := CreateKey(user.ID, "new-key")
|
|
if err != nil {
|
|
t.Errorf("Error creating key: %v", err)
|
|
}
|
|
if newKey.Content != "new-key" {
|
|
t.Errorf("Expected key content to be 'new-key', got '%s'", newKey.Content)
|
|
}
|
|
|
|
// Test UpdateKey
|
|
updatedKey, err := UpdateKey(newKey.ID, "updated-key")
|
|
if err != nil {
|
|
t.Errorf("Error updating key: %v", err)
|
|
}
|
|
if updatedKey.Content != "updated-key" {
|
|
t.Errorf("Expected key content to be 'updated-key', got '%s'", updatedKey.Content)
|
|
}
|
|
|
|
// Test DeleteKey
|
|
err = DeleteKey(newKey.ID)
|
|
if err != nil {
|
|
t.Errorf("Error deleting key: %v", err)
|
|
}
|
|
|
|
// Verify key was deleted
|
|
_, err = GetKey(newKey.ID)
|
|
if err == nil {
|
|
t.Errorf("Expected key to be deleted")
|
|
}
|
|
}
|