package api
import (
"path/filepath"
"strings"
"testing"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/oltp"
)
// "Closes #N" CLOSES THE TICKET, AS IT DOES ON A PULL REQUEST.
//
// Anywhere in the landing's message, by the forge's number, and for a
// ticket that lives only on this forge. Before, only a hash in the first
// line was read, so "Closes #290" in a landing's body closed nothing
// (quarry#290 itself stayed open after it landed).
func TestClosesByNumberAnywhereInTheMessage(t *testing.T) {
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
local, err := db.LocalTicketNew("quarry", "dan", "", map[string]string{"title": "local work", "status": "Open"})
if err != nil {
t.Fatal(err)
}
synced := ticketAt(t, openTicket, "Open")
numbers := map[int]string{290: local, 291: openTicket}
look := func(_ string, n int) (string, bool) { id, ok := numbers[n]; return id, ok }
prev := ticketByNumber.Swap(&look)
t.Cleanup(func() { ticketByNumber.Store(prev) })
d := Deps{Local: db}
text := "Landing CI tests the merge\n\nA long body.\n\nCloses #290. Fixes #291, and mentions #292."
got := d.ticketsToClose("quarry", synced, text)
if len(got) != 2 || got[0].ID != local || got[0].Local == nil || got[1].ID != openTicket || got[1].Local != nil {
t.Fatalf("FAIL: picked %+v, want the local #290 then the synced #291", got)
}
if _, err := d.localTicketSet(as("dan", "cw"), ticketSetIn{Repo: "quarry", ID: local, Status: "Closed", Comment: "closed"}, *got[0].Local); err != nil {
t.Fatal(err)
}
if again := d.ticketsToClose("quarry", synced, text); len(again) != 1 || again[0].ID != openTicket {
t.Fatalf("FAIL: a closed local ticket was picked again: %+v", again)
}
t.Log("ok: #290 (local) and #291 (synced) close from the body; a closed one is left alone")
}
// The landing's own record carries the message the text is read from.
func TestLandingTextIsTitleAndMessage(t *testing.T) {
ix := openLandingIndex(t, "feat", strings.Repeat("c", 40))
got := landingText(ix, index.LandingSummary{ID: landingHash, Title: "land it"})
if !strings.HasPrefix(got, "land it\n") || !strings.Contains(got, "ready") {
t.Fatalf("FAIL: landing text = %q, want the title and the record's message", got)
}
t.Log("ok: title and message")
}