server_import_sniff_test.go 1.4 KB

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