package api
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestSetTimingForACompletedRun(t *testing.T) {
r := CIRun{Started: "2026-11-01T10:00:00Z", FirstStepAt: "2026-11-01T10:05:00Z",
Completed: "2026-11-01T10:07:30Z"}
r.SetTiming(time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC))
if r.QueuedSeconds == nil || *r.QueuedSeconds != 300 {
t.Errorf("FAIL: queuedSeconds = %v, want 300", r.QueuedSeconds)
}
if r.RanSeconds == nil || *r.RanSeconds != 150 {
t.Errorf("FAIL: ranSeconds = %v, want 150, measured to completed not to now", r.RanSeconds)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestSetTimingForARunningRun(t *testing.T) {
r := CIRun{Started: "2026-11-01T10:00:00Z", FirstStepAt: "2026-11-01T10:05:00Z"}
r.SetTiming(time.Date(2026, 11, 1, 10, 6, 0, 0, time.UTC))
if r.QueuedSeconds == nil || *r.QueuedSeconds != 300 {
t.Errorf("FAIL: queuedSeconds = %v, want 300", r.QueuedSeconds)
}
if r.RanSeconds == nil || *r.RanSeconds != 60 {
t.Errorf("FAIL: ranSeconds = %v, want 60, measured to now", r.RanSeconds)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestSetTimingOmitsWhatIsUnknown(t *testing.T) {
r := CIRun{Started: "2026-11-01T10:00:00Z", Completed: "2026-11-01T10:07:30Z"}
r.SetTiming(time.Now())
b, _ := json.Marshal(r)
for _, k := range []string{"firstStepAt", "queuedSeconds", "ranSeconds"} {
if strings.Contains(string(b), `"`+k+`"`) {
t.Errorf("FAIL: %s present with no first step known: %s", k, b)
}
}
q := CIRun{Started: "2026-11-01T10:00:00Z", FirstStepAt: "2026-11-01T10:00:00Z"}
q.SetTiming(time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC))
b, _ = json.Marshal(q)
if !strings.Contains(string(b), `"queuedSeconds":0`) {
t.Errorf("FAIL: a zero wait must still be reported: %s", b)
}
// Clocks that disagree (the engine made the run a moment before
// quarry recorded it) give no wait, rather than a false zero.
n := CIRun{Started: "2026-11-01T10:00:05Z", FirstStepAt: "2026-11-01T10:00:00Z", Completed: "2026-11-01T10:05:00Z"}
n.SetTiming(time.Now())
if n.QueuedSeconds != nil {
t.Errorf("FAIL: a first step before the recorded start gives a wait of %d, want none", *n.QueuedSeconds)
}
if n.RanSeconds == nil || *n.RanSeconds != 300 {
t.Errorf("FAIL: ran = %v, want 300", n.RanSeconds)
}
e := CIRun{Started: "2026-11-01T10:00:00Z", FirstStepAt: "2026-11-01T10:05:00Z", Completed: "2026-11-01T10:04:00Z"}
e.SetTiming(time.Now())
if e.RanSeconds != nil {
t.Errorf("FAIL: a completion before the first step gives ran %d, want none", *e.RanSeconds)
}
if !t.Failed() {
t.Log("ok")
}
}