package server import ( "context" "io" "net/http" "net/http/httptest" "strconv" "strings" "testing" "codeberg.org/maxwelljensen/weimar/internal/auth" "codeberg.org/maxwelljensen/weimar/internal/db" ) func TestHandleOGPreview_ServesAllRequiredTags(t *testing.T) { database, err := db.Open(":memory:") if err != nil { t.Fatalf("open db: %v", err) } t.Cleanup(func() { database.Close() }) if err := database.Migrate(context.Background()); err != nil { t.Fatalf("migrate: %v", err) } // Create a user and an image directly. auth.Register(context.Background(), database, "testuser", "password123", false) img, err := database.CreateImage(context.Background(), &db.Image{ Filename: "photo.jpg", StoragePath: "ab/cd/ef/abcdef.jpg", UploadedBy: 1, FileSize: 204800, Width: 1920, Height: 1080, MimeType: "image/jpeg", }) if err != nil { t.Fatalf("create image: %v", err) } // Construct a minimal Server with just the fields needed by handleOGPreview. s := &Server{ db: database, // spaH is only called on error (missing image); we never hit it in this test. spaH: func(w http.ResponseWriter, r *http.Request) {}, } idStr := strconv.FormatInt(img.ID, 10) req := httptest.NewRequest("GET", "/image/"+idStr, nil) req.SetPathValue("id", idStr) w := httptest.NewRecorder() s.handleOGPreview(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) resp.Body.Close() html := string(body) if resp.StatusCode != 200 { t.Fatalf("status = %d, want 200; body:\n%s", resp.StatusCode, html) } ct := resp.Header.Get("Content-Type") if !strings.HasPrefix(ct, "text/html") { t.Fatalf("Content-Type = %q, want text/html", ct) } // Verify all required OG tags are present by content. required := []string{ `og:title`, `og:description`, `og:url`, `og:image`, `og:image:secure_url`, `og:type`, `og:locale`, `twitter:card`, `twitter:image`, } for _, tag := range required { if !strings.Contains(html, tag) { t.Errorf("missing meta tag: %s", tag) } } // Verify specific values. if !strings.Contains(html, "photo.jpg") { t.Errorf("expected filename in OG title, got:\n%s", html) } if !strings.Contains(html, "testuser") { t.Errorf("expected uploader in description, got:\n%s", html) } if !strings.Contains(html, "1920") { t.Errorf("expected width in OG image:width, got:\n%s", html) } if strings.Contains(html, "&") || strings.Contains(html, "<") { t.Errorf("HTML appears double-escaped:\n%s", html) } // Should NOT contain the SPA title placeholder. if strings.Contains(html, "weimar") && !strings.Contains(html, "og:site_name") { t.Errorf("response appears to be SPA fallback, not OG page:\n%s", html) } }