hub (unreleased): review fix 6 — the test-only helpers in production files refuse outside a test binary, and no production file may call one

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-11-15 17:32:09 +01:00
1 parent a6f4aa0b64
commit efea838203
7 files changed
+144

No files matched your search

@@ -0,0 +1,22 @@
# Review finding 6 — the test-only helpers in production files run in any binary. The test on the code BEFORE the guards:
--- FAIL: TestReview6_TheTestOnlyHelpersRefuseOutsideATestBinary (0.05s)
offsite_end_notice_test.go:256: SetEndNoticeForTest ran outside a test binary
offsite_end_notice_test.go:259: …and it wrote a row: map[vikunja:{App:vikunja Press: FirstNamed:2026-08-17 16:26:23 +0000 UTC ToldAt:2026-08-17 16:26:23 +0000 UTC ToldTo:operator Tries:0 LastTry:0001-01-01 00:00:00 +0000 UTC LastReason: StuckTold:0001-01-01 00:00:00 +0000 UTC}]
offsite_end_notice_test.go:262: BackdateNotificationLogForTest ran outside a test binary
FAIL
FAIL gitea.dooplex.hu/admin/felhom-hub/internal/store 0.052s
FAIL
--- PASS: TestReview6_NoProductionFileCallsATestOnlyHelper (0.13s)
ok gitea.dooplex.hu/admin/felhom-hub/internal/api 0.149s
# After the fix: the store test above is green; by mutation:
== MUTATION: a production function calls a test-only helper
RED on the mutant, GREEN on the real file
--- FAIL: TestReview6_NoProductionFileCallsATestOnlyHelper (0.13s)
test_seams_scan_test.go:41: ../../internal/notify/end_notice.go:85 calls a test-only helper from production code: d.SetSendFnForTest(nil)
== MUTATION: SetSendFnForTest replaces the sender in any binary
RED on the mutant, GREEN on the real file
--- FAIL: TestReview6_SetSendFnForTestDoesNothingOutsideATestBinary (0.05s)
end_notice_test.go:275: the sender was replaced outside a test binary (outcome sent, replaced=true, mails through the real one=0)
2 mutations, 0 not a red-proof
+8
View File
@@ -1,5 +1,13 @@
## Unreleased (after v0.182.0) ## Unreleased (after v0.182.0)
- **Review of the notice lock, finding 6 (2026-11-15 night): the test-only helpers in production files cannot be
used by the product.** `store.SetEndNoticeForTest` (it writes „told” with any date),
`store.BackdateNotificationLogForTest` and `notify.Dispatcher.SetSendFnForTest` must stay in production files —
other packages' tests call them, and a `_test.go` file is not visible across packages. Each now refuses outside a
test binary (`testing.Testing()`: the two store helpers return an error and write nothing; the sender is not
replaced and the hub says so in its log), and `TestReview6_NoProductionFileCallsATestOnlyHelper` reads every
non-test Go file of the hub and fails when one calls any `…ForTest(` helper. Tests `TestReview6_*` (3); the
store test seen red before the guards, 2 mutations red.
- **Review of the notice lock, finding 1 — the real hole (2026-11-15 night): „told” does not survive a change of the - **Review of the notice lock, finding 1 — the real hole (2026-11-15 night): „told” does not survive a change of the
household's notification address.** Somebody with the household's login could set the address to his own, press household's notification address.** Somebody with the household's login could set the address to his own, press
„delete backup data”, get the notice, and put the real address back: the row stayed told, the real address got „delete backup data”, get the notice, and put the real address back: the row stayed told, the real address got
+52
View File
@@ -0,0 +1,52 @@
package api
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
// Review finding 6: a helper named `…ForTest` is a way around the product's rules (SetEndNoticeForTest writes „told”
// with any date; SetSendFnForTest replaces the mail service). Some must live in production files because another
// package's tests call them. This test reads every non-test Go file of the hub and fails when one CALLS such a
// helper — a definition (`func (…) XForTest(`) is not a call.
func TestReview6_NoProductionFileCallsATestOnlyHelper(t *testing.T) {
root := filepath.Join("..", "..")
call := regexp.MustCompile(`\b[A-Za-z0-9_]+ForTest\(`)
def := regexp.MustCompile(`^func (\([^)]*\) )?[A-Za-z0-9_]+ForTest\(`)
files, defs := 0, 0
err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
return nil
}
b, rerr := os.ReadFile(p)
if rerr != nil {
return rerr
}
files++
for i, line := range strings.Split(string(b), "\n") {
if def.MatchString(line) {
defs++
continue
}
if tr := strings.TrimSpace(line); strings.HasPrefix(tr, "//") {
continue
}
if call.MatchString(line) {
t.Errorf("%s:%d calls a test-only helper from production code: %s", p, i+1, strings.TrimSpace(line))
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
if files < 100 || defs < 5 {
t.Fatalf("read %d files and found %d …ForTest definitions — the scan stopped reading the hub", files, defs)
}
}
+11
View File
@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings" "strings"
"testing"
"time" "time"
"gitea.dooplex.hu/admin/felhom-hub/internal/i18n" "gitea.dooplex.hu/admin/felhom-hub/internal/i18n"
@@ -164,6 +165,16 @@ func (d *Dispatcher) SendOperatorNow(customerID, eventType, severity, message, d
// SetSendFnForTest replaces the function that hands a mail to the mail service. TEST-ONLY: it lets a test in another // SetSendFnForTest replaces the function that hands a mail to the mail service. TEST-ONLY: it lets a test in another
// package (api.endNotices) see every mail and fail a send, with no call to the real service. // package (api.endNotices) see every mail and fail a send, with no call to the real service.
//
// It lives in a production file because api's tests need it. Outside a test binary it does NOTHING and says so in
// the log; no production file may call it (api.TestReview6_NoProductionFileCallsATestOnlyHelper).
func (d *Dispatcher) SetSendFnForTest(fn func(to, subject, body string, headers map[string]string) error) { func (d *Dispatcher) SetSendFnForTest(fn func(to, subject, body string, headers map[string]string) error) {
if !inTestBinary() {
d.logger.Printf("[ERROR] notify: SetSendFnForTest was called outside a test binary — ignored")
return
}
d.sendEmailFn = fn d.sendEmailFn = fn
} }
// inTestBinary says whether this process is a test binary (a variable so that a test can show the refusal).
var inTestBinary = testing.Testing
+13
View File
@@ -262,3 +262,16 @@ func TestNotice_SendOperatorNow(t *testing.T) {
t.Fatal("offsite_end_notice_stuck: two apps stuck in one hour must be two mails") t.Fatal("offsite_end_notice_stuck: two apps stuck in one hour must be two mails")
} }
} }
// Review finding 6: outside a test binary SetSendFnForTest replaces nothing.
func TestReview6_SetSendFnForTestDoesNothingOutsideATestBinary(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
old := inTestBinary
inTestBinary = func() bool { return false } // as in the production binary
replaced := false
d.SetSendFnForTest(func(string, string, string, map[string]string) error { replaced = true; return nil })
inTestBinary = old
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeSent || replaced || len(*mails) != 1 {
t.Fatalf("the sender was replaced outside a test binary (outcome %s, replaced=%v, mails through the real one=%d)", out, replaced, len(*mails))
}
}
+19
View File
@@ -8,6 +8,7 @@ import (
"sort" "sort"
"strings" "strings"
"sync" "sync"
"testing"
"time" "time"
) )
@@ -349,7 +350,14 @@ func (s *Store) MarkEndNoticeStuckTold(customerID, app, press string, now time.T
// SetEndNoticeForTest writes a row as if the hub had named the app at firstNamed and (toldAt non-zero) told `to` // SetEndNoticeForTest writes a row as if the hub had named the app at firstNamed and (toldAt non-zero) told `to`
// at toldAt. TEST-ONLY. // at toldAt. TEST-ONLY.
//
// It lives in a production file because other packages' tests need it (a _test.go file is not visible to them). It
// REFUSES TO RUN outside a test binary (errTestOnly), and no production file may call it
// (api.TestReview6_NoProductionFileCallsATestOnlyHelper).
func (s *Store) SetEndNoticeForTest(customerID, app, press string, firstNamed, toldAt time.Time, to string) error { func (s *Store) SetEndNoticeForTest(customerID, app, press string, firstNamed, toldAt time.Time, to string) error {
if !inTestBinary() {
return errTestOnly
}
var told sql.NullString var told sql.NullString
if !toldAt.IsZero() { if !toldAt.IsZero() {
told = sql.NullString{String: toldAt.UTC().Format(time.RFC3339), Valid: true} told = sql.NullString{String: toldAt.UTC().Format(time.RFC3339), Valid: true}
@@ -375,7 +383,11 @@ func (s *Store) SetEndNoticeForTest(customerID, app, press string, firstNamed, t
} }
// BackdateNotificationLogForTest moves a household's sent-log rows into the past. TEST-ONLY. // BackdateNotificationLogForTest moves a household's sent-log rows into the past. TEST-ONLY.
// Refuses to run outside a test binary, like SetEndNoticeForTest.
func (s *Store) BackdateNotificationLogForTest(customerID string, by time.Duration) error { func (s *Store) BackdateNotificationLogForTest(customerID string, by time.Duration) error {
if !inTestBinary() {
return errTestOnly
}
_, err := s.db.Exec(`UPDATE notification_log SET created_at = datetime(created_at, ?) WHERE customer_id = ?`, _, err := s.db.Exec(`UPDATE notification_log SET created_at = datetime(created_at, ?) WHERE customer_id = ?`,
fmt.Sprintf("-%d seconds", int(by.Seconds())), customerID) fmt.Sprintf("-%d seconds", int(by.Seconds())), customerID)
return err return err
@@ -421,3 +433,10 @@ func ValidNoticeApp(app string) bool {
} }
return true return true
} }
// inTestBinary says whether this process is a test binary. A variable so that a test can show what the test-only
// helpers do in the production binary.
var inTestBinary = testing.Testing
// errTestOnly: a test-only helper was called in a binary that is not a test.
var errTestOnly = fmt.Errorf("store: a test-only helper was called outside a test binary — refused")
@@ -243,3 +243,22 @@ func TestReview1_ToldCountsOnlyAtTheAddressOnRecord(t *testing.T) {
t.Fatalf("away and back through the save: the old „told” came back: %+v", n) t.Fatalf("away and back through the save: the old „told” came back: %+v", n)
} }
} }
// Review finding 6: the test-only helpers that live in production files (other packages' tests need them) refuse to
// run outside a test binary — SetEndNoticeForTest could write „told” with any date.
func TestReview6_TheTestOnlyHelpersRefuseOutsideATestBinary(t *testing.T) {
s := newTestStore(t)
old := inTestBinary
inTestBinary = func() bool { return false } // as in the production binary
defer func() { inTestBinary = old }()
long := time.Now().Add(-90 * 24 * time.Hour)
if err := s.SetEndNoticeForTest("c1", "vikunja", "", long, long, EndNoticeOperator); err == nil {
t.Error("SetEndNoticeForTest ran outside a test binary")
}
if ns, _ := s.EndNotices("c1"); len(ns) != 0 {
t.Errorf("…and it wrote a row: %+v", ns)
}
if err := s.BackdateNotificationLogForTest("c1", time.Hour); err == nil {
t.Error("BackdateNotificationLogForTest ran outside a test binary")
}
}