internal/pipeline/stage/parse_test.go

package stage

import (
	"context"
	"strings"
	"testing"

	"mercemay.top/src/tilstream/internal/pipeline"
)

func TestParseFrontmatter(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name      string
		raw       string
		wantKeys  []string
		wantBody  string
		wantError bool
	}{
		{
			name:     "basic",
			raw:      "---\ntitle: hi\ntags: [a,b]\n---\nbody text\n",
			wantKeys: []string{"title", "tags"},
			wantBody: "body text\n",
		},
		{
			name:     "no_front_matter",
			raw:      "just a body",
			wantKeys: nil,
			wantBody: "just a body",
		},
		{
			name:      "unterminated",
			raw:       "---\ntitle: hi\nno end here\n",
			wantError: true,
		},
	}
	for _, tc := range cases {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			st := &pipeline.State{Posts: []pipeline.Post{{Raw: []byte(tc.raw)}}}
			err := (&Parse{}).Run(context.Background(), st)
			if tc.wantError {
				if err == nil {
					t.Error("expected error")
				}
				return
			}
			if err != nil {
				t.Fatalf("Run: %v", err)
			}
			body := string(st.Posts[0].Raw)
			if !strings.HasPrefix(body, strings.TrimLeft(tc.wantBody, "")) {
				t.Errorf("body = %q, want prefix %q", body, tc.wantBody)
			}
			for _, k := range tc.wantKeys {
				if _, ok := st.Posts[0].Meta[k]; !ok {
					t.Errorf("missing key %q in meta", k)
				}
			}
		})
	}
}

func TestParseBytesHelper(t *testing.T) {
	t.Parallel()
	meta, body, err := ParseBytes([]byte("---\nslug: x\n---\nbody\n"))
	if err != nil {
		t.Fatalf("ParseBytes: %v", err)
	}
	if meta["slug"] != "x" || string(body) != "body\n" {
		t.Errorf("meta=%v body=%q", meta, body)
	}
}