server_pg_import_sniff_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package service
  2. import (
  3. "path/filepath"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. )
  7. func TestSniffPgImportKind(t *testing.T) {
  8. cases := []struct {
  9. name string
  10. header []byte
  11. want int
  12. }{
  13. {"pg custom archive", []byte("PGDMP\x01\x10\x04"), pgImportPgDump},
  14. {"raw sqlite database", []byte("SQLite format 3\x00rest of header"), pgImportSQLiteDB},
  15. {"sqlite cli dump without pragma", []byte("BEGIN TRANSACTION;\nCREATE TABLE t(i);"), pgImportSQLiteDump},
  16. {"bom and whitespace before pragma", []byte("\xef\xbb\xbf\r\n PRAGMA foreign_keys=OFF;"), pgImportSQLiteDump},
  17. {"plain-format postgres dump", []byte("--\n-- PostgreSQL database dump\n--"), pgImportUnknown},
  18. {"empty file", nil, pgImportUnknown},
  19. }
  20. for _, tc := range cases {
  21. t.Run(tc.name, func(t *testing.T) {
  22. if got := sniffPgImportKind(tc.header); got != tc.want {
  23. t.Errorf("sniffPgImportKind(%q) = %d, want %d", tc.header, got, tc.want)
  24. }
  25. })
  26. }
  27. t.Run("panel migration dump", func(t *testing.T) {
  28. dbPath := filepath.Join(t.TempDir(), "x-ui.db")
  29. if err := database.InitDB(dbPath); err != nil {
  30. t.Fatalf("InitDB: %v", err)
  31. }
  32. t.Cleanup(func() { _ = database.CloseDB() })
  33. dump, err := database.DumpSQLiteToBytes(dbPath)
  34. if err != nil {
  35. t.Fatalf("DumpSQLiteToBytes: %v", err)
  36. }
  37. if got := sniffPgImportKind(dump[:64]); got != pgImportSQLiteDump {
  38. t.Errorf("sniffPgImportKind(real migration dump) = %d, want %d", got, pgImportSQLiteDump)
  39. }
  40. })
  41. }