backup_integration_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package controller
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "git.aetherial.dev/aeth/keiji/pkg/storage"
  10. "github.com/gin-gonic/gin"
  11. _ "github.com/mattn/go-sqlite3"
  12. )
  13. // Run explicitly with KEIJI_BACKUP_DIR pointing to a backup containing the
  14. // migrated database and image store. The database is opened read-only.
  15. func TestMigratedBackup(t *testing.T) {
  16. dir := os.Getenv("KEIJI_BACKUP_DIR")
  17. if dir == "" {
  18. t.Skip("set KEIJI_BACKUP_DIR to test a migrated backup")
  19. }
  20. db, err := sql.Open("sqlite3", "file:"+filepath.Join(dir, "sqlite-media-types-category.db")+"?mode=ro&immutable=1")
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. defer db.Close()
  25. repo := storage.NewSQLiteRepo(db, storage.FilesystemImageIO{RootDir: filepath.Join(dir, "images")})
  26. images := repo.GetImagesByCategory(storage.DIGITAL_ART)
  27. if len(images) != 8 {
  28. t.Fatalf("got %d images, want 8", len(images))
  29. }
  30. gin.SetMode(gin.TestMode)
  31. r := gin.New()
  32. c := &Controller{database: repo}
  33. r.GET("/images/:file", c.ServeImage)
  34. counts := map[string]int{}
  35. for _, img := range images {
  36. counts[img.MediaType]++
  37. original, err := os.ReadFile(filepath.Join(dir, "images", string(img.Ident)))
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. req := httptest.NewRequest("GET", "/images/"+string(img.Ident), nil)
  42. rec := httptest.NewRecorder()
  43. r.ServeHTTP(rec, req)
  44. if rec.Code != 200 || rec.Header().Get("Content-Type") != img.MediaType || !bytes.Equal(rec.Body.Bytes(), original) {
  45. t.Fatalf("bad response for %s: status %d type %s", img.Ident, rec.Code, rec.Header().Get("Content-Type"))
  46. }
  47. if img.MediaType == "video/webm" {
  48. if detectMediaType(original) != "video/webm" {
  49. t.Fatal("webm detection failed")
  50. }
  51. req = httptest.NewRequest("GET", "/images/"+string(img.Ident), nil)
  52. req.Header.Set("Range", "bytes=0-15")
  53. rec = httptest.NewRecorder()
  54. r.ServeHTTP(rec, req)
  55. if rec.Code != 206 || !bytes.Equal(rec.Body.Bytes(), original[:16]) {
  56. t.Fatal("webm range request failed")
  57. }
  58. }
  59. }
  60. if counts["video/webm"] != 1 || counts["image/jpeg"] != 3 || counts["image/gif"] != 4 {
  61. t.Fatalf("unexpected types: %v", counts)
  62. }
  63. }