package web
import (
"container/list"
"net/http"
"runtime"
"strings"
"sync/atomic"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/ops"
)
func resetMeldCaches() {
for _, c := range []*meldLRU{melds, mergeViews} {
c.Lock()
c.order.Init()
c.byKey = map[string]*list.Element{}
c.bytes = 0
c.Unlock()
}
}
// allocated is the bytes one request to target allocates, with nothing
// else running.
func allocated(tb testing.TB, h http.Handler, target string, headers ...string) uint64 {
tb.Helper()
var a, b runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&a)
mpGet(tb, h, target, headers...)
runtime.ReadMemStats(&b)
return b.TotalAlloc - a.TotalAlloc
}
// A repeat request for a pair already drawn costs a small fraction of
// the first, whatever the pair's size: it reads the standing of the
// pair, not its files. Held as a ratio of bytes allocated, never a time.
func TestARepeatMergePageAllocatesAFractionOfTheFirst(t *testing.T) {
resetMeldCaches()
h := HandlerWith(mpRegistry(t, 20000, 300, false, nil), nil, nil, nil)
first := allocated(t, h, "/r/big/merge")
repeat := allocated(t, h, "/r/big/merge")
if repeat*5 > first {
t.Errorf("FAIL: a repeat request allocated %d bytes, the first %d: not under a fifth", repeat, first)
}
body := mpGet(t, h, "/r/big/merge")
if !strings.Contains(body, `data-hook="meld"`) || !strings.Contains(body, `data-hook="meld-rest"`) {
t.Error("FAIL: the repeat does not draw the conflict view and the files named below it")
}
if !t.Failed() {
t.Logf("ok: first %d B, repeat %d B", first, repeat)
}
}
// A tip that moves between two requests shows the new pair at once: the
// view is kept by tips, so the new tips are a view of their own.
func TestAMergePageShowsAMovedTipAtOnce(t *testing.T) {
resetMeldCaches()
var moved atomic.Bool
h := HandlerWith(mpRegistry(t, 15, 40, false, func() (string, string) {
if moved.Load() {
return "bnew0001", "tnew0001"
}
return "bold0001", "told0001"
}), nil, nil, nil, authOwner)
owner := []string{"Authorization", "Basic b3duZXI6cHc="}
before := mpGet(t, h, "/r/big/merge", owner...)
if !strings.Contains(before, `data-branch-tip="bold0001"`) || !strings.Contains(before, `data-target-tip="told0001"`) {
t.Fatalf("FAIL: the first request does not carry the first tips")
}
moved.Store(true)
after := mpGet(t, h, "/r/big/merge", owner...)
if !strings.Contains(after, `data-branch-tip="bnew0001"`) || !strings.Contains(after, `data-target-tip="tnew0001"`) ||
strings.Contains(after, "bold0001") {
t.Error("FAIL: after a tip moved the page still carries the old tips")
}
if !t.Failed() {
t.Log("ok")
}
}
// authOwner knows one account, owner, who may push; everyone else is
// anonymous and may read.
var authOwner = Verify(func(repo, user, pass string, need ops.Auth) api.Decision {
if need == ops.Anonymous || (user == "owner" && pass == "pw") {
return api.Allowed
}
return api.Denied
})
// Nothing a viewer may not do is served from a view drawn for another:
// an anonymous render then an owner's, and the reverse, each carry only
// their own controls.
func TestAMergeViewIsNotSharedBetweenViewers(t *testing.T) {
owner := []string{"Authorization", "Basic b3duZXI6cHc="}
controls := func(body string) (resolve, into bool) {
return strings.Contains(body, `data-hook="meld-commit"`), strings.Contains(body, `data-hook="merge-into"`)
}
for _, order := range [][]bool{{false, true}, {true, false}} {
resetMeldCaches()
h := HandlerWith(mpRegistry(t, 3, 40, false, nil), nil, nil, nil, authOwner)
for _, asOwner := range order {
var body string
if asOwner {
body = mpGet(t, h, "/r/big/merge", owner...)
} else {
body = mpGet(t, h, "/r/big/merge")
}
resolve, into := controls(body)
if asOwner != resolve || asOwner != into {
t.Errorf("FAIL: order %v, owner=%v: resolve controls %v, commit target %v", order, asOwner, resolve, into)
}
if !asOwner && strings.Contains(body, "data-draft=") {
t.Errorf("FAIL: order %v: an anonymous render carries a draft key", order)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// What the page counts and says cannot be answered is the same for a
// report that lists every file as for one that lists the first of them
// and counts the rest.
func TestABoundedReportDrawsAsTheWholeOneDid(t *testing.T) {
bounded := mpReport("feat", "trunk", 600, 30)
// The whole report lists all 600; the bounded one lists 250.
full := mpReport("feat", "trunk", 250, 30)
for i := 250; i < 600; i++ {
full.Files = append(full.Files, mpFile{Path: "d/f" + string(rune('a'+i%26)) + string(rune('a'+i/26%26)) + string(rune('a'+i/676)), Kind: "text", Omitted: "past the file limit"})
}
full.Total, full.Omitted = 0, 0
var a, b conflictsReport
remarshal(full, &a)
remarshal(bounded, &b)
va, vb := buildMeldUncached(a, "/r/x"), buildMeldUncached(b, "/r/x")
if va.Total != 600 || vb.Total != 600 {
t.Errorf("FAIL: file counts %d and %d, want 600", va.Total, vb.Total)
}
if len(va.Rest) != len(vb.Rest) || va.RestMore != vb.RestMore || va.Unresolvable == "" || va.Unresolvable != vb.Unresolvable {
t.Errorf("FAIL: the views differ: rest %d/%d more %d/%d unresolvable %q / %q",
len(va.Rest), len(vb.Rest), va.RestMore, vb.RestMore, va.Unresolvable, vb.Unresolvable)
}
if !t.Failed() {
t.Log("ok")
}
}
// A mirror merges nothing here, so a request that names no pair opens on
// the pickers and does not read or draw the newest branch's files; a pair
// named in the address is drawn as before, and so is the default pair
// on a repository that takes merges.
func TestAMirrorOpensOnThePickersUntilAPairIsNamed(t *testing.T) {
resetMeldCaches()
mirror := HandlerWith(mpRegistry(t, 15, 40, true, nil), nil, nil, nil)
mpConflictCalls.Store(0)
body := mpGet(t, mirror, "/r/lib/merge")
if n := mpConflictCalls.Load(); n != 0 {
t.Errorf("FAIL: the unnamed pair on a mirror asked merge.conflicts %d times", n)
}
for _, hook := range []string{`data-hook="merge-pick"`, `data-hook="merge-mirror"`, `name="branch"`, `name="onto"`} {
if !strings.Contains(body, hook) {
t.Errorf("FAIL: the pickers page lacks %s", hook)
}
}
if !strings.Contains(body, `href="/r/lib/merge?branch=feat-000&onto=trunk"`) || strings.Contains(body, `data-hook="meld"`) {
t.Error("FAIL: the newest branch is not one link away, or the page drew it")
}
named := mpGet(t, mirror, "/r/lib/merge?branch=feat-000&onto=trunk")
if !strings.Contains(named, `data-hook="meld"`) || strings.Contains(named, `data-hook="merge-pick"`) || mpConflictCalls.Load() == 0 {
t.Error("FAIL: a named pair on a mirror is not drawn")
}
open := HandlerWith(mpRegistry(t, 15, 40, false, nil), nil, nil, nil)
if body := mpGet(t, open, "/r/lib/merge"); !strings.Contains(body, `data-hook="meld"`) || strings.Contains(body, `data-hook="merge-pick"`) {
t.Error("FAIL: a repository that takes merges no longer opens on its newest branch's pair")
}
if !t.Failed() {
t.Log("ok")
}
}
// The same viewer twice in a row, in any order, gets the controls once:
// nothing a render adds to its view is left on what is kept.
func TestRepeatedRendersDoNotAccumulateControls(t *testing.T) {
owner := []string{"Authorization", "Basic b3duZXI6cHc="}
count := func(body string) (commit, into int) {
return strings.Count(body, `data-hook="meld-commit"`), strings.Count(body, `name="into"`)
}
resetMeldCaches()
h := HandlerWith(mpRegistry(t, 3, 40, false, nil), nil, nil, nil, authOwner)
var wantCommit, wantInto int
for i, asOwner := range []bool{true, true, false, false, true} {
var body string
if asOwner {
body = mpGet(t, h, "/r/big/merge", owner...)
} else {
body = mpGet(t, h, "/r/big/merge")
}
commit, into := count(body)
if asOwner && wantCommit == 0 {
wantCommit, wantInto = commit, into
if commit == 0 || into == 0 {
t.Fatalf("FAIL: the owner has no controls to count")
}
}
if asOwner && (commit != wantCommit || into != wantInto) {
t.Errorf("FAIL: render %d (owner): %d commit forms, %d targets, want %d and %d", i, commit, into, wantCommit, wantInto)
}
if !asOwner && (commit != 0 || into != 0) {
t.Errorf("FAIL: render %d (anonymous): %d commit forms, %d targets", i, commit, into)
}
}
if !t.Failed() {
t.Log("ok")
}
}