* Make backend tests wait on conditions instead of durations The backend workflow has a long tail of runs that fail once and pass on a rerun. Every one of them comes down to a test assuming an operation finishes within some duration rather than waiting for the state it needs. Three were reproducible and each was reproduced against the old code before being changed: TestServerAuthHooks minted a token that lived one second and never tested expiry, so a slow runner turned the first POST into a 401; TestServerApp_AnonMode saw "connection refused" because waitForHTTPServerStart returned silently after three seconds and left a later assertion to fail with something unrelated; TestFsStore_Cleanup slept 200ms against a 300ms ttl that Cleanup widens to 400ms with its commit grace, so roughly 100ms of stall collected an image meant to survive. Fixed sleeps before asserting on asynchronous work are replaced with polls on the condition itself, using require.Eventually and require.EventuallyWithT, and require.Never where the assertion is that something did not happen. Polling closures assert on the CollectT they are handed rather than on t, since testify runs them on another goroutine, and polls that issue HTTP requests stay under the rate limit on the routes they poll through. Where a test needs time to have passed, the clock input is pinned instead: staging ages are stamped with os.Chtimes on both sides of the cleanup boundary right before each call, which also makes the 100ms commit grace an exact case rather than something no assertion reaches, and the RSS tests set store.Comment.Timestamp explicitly rather than racing the wall clock into the first 100ms of a second so pubDate matches. chooseUnusedPort takes a port from the kernel's ephemeral range. Picking at random out of a fixed 10000-port window let two package binaries, which go test ./... runs concurrently, land on the same number between the probe closing and the server binding. The start helpers fail naming the port they waited on, and the SSL tests wait on the redirect port as well as the TLS one. Arbitrary budgets that nothing tests are gone: ten HTTP clients with a one-second timeout against bolt-backed import and export, the "should take about 100msec" assertions, and a one-second bound on noticing an already cancelled context. Shutdown stays bounded at ten seconds so a hang is still caught. Two assertions get stronger. TestServerAuthHooks accepted 403 or 401 from a blocked user, an alternative that existed only because the short token could expire mid-test; it is deterministically 403 now. TestAdmin_BlockedList asserted two users blocked while one carried the same 150ms ttl the next step waits to lapse, so the halves raced each other. goleak stops reporting the regexp2 clock goroutine, which chroma pulls in for syntax highlighting and which lives for up to a second after the last match with a timeout; it ends on its own but a binary finishing inside that window was reported as leaking, and this suite now finishes sooner. The ignore for net/http.(*Server).Shutdown goes the other way: it no longer matches anything, with both packages run fifteen times each under CPU oversubscription to confirm. Two gaps the change would otherwise have opened are covered directly rather than left to the side effects that used to cover them. The one-second token was the only thing exercising the authenticator's ClaimsUpd hook on refresh, so TestServerApp_ClaimsUpd now calls the hook itself and checks admin, blocked, email and restricted-name impersonation, including the two pass-through cases. Lifting the open-route limit removed the last incidental exercise of the rate limiter, so TestRateLimiter drives a burst past the allowance and checks the refusals and that the limit is per client. Both run without a wall clock, and both were confirmed to fail when the behaviour they cover is removed. Production code is untouched. The two sleeps outside test code, the 429 backoff in cmd/cleanup.go and the submit poll in store/image/image.go, are left alone: no CI failure implicates them. Test sleeps drop from 67 to 21, all of them either inside a testing/synctest bubble or a poll interval. The suite runs in about 22 seconds instead of 46, mostly because TestPublic_FindCommentsCtrl_ConsistentCount no longer paces a hundred subtests with an 80ms sleep each to stay under the open route limit. The 300s per-package budget now matches across both workflows, the race_test target and the documented command, and CLAUDE.md records the convention. with '#' will be ignored, and an empty message aborts the commit. # # Date: Sat Aug 22 01:12:31 2026 +0100 # # interactive rebase in progress; onto7c312da1# Last command done (1 command done): # reword deb6cbf1 # Make backend tests wait on conditions instead of durations # Next command to do (1 remaining command): # reword 262e6dc2 # Apply go fix under Go 1.27 # You are currently editing a commit while rebasing branch 'fix/backend-test-flakiness' on '7c312da1'. # # Changes to be committed: .github/workflows/release.yml # modified: CLAUDE.md # modified: Makefile modified: backend/_example/memory_store/server/rpc_test.go # modified: backend/app/cmd/import_test.go # modified: backend/app/cmd/server_test.go # modified: backend/app/main_test.go # modified: backend/app/rest/api/admin_test.go # modified: backend/app/rest/api/middleware_test.go # modified: backend/app/rest/api/migrator_test.go # modified: backend/app/rest/api/rest_private_test.go # modified: backend/app/rest/api/rest_public_test.go # modified: backend/app/rest/api/rest_test.go # modified: backend/app/rest/api/rss_test.go # modified: backend/app/rest/proxy/image_test.go # modified: backend/app/store/image/fs_store_test.go # modified: backend/app/store/service/service_test.go # modified: docs/backlog/api-tests-deadlock-on-macos.md # * Apply go fix under Go 1.27 Go 1.27 extends go fix with the modernizers, so `go fix ./...` now rewrites patterns the language has since replaced. Running it across all three modules produces this: legacy sync/atomic calls on plain integers become the atomic types (notify.Service.closed, image.Service.term and submitCount, and several test counters), reverse index loops become slices.Backward, a Split-then-index becomes strings.Cut, counted loops become range over an int, and interface{} becomes any in the e2e suite. The example module needed no changes. The e2e module is behind a build tag, so it only matches with `go fix -tags e2e ./...`. One knock-on: prealloc can see the bound of a loop once it is written as range over an int, so the slice it feeds is now preallocated. with '#' will be ignored, and an empty message aborts the commit. # # Date: Sat Aug 22 01:32:09 2026 +0100 # # interactive rebase in progress; onto7c312da1# Last commands done (2 commands done): # reword deb6cbf1 262e6dc2 # Apply go fix under Go 1.27 # No commands remaining. # You are currently editing a commit while rebasing branch 'fix/backend-test-flakiness' on '7c312da1'. # # Changes to be committed: backend/app/migrator/native.go # modified: backend/app/notify/notify.go backend/app/rest/api/rest_private_test.go # modified: backend/app/store/comment.go # modified: backend/app/store/image/image.go # modified: backend/app/store/service/service_test.go # modified: backend/app/store/service/title_test.go # modified: e2e/e2e_test.go # modified: e2e/widgets_test.go #
174 lines
5.2 KiB
Go
174 lines
5.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"go.uber.org/goleak"
|
|
)
|
|
|
|
func Test_Main(t *testing.T) {
|
|
dir, err := os.MkdirTemp(os.TempDir(), "remark42")
|
|
require.NoError(t, err)
|
|
defer os.RemoveAll(dir)
|
|
|
|
port := chooseUnusedPort(t)
|
|
os.Args = []string{"test", "server", "--secret=123456", "--store.bolt.path=" + dir, "--backup=/tmp",
|
|
"--avatar.fs.path=" + dir, "--port=" + strconv.Itoa(port), "--url=https://demo.remark42.com", "--dbg", "--notify.type=none"}
|
|
|
|
done := make(chan struct{})
|
|
go func() {
|
|
<-done
|
|
e := syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
|
|
require.NoError(t, e)
|
|
}()
|
|
|
|
finished := make(chan struct{})
|
|
go func() {
|
|
main()
|
|
close(finished)
|
|
}()
|
|
|
|
// defer cleanup because require check below can fail
|
|
defer func() {
|
|
close(done)
|
|
<-finished
|
|
}()
|
|
|
|
waitForHTTPServerStart(t, port)
|
|
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/api/v1/ping", port))
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
body, err := io.ReadAll(resp.Body)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, "pong", string(body))
|
|
}
|
|
|
|
func TestMain_WithWebhook(t *testing.T) {
|
|
dir, err := os.MkdirTemp(os.TempDir(), "remark42")
|
|
require.NoError(t, err)
|
|
defer os.RemoveAll(dir)
|
|
|
|
var webhookSent atomic.Int32
|
|
ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
|
webhookSent.Store(1)
|
|
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
|
|
|
b, e := io.ReadAll(r.Body)
|
|
defer r.Body.Close()
|
|
|
|
assert.Nil(t, e)
|
|
assert.Equal(t, "Comment: env test", string(b))
|
|
}))
|
|
defer ts.Close()
|
|
|
|
port := chooseUnusedPort(t)
|
|
os.Args = []string{"test", "server", "--secret=123456", "--store.bolt.path=" + dir, "--backup=/tmp",
|
|
"--avatar.fs.path=" + dir, "--port=" + strconv.Itoa(port), "--url=https://demo.remark42.com", "--dbg",
|
|
"--admin-passwd=password", "--site=remark", "--notify.admins=webhook"}
|
|
|
|
err = os.Setenv("NOTIFY_WEBHOOK_URL", ts.URL)
|
|
assert.NoError(t, err)
|
|
err = os.Setenv("NOTIFY_WEBHOOK_TEMPLATE", "Comment: {{.Orig}}")
|
|
assert.NoError(t, err)
|
|
err = os.Setenv("NOTIFY_WEBHOOK_HEADERS", "Content-Type:application/json")
|
|
assert.NoError(t, err)
|
|
|
|
done := make(chan struct{})
|
|
go func() {
|
|
<-done
|
|
e := syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
|
|
require.NoError(t, e)
|
|
}()
|
|
|
|
finished := make(chan struct{})
|
|
go func() {
|
|
main()
|
|
close(finished)
|
|
}()
|
|
|
|
// defer cleanup because require check below can fail
|
|
defer func() {
|
|
close(done)
|
|
<-finished
|
|
}()
|
|
|
|
waitForHTTPServerStart(t, port)
|
|
|
|
resp, err := http.Post(fmt.Sprintf("http://admin:password@localhost:%d/api/v1/comment", port), "",
|
|
strings.NewReader(`{"text": "env test", "locator":{"url": "https://radio-t.com", "site": "remark"}}`))
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusCreated, resp.StatusCode)
|
|
|
|
// wait for webhook to be sent before shutting down
|
|
assert.Eventually(t, func() bool {
|
|
return webhookSent.Load() == int32(1)
|
|
}, 30*time.Second, 10*time.Millisecond, "webhook was not sent")
|
|
}
|
|
|
|
func TestGetDump(t *testing.T) {
|
|
dump := getDump()
|
|
assert.Contains(t, dump, "goroutine")
|
|
assert.Contains(t, dump, "[running]")
|
|
assert.Contains(t, dump, "backend/app/main.go")
|
|
t.Logf("\n dump: %s", dump)
|
|
}
|
|
|
|
// chooseUnusedPort asks the kernel for a free port from the ephemeral range, so concurrently
|
|
// running package test binaries never land on the same number
|
|
func chooseUnusedPort(t *testing.T) int {
|
|
t.Helper()
|
|
ln, err := net.Listen("tcp", ":0")
|
|
require.NoError(t, err, "no free port available")
|
|
port := ln.Addr().(*net.TCPAddr).Port
|
|
require.NoError(t, ln.Close())
|
|
return port
|
|
}
|
|
|
|
// waitForHTTPServerStart blocks until the server on port answers, failing the test naming the
|
|
// port if it never does
|
|
func waitForHTTPServerStart(t *testing.T, port int) {
|
|
t.Helper()
|
|
client := http.Client{Timeout: time.Second}
|
|
defer client.CloseIdleConnections()
|
|
require.Eventually(t, func() bool {
|
|
resp, err := client.Get(fmt.Sprintf("http://localhost:%d", port))
|
|
if err != nil {
|
|
return false
|
|
}
|
|
_ = resp.Body.Close()
|
|
return true
|
|
}, 30*time.Second, 10*time.Millisecond, "http server on port %d didn't start", port)
|
|
}
|
|
|
|
func TestMain(m *testing.M) {
|
|
// both ignores are for leaks which are detected locally
|
|
goleak.VerifyTestMain(
|
|
m,
|
|
// the shutdown goroutine in serverApp.run is not joined by Wait, and Rest.Shutdown gives
|
|
// httpServer.Shutdown a second, which can outlast goleak's retry budget on a loaded runner
|
|
goleak.IgnoreTopFunction("net/http.(*Server).Shutdown"),
|
|
goleak.IgnoreTopFunction("github.com/umputun/remark42/backend/app.init.0.func1"),
|
|
// this will be fixed in https://github.com/hashicorp/golang-lru/issues/159
|
|
goleak.IgnoreTopFunction("github.com/hashicorp/golang-lru/v2/expirable.NewLRU[...].func1"),
|
|
// regexp2, pulled in by chroma for syntax highlighting, keeps one shared clock goroutine
|
|
// alive for up to a second after the last match with a timeout, sleeping in 100ms ticks.
|
|
// it ends on its own, but a binary that finishes inside that window is reported as leaking
|
|
goleak.IgnoreAnyFunction("github.com/dlclark/regexp2/v2.runClock"),
|
|
)
|
|
}
|