beads/internal/storage/uow/notifying_parity_test.go
Julian Knutsen eaed71fbba
fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b) (#7554)
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)

`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.

- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
  Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
  row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
  printed), move it with ONE Lifecycle.Update whose patch is Persistence =
  persistent (the role's atomic plane move: same id, labels, deps, events and
  comments carried), then write the promotion comment (a comment failure is
  reported, the promotion stands). A no-op move is a lost race and reports
  NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
  connected http workspace and a local one take the same entry. The history
  label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
  anything else a 400 naming patch.persistence) on PATCH
  /v0/beads/issues/{id}, behind the new additive behavior token
  issues.update.persistence. wire_revision unchanged. Spec, apigen and the
  wire-shape golden regenerated; the handler only decodes and passes it to
  the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
  advertising the token, and otherwise refuses BEFORE the dial with
  *wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
  Capability set). The batchApply item still refuses it
  (W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
  uow and the served http leg; the served
  PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
  (label kept, comment written, one PATCH, re-promote refused), and under
  the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
  profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)

The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.

What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
  counter moves with the row: a promoted parent's next
  `bd create --parent` mints .3 after .1/.2 instead of failing with
  "issue already exists";
- on_update fires twice, for the move and for the comment, as on the
  direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
  "bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
  a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
  template guard applies, and a lost race reads "<id> is not a wisp
  (already persistent)".

The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.

CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.

Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
  children, a dependency and a comment under a counting on_update hook:
  the hook fires twice, the dependency and the children's parent edge
  survive, `bd comments` lists the old comment and the promotion reason,
  and the next child is .3. At the pre-PR base it fails (the hook fired
  0 times).
- The proxied journey pins the two commits, and new subtests pin the
  child counter (the child_counters row, next child .3) and the two hook
  firings. Against the contributor head each fails: one commit, no
  counter row and a failing create, one firing.

Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
  shard manifest (shard 64 of 100, from the generator's incremental
  --write). Without it //scripts:go_test_sources_test fails both the
  NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
  The direct route now writes that comment through st.Commenter(),
  which HookFiringStore wraps, so an embedded promote fires on_update
  for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
  list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
  bodies: the update body publishes it behind issues.update.persistence,
  and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
  conformance fixture's PromoteWisp no longer claims to do what
  `bd promote` does, the CLI differential's promote scenario names
  issueops.Promote, and export_source's wisp-relations note names
  issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
  reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
  members, so a Promote that also set Description passed it.

Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
  emitted request_error, though the caller could fix the request. The
  role now returns two refusals as ErrValidation, so bd serve answers
  400 invalid_argument and the client maps that back to ErrValidation:
  an unversioned row asked for ephemeral or no_history (the role wraps
  types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
  returns for that case alone, with its message unchanged), and a
  demotion of a row with retained snapshots. A row that breaks its own
  persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
  every leg (dolt, embedded dolt, the unit of work, served http): both
  wisp modes match ErrValidation and leave the row durable, unversioned
  and off the wisp plane. Without the wrap the dolt leg fails, and the
  served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
  the first test of the snapshot refusal, and fails without its wrap.
  The unversioned unit test now requires both sentinels. The types tests
  pin the sentinel, its unchanged message, and that no row-invariant
  error matches it: checking the unversioned class ahead of the
  invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
  fifth being the lost-race refusal sentence, and says the two refusals
  now answer 400 over bd serve and gain a `validation failed: ` prefix
  locally.
- NotAWispError's doc comment records that a no-history wisp is refused
  too: the gate reads the Ephemeral flag, as bd promote always has, and
  `bd update --persistent` is the move for that row.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 05:51:53 +00:00

474 lines
20 KiB
Go

package uow
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"reflect"
"runtime"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage/domain"
)
// The structural parity guard.
//
// The first attempt at unit-of-work hooks overrode a HAND-PICKED list of use
// case methods, which is a coverage claim that decays silently: the list is
// right the day it is written and wrong the first time someone adds a verb.
// This file replaces the claim with a PARTITION. Every method of every surface
// the notifying wrapper stands in front of is either recorded or listed below
// with the reason it records nothing, and the tests fail on anything that is
// neither, on anything that is both, and on an exemption that no longer names a
// real method.
//
// Adding a mutating verb to a use case therefore breaks this test until someone
// decides what hook it fires. That decision is the point.
//
// WHY REFLECTION AND A WRITTEN PARTITION rather than deriving "is this a
// mutator?" from the SQL each method reaches (the shape a journal completeness
// guard uses): the derivation needs a call graph, and a name-resolved one over
// domain + domain/db + issueops collapses — every repository body calls
// rows.Close(), which resolves to IssueSQLRepository.Close, so every read looks
// like a mutation. Dropping issueops from the scan loses the closes instead,
// which is the half that matters most here. A partition needs no classifier and
// cannot drift: the compiler supplies the method set, and reflection tells a
// DECLARED override from one promoted by the embedded interface.
// declaredOn reports whether typ declares name itself rather than inheriting it
// from an embedded field. The compiler reports a promoted method's
// implementation as living in "<autogenerated>" — the same discriminator
// internal/storage/role_accessor_decorator_test.go uses, and the only way to
// tell "wrapped" from "passed straight through" on a type that embeds the
// surface it decorates.
func declaredOn(typ reflect.Type, name string) (declared, exists bool) {
method, ok := typ.MethodByName(name)
if !ok {
return false, false
}
file, _ := runtime.FuncForPC(method.Func.Pointer()).FileLine(method.Func.Pointer())
return !strings.Contains(file, "<autogenerated>"), true
}
// assertPartition is the shared body of every guard below: recorded and
// exempted must together cover surface exactly, with no overlap and no
// exemption for a method that no longer exists.
func assertPartition(t *testing.T, what string, surface []string, recorder reflect.Type, exempt map[string]string) {
t.Helper()
present := make(map[string]bool, len(surface))
for _, name := range surface {
present[name] = true
declared, exists := declaredOn(recorder, name)
reason, exempted := exempt[name]
switch {
case exempted && declared:
t.Errorf("%s.%s is both recorded and exempted (%q) — delete the exemption", what, name, reason)
case exempted && strings.TrimSpace(reason) == "":
t.Errorf("%s.%s is exempted with no reason", what, name)
case exempted:
case declared:
case !exists:
t.Errorf("%s.%s is not answered by %s at all: a caller asks for it with a type assertion, "+
"which simply stops matching, so the wrapper loses the capability along with its hooks. "+
"Declare it, or exempt it in this file with the reason it offers nothing", what, name, recorder)
default:
t.Errorf("%s.%s is inherited from the embedded surface, so it records nothing: add an "+
"override that buffers the hook the DoltStorage chain fires for it "+
"(internal/storage/hook_decorator.go), or exempt it in this file with the reason it fires none",
what, name)
}
}
for name := range exempt {
if !present[name] {
t.Errorf("%s.%s is exempted but no longer exists — delete the exemption", what, name)
}
}
}
func interfaceMethods(iface reflect.Type) []string {
names := make([]string, 0, iface.NumMethod())
for i := 0; i < iface.NumMethod(); i++ {
names = append(names, iface.Method(i).Name)
}
sort.Strings(names)
return names
}
// ── The unit of work's use cases ────────────────────────────────────
// TestNotifyingUOWWrapsEveryMutatingUseCase pins which use cases the notifying
// unit of work stands in front of. A use case added to the UnitOfWork interface
// lands here first, before any of its methods can be forgotten.
func TestNotifyingUOWWrapsEveryMutatingUseCase(t *testing.T) {
assertPartition(t, "UnitOfWork", interfaceMethods(reflect.TypeOf((*UnitOfWork)(nil)).Elem()),
reflect.TypeOf((*notifyingUOW)(nil)), map[string]string{
"SwitchDatabase": "DDL against the connection, not a write to any bead",
"ConfigUseCase": "workspace settings and metadata, not beads: the DoltStorage chain's " +
"WorkspaceConfig role passes through undecorated for the same reason (hook_workspace_config.go)",
"DoltRemoteUseCase": "Dolt remotes are repository plumbing; no bead changes and no event to name",
"RawSQLUseCase": "the raw escape hatch executes statements this layer cannot read, so it " +
"cannot say which bead changed; the DoltStorage chain fires nothing for raw access either",
"EventsJournalUseCase": "read-only cursor surface; fires no hooks. Two of its three " +
"operations read bd_events_journal (Read, and ReadPage which adds the counter head " +
"GET /v0/beads/events pages with) and the third is a prefix delete of records " +
"already committed — the delete changes no bead, and the journal itself is written " +
"at the issueops seam inside the mutation's own transaction, so everything it " +
"records is already covered by the use case that made the change",
})
}
// TestRecordingIssueUseCaseCoversItsSurface and its three siblings are the
// method-level halves. The exemption reasons are the parity argument itself:
// each one says what the DoltStorage plumbing fires for the same operation,
// which is nothing.
func TestRecordingIssueUseCaseCoversItsSurface(t *testing.T) {
reads := "reads state, changes none"
deletes := "deletes fire no script hook on the DoltStorage plumbing either — the vocabulary " +
"has no name for a deletion and the row is gone (hook_deleter.go, hookTrackingTransaction.DeleteIssue)"
leases := "lease and claim bookkeeping the DoltStorage plumbing fires no hook for: " +
"HookFiringStore overrides neither UnclaimIssue, UnclaimIssueIfAssignee, HeartbeatIssue nor " +
"ReclaimExpiredLeases, so `bd unclaim` and `bd heartbeat` run no script on either plumbing"
assertPartition(t, "IssueUseCase", interfaceMethods(reflect.TypeOf((*domain.IssueUseCase)(nil)).Elem()),
reflect.TypeOf((*recordingIssueUC)(nil)), map[string]string{
"AsOf": reads,
"CountIssues": reads,
"CountIssuesByGroup": reads,
"CountOpenChildren": reads,
"CountOpenWispChildren": reads,
"FindWispDependentsRecursive": reads,
"GetBlockedIssues": reads,
"GetDescendants": reads,
"GetEpicsEligibleForClosure": reads,
"GetIssue": reads,
"GetIssuesByIDs": reads,
"GetMany": reads,
"GetNewlyUnblockedByClose": reads,
"GetNewlyUnblockedByCloseWisp": reads,
"GetReadyWork": reads,
"GetReadyWorkWithCounts": reads,
"GetStaleIssues": reads,
"GetStatistics": reads,
"GetWisp": reads,
"GetWispsByIDs": reads,
"History": reads,
"IterEvents": reads,
"PreviewDelete": reads,
"PreviewDeleteWisp": reads,
"SearchIssueIDs": reads,
"SearchIssues": reads,
"SearchWispsPlane": reads,
"SearchIssuesWithCounts": reads,
"DeleteIssue": deletes,
"DeleteIssues": deletes,
"DeleteWisp": deletes,
"DeleteWisps": deletes,
"Unclaim": leases,
"UnclaimIfAssignee": leases,
"Heartbeat": leases,
"ReclaimExpiredLeases": leases,
"WakeExpiredDefers": "the deferred-work sweep is a clock crossing rather than a user's " +
"mutation, and the DoltStorage plumbing fires nothing for it",
"PromoteWisp": "no route calls it: bd promote moves the row with ApplyUpdate's " +
"persistence spec, which records the update, and its DoltStorage twin, " +
"PromoteFromEphemeral, fires no hook either",
})
}
func TestRecordingDependencyUseCaseCoversItsSurface(t *testing.T) {
reads := "reads the graph, changes none"
assertPartition(t, "DependencyUseCase", interfaceMethods(reflect.TypeOf((*domain.DependencyUseCase)(nil)).Elem()),
reflect.TypeOf((*recordingDepUC)(nil)), map[string]string{
"CountByIssueID": reads,
"CountEdges": reads,
"CountByWispID": reads,
"CountsByIssueIDs": reads,
"CountsByWispIDs": reads,
// The two halves of the whole-graph gate issueops.BatchApplier
// re-runs at the end of a mixed request. Both are repository PROBES
// — an ancestry walk and a reachability walk — so there is nothing
// for the recorder to notify about; the writes those gates guard are
// recorded by AddDependencies, which is declared below.
"ValidateBlockingHierarchy": reads,
"CycleThroughEdges": reads,
"DetectCycleReport": reads,
"DetectCycles": reads,
"GetBlockingInfo": reads,
"GetDependencyTree": reads,
"GetExternalBlockingDependencyRecords": reads,
"GetForIssueIDs": reads,
"GetIssueDependencyRecords": reads,
"GetWispDependencyRecords": reads,
"IsBlocked": reads,
"IsWispBlocked": reads,
"IterWispWithIssueMetadata": reads,
"IterWithIssueMetadata": reads,
"ListByIssueIDs": reads,
"ListByWispIDs": reads,
"ListWispWithIssueMetadata": reads,
"ListWithIssueMetadata": reads,
"WalkDependencyTree": reads,
})
}
func TestRecordingLabelUseCaseCoversItsSurface(t *testing.T) {
reads := "reads labels, changes none"
assertPartition(t, "LabelUseCase", interfaceMethods(reflect.TypeOf((*domain.LabelUseCase)(nil)).Elem()),
reflect.TypeOf((*recordingLabelUC)(nil)), map[string]string{
"GetLabels": reads,
"GetLabelsForIssues": reads,
"GetLabelsForWisps": reads,
"GetWispLabels": reads,
})
}
func TestRecordingCommentUseCaseCoversItsSurface(t *testing.T) {
reads := "reads comments, changes none"
assertPartition(t, "CommentUseCase", interfaceMethods(reflect.TypeOf((*domain.CommentUseCase)(nil)).Elem()),
reflect.TypeOf((*recordingCommentUC)(nil)), map[string]string{
"CountCommentsForIssue": reads,
"CountCommentsForWisp": reads,
"GetCommentCounts": reads,
"GetCommentsForIssue": reads,
"GetCommentsForIssues": reads,
"GetCommentsForWisp": reads,
"GetCommentsForWisps": reads,
"GetWispCommentCounts": reads,
"IterCommentsForIssue": reads,
"IterCommentsForWisp": reads,
})
}
// ── The provider's capability surface ───────────────────────────────
// TestNotifyingProviderAnswersTheWholeProviderSurface enumerates what a
// provider offers by PARSING doltSQLProvider's methods out of this package,
// rather than listing them: doltSQLProvider is what every constructor in this
// package returns, so its method set is the surface a caller can reach through
// a UnitOfWorkProvider.
//
// A capability the wrapper does not answer is not a compile error — callers ask
// for these with a type assertion, which simply stops matching — so a role
// accessor added to the provider and forgotten here would silently lose both
// its hooks AND its feature in proxied mode. That is the failure this catches.
func TestNotifyingProviderAnswersTheWholeProviderSurface(t *testing.T) {
surface := methodsDeclaredOnType(t, "doltSQLProvider")
if len(surface) < 25 {
t.Fatalf("parsed only %d methods off doltSQLProvider — the scan is broken, not the provider", len(surface))
}
// initSchemaAttempt is the single-attempt body initSchema's backoff loop
// calls, and verifyTeamServerSchema and attachPreviewDatabase are the two open
// paths it fans out to (dolt_sql_provider.go). Like initSchema above them, each
// is an unexported startup helper reached only as p.<method> on the concrete
// provider — never through a UnitOfWorkProvider type assertion — so the wrapper
// has no capability to answer and no bead write to fire a hook for.
initBranch := "an unexported branch of initSchema's startup path, reached only on the concrete " +
"provider, not a capability any caller can reach through the wrapper"
assertPartition(t, "UnitOfWorkProvider", surface, reflect.TypeOf((*notifyingProvider)(nil)), map[string]string{
"BeginTx": "TxProvider hands out a bare transaction with no unit of work around it, so " +
"there is nothing to buffer and nothing to drain: the wrapper deliberately does not " +
"offer it, and only this package's own NewUOW asks a provider for one",
"initSchema": "unexported provider setup, not a capability any caller can reach",
"initSchemaAttempt": initBranch,
"verifyTeamServerSchema": initBranch,
"attachPreviewDatabase": initBranch,
})
}
// TestNotifyingProviderBuildsRolesOnItself is the other half of the accessor
// story, and the one reflection cannot see: an accessor that IS declared but
// reads `return NewCommenter(p.inner)` compiles, keeps every type assertion
// working, and silently builds the role on the UNWRAPPED provider — so its
// units of work are plain ones and every hook stops firing. The bodies are
// one-liners, so requiring the receiver to be the constructor's argument is an
// exact check rather than a heuristic.
// It scans the WHOLE package, not notifying.go: this package's convention is a
// file per role, so the accessor most likely to be written next — and to be
// written as a delegation — is the one in the new role's own file.
func TestNotifyingProviderBuildsRolesOnItself(t *testing.T) {
// The accessors are the provider methods that construct a role; the
// non-role capabilities forward to the inner provider on purpose.
forwarders := map[string]bool{
"NewUOW": true,
"Close": true,
"RunNonTx": true,
"SetPoolLimits": true,
"Unwrap": true,
// Events-journal and versioned-history capability plumbing: activation
// for both binds on the inner provider's transactions, and a retention
// pass writes no bead. None of these build a role, so none of them can
// build one "on itself".
"SetEventsJournalEnabled": true,
"RunEventsMaintenanceTx": true,
"SetVersionedHistoryEnabled": true,
}
var checked int
for _, fn := range funcsDeclaredOnType(t, "notifyingProvider") {
if forwarders[fn.Name.Name] {
continue
}
receiver := ""
if len(fn.Recv.List[0].Names) > 0 {
receiver = fn.Recv.List[0].Names[0].Name
}
if !passesReceiver(fn, receiver) {
t.Errorf("notifyingProvider.%s does not build its role on the wrapper: the role's units "+
"of work are then the inner provider's, and nothing it writes fires a hook", fn.Name.Name)
}
checked++
}
if checked < 25 {
t.Fatalf("checked only %d role accessors — the scan is broken", checked)
}
}
// TestUnitOfWorkBypassesAreAccountedFor is the third structural guard, and it
// closes the one hole the other two cannot see.
//
// The recorder sits at the USE-CASE seam, so it sees a write only if the write
// passed a use case. A caller that reaches the transaction directly — by
// peeling the decorator with unwrapUOW, or by asserting the concrete unit of
// work — writes rows no hook is fired for, and nothing about that is visible in
// a method set. Today there is exactly one such caller, and it is deliberate;
// the guard is here so that the SECOND one is a decision rather than an
// accident.
func TestUnitOfWorkBypassesAreAccountedFor(t *testing.T) {
bypasses := map[string]string{
"importStatementRunner": "the import role runs the shared batch-upsert engine on the " +
"transaction's statement runner (importer.go), so its writes never pass a use case. " +
"Import fires no hooks on the DoltStorage plumbing either — it runs the same engine " +
"there — so this is parity, not a gap. A hook per imported issue would be new " +
"behavior on both plumbings.",
}
found := map[string]bool{}
for _, fn := range funcsInPackage(t) {
if !reachesConcreteUOW(fn) {
continue
}
name := fn.Name.Name
found[name] = true
reason, ok := bypasses[name]
switch {
case !ok:
t.Errorf("%s reaches the unit of work beneath the recording layer, so whatever it "+
"writes fires no hook. Route the write through a use case, or list it in this "+
"test with the reason it fires none", name)
case strings.TrimSpace(reason) == "":
t.Errorf("%s is listed as a bypass with no reason", name)
}
}
for name := range bypasses {
if !found[name] {
t.Errorf("%s is listed as a bypass but no longer reaches past the recording layer — "+
"delete the entry", name)
}
}
}
// reachesConcreteUOW reports whether fn peels a unit of work down to the
// concrete type — by calling unwrapUOW, or by asserting baseUOW directly.
func reachesConcreteUOW(fn *ast.FuncDecl) bool {
reaches := false
ast.Inspect(fn, func(n ast.Node) bool {
switch node := n.(type) {
case *ast.CallExpr:
if ident, ok := node.Fun.(*ast.Ident); ok && ident.Name == "unwrapUOW" {
reaches = true
}
case *ast.TypeAssertExpr:
if receiverTypeName(node.Type) == "baseUOW" {
reaches = true
}
}
return true
})
return reaches
}
// funcsInPackage parses every non-test file in this package and returns all of
// its function and method declarations.
func funcsInPackage(t *testing.T) []*ast.FuncDecl {
t.Helper()
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, 0)
if err != nil {
t.Fatalf("parse package: %v", err)
}
var found []*ast.FuncDecl
for _, pkg := range pkgs {
for _, file := range pkg.Files {
for _, decl := range file.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
found = append(found, fn)
}
}
}
}
return found
}
// passesReceiver reports whether fn hands the receiver itself to a call.
func passesReceiver(fn *ast.FuncDecl, receiver string) bool {
found := false
ast.Inspect(fn, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
for _, arg := range call.Args {
if ident, ok := arg.(*ast.Ident); ok && ident.Name == receiver {
found = true
}
}
return true
})
return found
}
// methodsDeclaredOnType returns the names of the methods this package declares
// on the named receiver type.
func methodsDeclaredOnType(t *testing.T, typeName string) []string {
t.Helper()
var names []string
for _, fn := range funcsDeclaredOnType(t, typeName) {
names = append(names, fn.Name.Name)
}
sort.Strings(names)
return names
}
// funcsDeclaredOnType parses EVERY non-test file in this package and returns
// the declarations whose receiver is typeName. Both structural guards read the
// package rather than one file: a role lives in its own file here, so a scan
// pinned to notifying.go would not see the accessor a new role adds — which is
// the one most likely to be written as a delegation.
func funcsDeclaredOnType(t *testing.T, typeName string) []*ast.FuncDecl {
t.Helper()
var found []*ast.FuncDecl
for _, fn := range funcsInPackage(t) {
if fn.Recv == nil || len(fn.Recv.List) == 0 {
continue
}
if receiverTypeName(fn.Recv.List[0].Type) == typeName {
found = append(found, fn)
}
}
return found
}
func receiverTypeName(expr ast.Expr) string {
if star, ok := expr.(*ast.StarExpr); ok {
expr = star.X
}
if ident, ok := expr.(*ast.Ident); ok {
return ident.Name
}
return ""
}