package repository import ( "os" "path/filepath" "strings" "testing" ) // TestMigrateLegacyDataFile 首次从历史命名(opsxloki.json)加载后必须升级到 lokistack.json: // 新文件出现且内容完整,旧文件改名留档(不删数据)。 func TestMigrateLegacyDataFile(t *testing.T) { dir := t.TempDir() legacy := filepath.Join(dir, "opsxloki.json") seed := `{"schemaVersion":10,"users":[{"id":1,"username":"admin"}],"clusters":[],"hosts":[],"storages":[],"deployments":[],"collectors":[],"logs":[],"settings":[],"logSources":[],"alertRules":[],"alertDeliveries":[],"notifyChannels":[],"logPolicyGroups":[],"auditLogs":[],"dailyVolumeSnapshots":[]}` if err := os.WriteFile(legacy, []byte(seed), 0o600); err != nil { t.Fatal(err) } d := &JsonDB{dataFile: legacy} d.loadFromDisk() d.migrateLegacyDataFile() // 新文件存在且包含原有数据 content, err := os.ReadFile(filepath.Join(dir, "lokistack.json")) if err != nil { t.Fatalf("未生成 lokistack.json: %v", err) } if !strings.Contains(string(content), `"admin"`) { t.Fatalf("迁移后数据不完整: %s", content[:min(len(content), 120)]) } // 旧文件迁移成功后直接删除(不留档) if _, err := os.Stat(legacy); !os.IsNotExist(err) { t.Fatalf("旧文件应被删除: %v", err) } // dataFile 已切到新路径 if filepath.Base(d.dataFile) != "lokistack.json" { t.Fatalf("dataFile 未切换: %s", d.dataFile) } } func min(a, b int) int { if a < b { return a } return b }