255 lines
8.3 KiB
Go
255 lines
8.3 KiB
Go
package tide_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/tide"
|
|
)
|
|
|
|
// backend stands in for one implementation of GET /api/blog/posts.
|
|
func backend(body string) *httptest.Server {
|
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
fmt.Fprint(w, body)
|
|
}))
|
|
}
|
|
|
|
func ExampleReplayFlow() {
|
|
ctx := context.Background()
|
|
// The reference (PHP) backend and two Go ports. IDs and *_at timestamps
|
|
// legitimately differ; the second port changed a title.
|
|
reference := backend(`{"data":[{"id":12,"title":"Hello","created_at":"2026-09-30T10:00:00+00:00"}]}`)
|
|
defer reference.Close()
|
|
port := backend(`{"data":[{"id":3,"title":"Hello","created_at":"2026-10-01T08:30:00+00:00"}]}`)
|
|
defer port.Close()
|
|
broken := backend(`{"data":[{"id":3,"title":"hello","created_at":"2026-10-01T08:30:00+00:00"}]}`)
|
|
defer broken.Close()
|
|
|
|
raw, err := os.ReadFile("testdata/docs/posts-spec.yaml")
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
spec, err := tide.ParseFlow(raw)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
// Record the reference once; the flow is what testdata/parity keeps.
|
|
flow, err := tide.RecordFlow(ctx, spec, tide.RecordConfig{Target: reference.URL})
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
for _, target := range []string{port.URL, broken.URL} {
|
|
res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{Target: target})
|
|
var mismatch *tide.MismatchError
|
|
if errors.As(err, &mismatch) {
|
|
res = mismatch.Result // a difference is an error carrying the result
|
|
} else if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
fmt.Println("ok:", res.OK)
|
|
for _, step := range res.Steps {
|
|
for _, d := range step.Diffs {
|
|
fmt.Printf(" %s %s: want %s, got %s\n", step.ID, d.Path, d.Expected, d.Actual)
|
|
}
|
|
}
|
|
}
|
|
// Output:
|
|
// ok: true
|
|
// ok: false
|
|
// list-posts $.data[0].title: want "Hello", got "hello"
|
|
}
|
|
|
|
// parity records the flow spec kept in dir against the reference backend
|
|
// once, saves the recorded flow next to it, then replays it against the
|
|
// port and prints every difference to w.
|
|
func parity(ctx context.Context, dir, reference, port string, w io.Writer) error {
|
|
spec, err := tide.LoadFlow(filepath.Join(dir, "posts.spec.yaml"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
flow, err := tide.RecordFlow(ctx, spec, tide.RecordConfig{Target: reference})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := tide.SaveFlow(filepath.Join(dir, "posts.yaml"), flow); err != nil {
|
|
return err
|
|
}
|
|
|
|
res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{
|
|
Target: port,
|
|
BaseDir: dir,
|
|
})
|
|
var mismatch *tide.MismatchError
|
|
if errors.As(err, &mismatch) {
|
|
res = mismatch.Result // a difference is an error carrying the result
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
for _, step := range res.Steps {
|
|
for _, d := range step.Diffs {
|
|
fmt.Fprintf(w, "%s %s: want %s, got %s\n", step.ID, d.Path, d.Expected, d.Actual)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// TestDocsParity runs parity on a spec written to a temporary directory,
|
|
// against two httptest backends whose titles differ.
|
|
func TestDocsParity(t *testing.T) {
|
|
spec, err := os.ReadFile("testdata/docs/posts-spec.yaml")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "posts.spec.yaml"), spec, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reference := backend(`{"data":[{"id":12,"title":"Hello","created_at":"2026-09-30T10:00:00+00:00"}]}`)
|
|
defer reference.Close()
|
|
port := backend(`{"data":[{"id":3,"title":"hello","created_at":"2026-10-01T08:30:00+00:00"}]}`)
|
|
defer port.Close()
|
|
|
|
var out bytes.Buffer
|
|
if err := parity(t.Context(), dir, reference.URL, port.URL, &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if want := "list-posts $.data[0].title: want \"Hello\", got \"hello\"\n"; out.String() != want {
|
|
t.Fatalf("diffs = %q, want %q", out.String(), want)
|
|
}
|
|
if _, err := tide.LoadFlow(filepath.Join(dir, "posts.yaml")); err != nil {
|
|
t.Fatalf("recorded flow: %v", err)
|
|
}
|
|
}
|
|
|
|
// broadcasts records the publications the reference backend sends for the
|
|
// delete step of spec, writes them as a golden in dir, and compares the
|
|
// publications a new backend sent to rec with it, printing the differences
|
|
// to w. listen is the recorder address the reference backend publishes to.
|
|
func broadcasts(ctx context.Context, spec tide.Flow, reference, listen string, store *tide.Store, dir string,
|
|
rec *tide.CentrifugoRecorder, idsOfTheNewBackend *tide.Store, w io.Writer) error {
|
|
// docs:start broadcasts
|
|
golden, err := tide.RecordBroadcasts(ctx, spec, tide.BroadcastConfig{
|
|
Target: reference, // a loopback URL such as http://127.0.0.1:8000
|
|
Listen: listen, // empty: tide.DefaultCentrifugoListen
|
|
APIKey: "test-only-key",
|
|
Store: store,
|
|
Step: "delete",
|
|
IDs: []string{"id:room", "id:item"},
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := tide.WriteBroadcastGolden(filepath.Join(dir, "deleted.yaml"), golden); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Later, with the new backend publishing to rec (a tide.CentrifugoRecorder):
|
|
norm, err := tide.NormalizePublications(rec.Publications(), idsOfTheNewBackend)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, d := range tide.DiffPublications(golden.Publications, norm) {
|
|
fmt.Fprintf(w, "%s: want %s, got %s\n", d.Path, d.Expected, d.Actual)
|
|
}
|
|
// docs:end broadcasts
|
|
return nil
|
|
}
|
|
|
|
// itemsBackend is a backend whose create and delete endpoints publish to
|
|
// the Centrifugo API at centrifugo, using the given ids and delete event.
|
|
func itemsBackend(centrifugo, room, item, deleted string) *httptest.Server {
|
|
publish := func(body string) {
|
|
req, _ := http.NewRequest(http.MethodPost, centrifugo+"/api/publish", strings.NewReader(body))
|
|
req.Header.Set("Authorization", "apikey test-only-key")
|
|
if resp, err := http.DefaultClient.Do(req); err == nil {
|
|
_ = resp.Body.Close()
|
|
}
|
|
}
|
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
event := "created"
|
|
if r.Method == http.MethodDelete {
|
|
event = deleted
|
|
}
|
|
publish(`{"channel":"room:` + room + `","data":{"event":"` + event + `","payload":{"id":` + item + `},"timestamp":"2026-09-30T10:00:00+00:00"}}`)
|
|
if r.Method == http.MethodPost {
|
|
fmt.Fprint(w, `{"data":{"id":`+item+`}}`)
|
|
return
|
|
}
|
|
fmt.Fprint(w, `{"message":"deleted"}`)
|
|
}))
|
|
}
|
|
|
|
// TestDocsBroadcasts records a golden from one backend and compares the
|
|
// publications of a second one, which renamed the delete event, with it.
|
|
func TestDocsBroadcasts(t *testing.T) {
|
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
listen := ln.Addr().String()
|
|
_ = ln.Close()
|
|
reference := itemsBackend("http://"+listen, "5", "77", "deleted")
|
|
defer reference.Close()
|
|
|
|
store, err := tide.OpenStore("")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
store.Set("id:room", "5")
|
|
spec := tide.Flow{Version: tide.CurrentVersion, Name: "items", Steps: []tide.Step{
|
|
{ID: "create", Request: tide.Request{Method: "POST", Path: "/items"},
|
|
Capture: []tide.CaptureRule{{From: "response.json", Path: "$.data.id", As: "id:item"}}},
|
|
{ID: "delete", Request: tide.Request{Method: "DELETE", Path: "/items/{{id:item}}"}},
|
|
}}
|
|
|
|
// The new backend publishes to rec with its own ids.
|
|
rec := tide.NewCentrifugoRecorder(tide.CentrifugoRecorderOptions{APIKey: "test-only-key"})
|
|
centrifugo := httptest.NewServer(rec)
|
|
defer centrifugo.Close()
|
|
port := itemsBackend(centrifugo.URL, "9", "31", "removed")
|
|
defer port.Close()
|
|
req, _ := http.NewRequest(http.MethodDelete, port.URL+"/items/31", nil)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_ = resp.Body.Close()
|
|
ids, err := tide.OpenStore("")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ids.Set("id:room", "9")
|
|
ids.Set("id:item", "31")
|
|
|
|
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
|
defer cancel()
|
|
dir := t.TempDir()
|
|
var out bytes.Buffer
|
|
if err := broadcasts(ctx, spec, reference.URL, listen, store, dir, rec, ids, &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if want := `$[0].body.data.event: want "deleted", got "removed"` + "\n"; out.String() != want {
|
|
t.Fatalf("diffs = %q, want %q", out.String(), want)
|
|
}
|
|
if _, err := tide.LoadBroadcastGolden(filepath.Join(dir, "deleted.yaml")); err != nil {
|
|
t.Fatalf("golden: %v", err)
|
|
}
|
|
}
|