package service
import (
"bytes"
"context"
"testing"
)
// TestProposalDiffReturnsChangedDocuments proves ProposalDiff returns exactly
// the documents a proposal changes — a modified one with its base and proposed
// content, and an added one marked new — and not the documents it leaves alone.
func TestProposalDiffReturnsChangedDocuments(t *testing.T) {
svc, _ := newTestService(t)
ctx := context.Background()
sp, err := svc.CreateSpace(ctx, fxSpace)
if err != nil {
t.Fatalf("CreateSpace: %v", err)
}
// The approved head carries two documents; the proposal edits one, adds a
// third, and leaves the second untouched.
commitFiles(t, sp, sp.ApprovedBranch(), 1, map[string][]byte{
"specs/a.md": mdDoc("S-1", "A", "original body"),
"specs/keep.md": mdDoc("S-2", "Keep", "unchanged body"),
})
base, err := sp.Repo.ApprovedHead(ctx)
if err != nil {
t.Fatalf("ApprovedHead: %v", err)
}
res, err := svc.Propose(ctx, ProposeRequest{
Space: fxSpace,
Principal: agentPrincipal(),
Title: "edit and add",
IfMatch: base.String(),
Message: "two changes",
Writes: []DocumentWrite{
{Path: "specs/a.md", Content: mdDoc("S-1", "A", "revised body")},
{Path: "specs/new.md", Content: mdDoc("S-3", "New", "brand new body")},
},
})
if err != nil {
t.Fatalf("Propose: %v", err)
}
docs, err := svc.ProposalDiff(ctx, res.Proposal)
if err != nil {
t.Fatalf("ProposalDiff: %v", err)
}
byPath := make(map[string]ProposalDoc, len(docs))
for _, d := range docs {
byPath[d.Path] = d
}
if _, ok := byPath["specs/keep.md"]; ok {
t.Errorf("ProposalDiff returned the untouched specs/keep.md")
}
edited, ok := byPath["specs/a.md"]
if !ok {
t.Fatalf("ProposalDiff missing the edited document")
}
if edited.New {
t.Errorf("specs/a.md marked new, want an edit")
}
if !bytes.Contains(edited.Base, []byte("original body")) {
t.Errorf("edited doc base = %q, want the approved content", edited.Base)
}
if !bytes.Contains(edited.Proposed, []byte("revised body")) {
t.Errorf("edited doc proposed = %q, want the proposal content", edited.Proposed)
}
added, ok := byPath["specs/new.md"]
if !ok {
t.Fatalf("ProposalDiff missing the added document")
}
if !added.New || added.Base != nil {
t.Errorf("added doc = %+v, want New with a nil base", added)
}
}