diff --git a/backend/maintenance/api_maint_test.go b/backend/maintenance/api_maint_test.go index 59f36d8..02c4b0c 100644 --- a/backend/maintenance/api_maint_test.go +++ b/backend/maintenance/api_maint_test.go @@ -139,55 +139,3 @@ func TestGetMDSkills(t *testing.T) { //assert.Equal(t, false, listOfCharacter.Public) } - -/* -func TestUpdateMDSkill(t *testing.T) { - database.SetupTestDB(false) - // Initialize a Gin router - r := gin.Default() - router.SetupGin(r) - - // Routes - protected := router.BaseRouterGrp(r) - character.RegisterRoutes(protected) - gsmaster.RegisterRoutes(protected) - protected.GET("/test", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"status": "Test OK"}) - }) - u := user.User{} - u.FirstId(1) - - // Define the test case input - sk := models.Skill{} - sk.Name = "Geländekunde" - sk.ID = 64 - jsonData, err := json.Marshal(sk) - if err != nil { - t.Fatalf("Failed to marshal skill: %v", err) - } - - // Create a test HTTP request - req, _ := http.NewRequest("PUT", "/api/maintenance/skills/64", bytes.NewBuffer(jsonData)) - req.Header.Set("Content-Type", "application/json") - token := user.GenerateToken(&u) - req.Header.Set("Authorization", "Bearer "+token) - - // Create a response recorder to capture the handler's response - respRecorder := httptest.NewRecorder() - - // Perform the test request - r.ServeHTTP(respRecorder, req) - - // Assert the response status code - assert.Equal(t, http.StatusCreated, respRecorder.Code) - - // Assert the response body - var createdCharacter models.Char - err = json.Unmarshal(respRecorder.Body.Bytes(), &createdCharacter) - assert.NoError(t, err) - assert.Equal(t, "Aragorn", createdCharacter.Name) - assert.Equal(t, "Human", createdCharacter.Rasse) - assert.Equal(t, 1, createdCharacter.ID) // Check the simulated ID -} - -*/ diff --git a/backend/maintenance/copy_db_test.go b/backend/maintenance/copy_db_test.go index 60a759f..011bcd7 100644 --- a/backend/maintenance/copy_db_test.go +++ b/backend/maintenance/copy_db_test.go @@ -1,6 +1,7 @@ package maintenance import ( + "bamort/database" "bamort/models" "bamort/user" "fmt" @@ -15,7 +16,7 @@ import ( ) // TestCopyLiveDatabaseToFile_Success tests the main functionality of copyLiveDatabaseToFile -func TestCopyLiveDatabaseToFile_Success(t *testing.T) { +func TestCopyDatabaseToFile_Success(t *testing.T) { // Setup tempDir := t.TempDir() targetFile := filepath.Join(tempDir, "test_backup.db") @@ -94,7 +95,7 @@ func TestCopyLiveDatabaseToFile_Success(t *testing.T) { } // TestCopyLiveDatabaseToFile_BackupExisting tests file backup functionality -func TestCopyLiveDatabaseToFile_BackupExisting(t *testing.T) { +func TestCopyDatabaseToFile_BackupExisting(t *testing.T) { // Setup tempDir := t.TempDir() targetFile := filepath.Join(tempDir, "test_backup.db") @@ -143,7 +144,7 @@ func TestCopyLiveDatabaseToFile_BackupExisting(t *testing.T) { } // TestCopyLiveDatabaseToFile_EmptyDatabase tests with empty database -func TestCopyLiveDatabaseToFile_EmptyDatabase(t *testing.T) { +func TestCopyDatabaseToFile_EmptyDatabase(t *testing.T) { // Setup tempDir := t.TempDir() targetFile := filepath.Join(tempDir, "empty_backup.db") @@ -184,6 +185,44 @@ func TestCopyLiveDatabaseToFile_EmptyDatabase(t *testing.T) { assert.Equal(t, int64(0), userCount, "User table should be empty") } +func TestCopyLiveDatabaseToFile(t *testing.T) { + // Setup + tempDir := t.TempDir() + targetFile := filepath.Join(tempDir, "empty_backup.db") + + // Create empty live database (only migrate structures, no data) + database.ConnectDatabase() + liveDB := database.DB + require.NotNil(t, liveDB, "Live database should be connected") + defer func() { + if sqlDB, err := liveDB.DB(); err == nil { + sqlDB.Close() + } + }() + + // Execute + err := CopyLiveDatabaseToFile(liveDB, targetFile) + + // Verify + require.NoError(t, err, "CopyLiveDatabaseToFile should succeed with empty database") + assert.FileExists(t, targetFile, "Target file should be created") + + // Verify target database has structures but no data + targetDB, err := gorm.Open(sqlite.Open(targetFile), &gorm.Config{}) + require.NoError(t, err, "Should be able to open target database") + defer func() { + if sqlDB, err := targetDB.DB(); err == nil { + sqlDB.Close() + } + }() + + // Check that tables exist but are empty + var userCount int64 + err = targetDB.Model(&user.User{}).Count(&userCount).Error + require.NoError(t, err, "Should be able to count users") + assert.Equal(t, int64(2), userCount, "User table should be empty") +} + // BenchmarkCopyLiveDatabaseToFile benchmarks the copy function performance func BenchmarkCopyLiveDatabaseToFile(b *testing.B) { // Setup test database once diff --git a/backend/maintenance/handlers.go b/backend/maintenance/handlers.go index a18a00a..ae38dec 100644 --- a/backend/maintenance/handlers.go +++ b/backend/maintenance/handlers.go @@ -13,6 +13,7 @@ import ( "github.com/gin-gonic/gin" "gorm.io/driver/sqlite" "gorm.io/gorm" + "gorm.io/gorm/clause" ) // Constants for test data management @@ -221,8 +222,11 @@ func copyTableData(sourceDB, targetDB *gorm.DB, model interface{}) error { break } - // Batch in SQLite einfügen - if err := targetDB.Model(model).Create(&records).Error; err != nil { + // Batch in SQLite einfügen mit Konflikt-Behandlung + // Verwende Clauses.OnConflict um bestehende Datensätze zu ersetzen + if err := targetDB.Model(model).Clauses(clause.OnConflict{ + UpdateAll: true, + }).Create(&records).Error; err != nil { return err } } diff --git a/backend/models/database.go b/backend/models/database.go index cd7f81e..776b0d5 100644 --- a/backend/models/database.go +++ b/backend/models/database.go @@ -35,6 +35,10 @@ func MigrateStructure(db ...*gorm.DB) error { if err != nil { return err } + err = learningMigrateStructure(targetDB) + if err != nil { + return err + } return nil } @@ -130,3 +134,30 @@ func skillsMigrateStructure(db ...*gorm.DB) error { } return nil } + +func learningMigrateStructure(db ...*gorm.DB) error { + // Use provided DB or default to database.DB + var targetDB *gorm.DB + if len(db) > 0 && db[0] != nil { + targetDB = db[0] + } else { + targetDB = database.DB + } + + err := targetDB.AutoMigrate( + &Source{}, + &CharacterClass{}, + &SkillCategory{}, + &SkillDifficulty{}, + &SpellSchool{}, + &ClassCategoryEPCost{}, + &ClassSpellSchoolEPCost{}, + &SpellLevelLECost{}, + &SkillCategoryDifficulty{}, + &SkillImprovementCost{}, + ) + if err != nil { + return err + } + return nil +}