fake

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

Documentation

Overview

Package fake is an in-memory provider for tests: it keeps objects in memory, records every Project and Apply for assertions, emits scripted deliveries into an IngressSink and normalises them into Events, resolves Groups from configured membership, mints fake git tokens and reports a settable health.

Everything is safe for concurrent use. Getters return copies.

Index

Constants

View Source
const (
	DefaultType    = string(v1alpha1.ProviderTypeGitHub)
	DefaultHost    = "github.com"
	DefaultBaseURL = "https://fake.invalid"
	// DefaultTier is the tier of an actor no trust rule matches.
	DefaultTier = "anyone"
	// DeliveryPrefix starts the ID of every delivery the fake makes ("fake-1").
	DeliveryPrefix = "fake-"
)

Defaults for Options.

View Source
const MaxCredentialTTL = time.Hour

MaxCredentialTTL caps a minted token's lifetime, as GitHub does.

View Source
const MaxWebhookBytes = 1 << 20

MaxWebhookBytes bounds a posted webhook body, like the API server's body limit.

Variables

View Source
var DefaultIdentities = map[string]string{
	"ccf-factory[bot]":          "author",
	"ccf-factory-reviewer[bot]": "reviewer",
}

DefaultIdentities are the factory App logins, as on GitHub.

Functions

func RepoOf

func RepoOf(ref string) string

RepoOf returns the repo of a ref ("owner/name#42" → "owner/name"), or "" for a ref without a number.

Types

type Adapter

type Adapter struct {
	// contains filtered or unexported fields
}

Adapter is a fake provider.Adapter. Each Provider instance (by name) gets one Conn, which outlives reconnects, as a real provider's objects do.

func NewAdapter

func NewAdapter(opts Options) *Adapter

NewAdapter returns an adapter with no connections.

func (*Adapter) Conn

func (a *Adapter) Conn(name string) *Conn

Conn returns the Conn for the Provider named name, creating it if needed, so a test can seed it before the code under test connects.

func (*Adapter) Connect

Connect implements provider.Adapter: it binds p to the Conn named p.Metadata.Name, creating it if needed. Secrets are not used.

func (*Adapter) Connects

func (a *Adapter) Connects() int

Connects returns how many times Connect succeeded.

func (*Adapter) Type

func (a *Adapter) Type() string

Type implements provider.Adapter.

type ApplyCall

type ApplyCall struct {
	Request provider.EffectRequest
	Result  provider.EffectResult
	Err     error
}

ApplyCall is one recorded Apply call.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is a fake provider.Conn for one Provider instance.

func NewConn

func NewConn(p v1alpha1.Provider, opts Options) *Conn

NewConn returns a Conn for p, without an Adapter.

func (*Conn) Applies

func (c *Conn) Applies() []ApplyCall

Applies returns every Apply call, in order: replays and failures included.

func (*Conn) Apply

Apply implements provider.Conn. The first Apply of an idempotency key changes the objects as the op says and stores the result; a later Apply of the key (whatever its op) changes nothing and returns that result with Replayed set. A failed Apply stores nothing, so a retry runs again. Every call is recorded.

Modelled ops: comment ops count on the issue; label.add/remove (args.labels or args.label); close; link-duplicate (label "duplicate" and close); create-issue and pr.open (Target.Ref is the repo; args.labels, args.base, args.head, args.draft) create the next number in the repo; sub-issue.add (args.issue: a ref); pr.retarget (args.base); pr.merge; review.approve (approves the head for Identity); thread.resolve. Other API ops only need the target to exist. Git-side ops are ErrUnsupported (the agent executes them).

func (*Conn) Deliveries

func (c *Conn) Deliveries() []provider.RawEvent

Deliveries returns every delivery the provider made (emitted, posted or undelivered), in order.

func (*Conn) Effects

func (c *Conn) Effects() []ApplyCall

Effects returns the effects that were applied: the successful Apply calls that were not replays, in order.

func (*Conn) Emit

func (c *Conn) Emit(ctx context.Context, sink provider.IngressSink, ws ...Webhook) ([]provider.RawEvent, error)

Emit delivers each webhook to sink in order, as the provider would, and then records it for Recover (whatever Accept returned: the provider keeps failed deliveries too). It stops at the first error Accept returns (ErrDuplicateDelivery included) and returns the deliveries made so far.

func (*Conn) FailNext

func (c *Conn) FailNext(m Method, err error)

FailNext makes the next call of m return err (once per call; queued in order).

func (*Conn) Handler

func (c *Conn) Handler(sink provider.IngressSink) http.Handler

Handler implements provider.Conn. It accepts a POSTed Webhook as JSON (there is no signature to verify), calls sink.Accept and only then answers: 202, 200 for a duplicate delivery, 503 when the sink fails. A bad method is 405, a body over MaxWebhookBytes 413, a bad body 400. Refusals are problems (provider.WriteProblem), with internal/server's codes.

func (*Conn) Health

func (c *Conn) Health() provider.HealthStatus

Health implements provider.Conn: ok unless SetHealth said otherwise.

func (*Conn) MintGitCredential

func (c *Conn) MintGitCredential(ctx context.Context, req provider.GitCredentialRequest) (provider.Credential, error)

MintGitCredential implements provider.Conn: a fake token ("fake-<identity>-<n>") for exactly the requested repos and permissions (a read-only request gets contents: read), expiring after TTL (capped at MaxCredentialTTL). A request that fails Validate (no identity, no repo, no positive TTL, readRepos on a token that can write) is ErrInvalid, as is an identity the Provider's github.identities doesn't list (when it lists any). Mints records every call.

func (*Conn) Mints

func (c *Conn) Mints() []MintCall

Mints returns every MintGitCredential call, in order.

func (*Conn) Name

func (c *Conn) Name() string

Name is the Provider instance's name.

func (*Conn) Normalise

func (c *Conn) Normalise(ctx context.Context, ev provider.RawEvent) ([]v1alpha1.Event, error)

Normalise implements provider.Conn. Each object of the webhook (Object, then FanOut, sorted by ref) becomes one Event with ID EventID(ev.ID, n); a webhook without objects becomes one Event. The actor's ID is "<provider>:<login>", its tier comes from Sender.Tier or the Provider's trust rules (DefaultTier when none matches), and a factory App login sets IsFactory and Identity.

func (*Conn) Object

func (c *Conn) Object(ref string) (provider.Observation, bool)

Object returns a copy of the object at ref.

func (*Conn) Observe

func (c *Conn) Observe(ctx context.Context, ref v1alpha1.ObjectRef) (provider.Observation, error)

Observe implements provider.Conn: a copy of the seeded (and since changed) object.

func (*Conn) Project

func (c *Conn) Project(ctx context.Context, ref v1alpha1.ObjectRef, p provider.Projection) error

Project implements provider.Conn: it stores the projection on the object (replacing the work item's previous one; ProjectionsOn returns them) and adds the projection's labels the object lacks. Unknown objects are ErrNotFound.

func (*Conn) Projections

func (c *Conn) Projections() []ProjectCall

Projections returns every Project call, in order.

func (*Conn) ProjectionsOn added in v0.2.0

func (c *Conn) ProjectionsOn(ref string) []provider.Projection

ProjectionsOn returns the projections on the object at ref: what Project last wrote for each work item, sorted by WorkItemID (nil when none). Observe doesn't return them, as GitHub's Observe doesn't read its markers back.

func (*Conn) RawEvent

func (c *Conn) RawEvent(w Webhook) (provider.RawEvent, error)

RawEvent builds the delivery for w without recording or sending it.

func (*Conn) Recover

func (c *Conn) Recover(ctx context.Context, since time.Time, sink provider.IngressSink) error

Recover implements provider.Conn: it sends every recorded delivery received at or after since to sink, skipping the ones the sink reports as duplicates.

func (*Conn) ResolveGroup

func (c *Conn) ResolveGroup(ctx context.Context, g v1alpha1.GroupSource) ([]string, error)

ResolveGroup implements provider.Conn from the membership set with SetTeam, SetOrgRole and SetUserGroup; users are returned as listed. A team, org role or user group that was never set is ErrNotFound; a source for another provider, or with not exactly one source, is ErrInvalid.

func (*Conn) Seed

func (c *Conn) Seed(objs ...provider.Observation) error

Seed adds or replaces objects. Ref.Provider defaults to this provider, Ref.Kind to "issue", State to open; an issue gets an empty Issue and a PR an empty PR when unset. A replaced object loses its projections.

func (*Conn) SetHealth

func (c *Conn) SetHealth(h provider.HealthStatus)

SetHealth sets what Health returns; a zero CheckedAt is stamped with the clock on read.

func (*Conn) SetOrgRole

func (c *Conn) SetOrgRole(org, role string, logins ...string)

SetOrgRole sets the members of an org with a role (e.g. the admins).

func (*Conn) SetTeam

func (c *Conn) SetTeam(team string, logins ...string)

SetTeam sets the members of a team ("org/team-slug").

func (*Conn) SetUserGroup

func (c *Conn) SetUserGroup(name string, logins ...string)

SetUserGroup sets the members of a user group (Slack).

func (*Conn) Undelivered

func (c *Conn) Undelivered(ws ...Webhook) ([]provider.RawEvent, error)

Undelivered records webhooks the provider made but the dispatcher never received (the restart gap): only Recover delivers them.

func (*Conn) Update

func (c *Conn) Update(ref string, fn func(*provider.Observation)) error

Update changes an object out of band (a human merging a PR, say); ErrNotFound when there is none at ref.

type Method

type Method string

Method names a Conn method, for FailNext.

const (
	MethodRecover           Method = "Recover"
	MethodNormalise         Method = "Normalise"
	MethodObserve           Method = "Observe"
	MethodResolveGroup      Method = "ResolveGroup"
	MethodProject           Method = "Project"
	MethodApply             Method = "Apply"
	MethodMintGitCredential Method = "MintGitCredential"
)

Methods that can be made to fail.

type MintCall

type MintCall struct {
	Request    provider.GitCredentialRequest
	Credential provider.Credential
	Err        error
}

MintCall is one recorded MintGitCredential call.

type Options

type Options struct {
	// Type is the adapter type (default "github"), so a catalog Provider of that type
	// connects to the fake.
	Type string
	// Clock stamps deliveries, merges, tokens and health (default clock.Real).
	Clock clock.Clock
	// Groups resolves the catalog Groups named by trust rules; nil means group rules never
	// match.
	Groups provider.GroupLookup
	// Identities maps the factory Apps' logins to identities (default DefaultIdentities).
	Identities map[string]string
	// Host is the git host of minted credentials (default "github.com").
	Host string
	// BaseURL prefixes the URLs of objects and effects (default "https://fake.invalid").
	BaseURL string
}

Options configure an Adapter or a Conn. The zero value is usable.

type ProjectCall

type ProjectCall struct {
	Ref        v1alpha1.ObjectRef
	Projection provider.Projection
	// Changed is false when the object already carried this projection and its labels.
	Changed bool
	Err     error
}

ProjectCall is one recorded Project call.

type Sender

type Sender struct {
	Login string `json:"login"`
	Bot   bool   `json:"bot,omitzero"`
	// Association is GitHub's author association (MEMBER, CONTRIBUTOR, …), for trust rules.
	Association string `json:"association,omitzero"`
	// Tier, when set, is used as is instead of the Provider's trust rules.
	Tier string `json:"tier,omitzero"`
}

Sender is who caused a delivery.

type Webhook

type Webhook struct {
	// Delivery is the provider's delivery ID; one is generated when empty. The RawEvent's ID
	// is DeliveryPrefix + Delivery.
	Delivery string             `json:"delivery,omitzero"`
	Type     v1alpha1.EventType `json:"type"`
	Sender   Sender             `json:"sender,omitzero"`
	// Object is the event's object. FanOut adds more: one Event per object, numbered in ref
	// order (like GitHub's check_suite → one Event per PR).
	Object *v1alpha1.ObjectRef  `json:"object,omitzero"`
	FanOut []v1alpha1.ObjectRef `json:"fanOut,omitzero"`
	// Repo defaults to the object's repo.
	Repo       string         `json:"repo,omitzero"`
	Subject    string         `json:"subject,omitzero"`
	ContentRef string         `json:"contentRef,omitzero"`
	Facts      map[string]any `json:"facts,omitzero"`
	// Time defaults to when the delivery was received.
	Time time.Time `json:"time,omitzero"`
}

Webhook is a scripted delivery: the body of a fake webhook, which Normalise turns into Events. Tests build it directly.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL