Files
sm-journal-plugin/translated_slug_test.go
Jakub Zych a598a7c5e7 fix: resolve translated post slugs (D-58)
GET /_journal/api/v1/posts/{slug} now looks the slug up in translate's
slug index for the request locale after the default-locale slug and
before the numeric id. TestTranslatedSlug covers the translated slug,
the default slug, the id and an unknown slug.
2026-10-26 22:46:49 +01:00

66 lines
1.9 KiB
Go

package journal_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"git.golem15.com/golem15/sm-journal-plugin/models"
translate "git.golem15.com/golem15/sm-translate-plugin/classes"
)
// TestTranslatedSlug (D-58): GET /_journal/api/v1/posts/{slug} resolves a
// post by its slug in the request locale, still by the default slug and by
// id, and answers 404 for an unknown slug.
func TestTranslatedSlug(t *testing.T) {
env := newPostsEnv(t)
ctx := context.Background()
past := time.Date(2026, 3, 4, 10, 0, 0, 0, time.UTC)
post := models.Post{Title: "Hello", Slug: "hello-d58", Content: "x", Published: true, PublishedAt: &past}
if err := env.gdb.Create(&post).Error; err != nil {
t.Fatal(err)
}
if err := translate.SetTranslated(ctx, env.gdb, &post, "slug", "pl", "witaj-d58"); err != nil {
t.Fatal(err)
}
get := func(slug, lang string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/_journal/api/v1/posts/"+slug, nil)
req.Host = "example.com"
req.RemoteAddr = "198.51.100.7:4000"
req.Header.Set("Accept-Language", lang)
rec := httptest.NewRecorder()
env.h.ServeHTTP(rec, req)
return rec
}
postID := func(rec *httptest.ResponseRecorder) uint {
t.Helper()
var body struct {
Data struct {
ID uint `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("body %s: %v", rec.Body.String(), err)
}
return body.Data.ID
}
for _, tc := range []struct{ slug, lang string }{
{"witaj-d58", "pl"},
{"hello-d58", "pl"},
{"hello-d58", "en"},
{id(post.ID), "en"},
} {
rec := get(tc.slug, tc.lang)
if rec.Code != http.StatusOK || postID(rec) != post.ID {
t.Fatalf("GET %s (%s) = %d %s", tc.slug, tc.lang, rec.Code, rec.Body.String())
}
}
if rec := get("nie-ma-takiego", "pl"); rec.Code != http.StatusNotFound {
t.Fatalf("unknown slug = %d %s", rec.Code, rec.Body.String())
}
}