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
- Variables
- func RepoOf(ref string) string
- type Adapter
- type ApplyCall
- type Conn
- func (c *Conn) Applies() []ApplyCall
- func (c *Conn) Apply(ctx context.Context, e provider.EffectRequest) (provider.EffectResult, error)
- func (c *Conn) Deliveries() []provider.RawEvent
- func (c *Conn) Effects() []ApplyCall
- func (c *Conn) Emit(ctx context.Context, sink provider.IngressSink, ws ...Webhook) ([]provider.RawEvent, error)
- func (c *Conn) FailNext(m Method, err error)
- func (c *Conn) Handler(sink provider.IngressSink) http.Handler
- func (c *Conn) Health() provider.HealthStatus
- func (c *Conn) List(ctx context.Context, scope v1alpha1.Scope) ([]v1alpha1.ObjectRef, error)
- func (c *Conn) MintGitCredential(ctx context.Context, req provider.GitCredentialRequest) (provider.Credential, error)
- func (c *Conn) Mints() []MintCall
- func (c *Conn) Name() string
- func (c *Conn) Normalise(ctx context.Context, ev provider.RawEvent) ([]v1alpha1.Event, error)
- func (c *Conn) Object(ref string) (provider.Observation, bool)
- func (c *Conn) Observe(ctx context.Context, ref v1alpha1.ObjectRef) (provider.Observation, error)
- func (c *Conn) Project(ctx context.Context, ref v1alpha1.ObjectRef, p provider.Projection) error
- func (c *Conn) Projections() []ProjectCall
- func (c *Conn) RawEvent(w Webhook) (provider.RawEvent, error)
- func (c *Conn) Recover(ctx context.Context, since time.Time, sink provider.IngressSink) error
- func (c *Conn) ResolveGroup(ctx context.Context, g v1alpha1.GroupSource) ([]string, error)
- func (c *Conn) Seed(objs ...provider.Observation) error
- func (c *Conn) SetHealth(h provider.HealthStatus)
- func (c *Conn) SetOrgRole(org, role string, logins ...string)
- func (c *Conn) SetTeam(team string, logins ...string)
- func (c *Conn) SetUserGroup(name string, logins ...string)
- func (c *Conn) Undelivered(ws ...Webhook) ([]provider.RawEvent, error)
- func (c *Conn) Update(ref string, fn func(*provider.Observation)) error
- type Method
- type MintCall
- type Options
- type ProjectCall
- type Sender
- type Webhook
Constants ¶
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.
const MaxCredentialTTL = time.Hour
MaxCredentialTTL caps a minted token's lifetime, as GitHub does.
const MaxWebhookBytes = 1 << 20
MaxWebhookBytes bounds a posted webhook body, like the API server's body limit.
Variables ¶
var DefaultIdentities = map[string]string{
"ccf-factory[bot]": "author",
"ccf-factory-reviewer[bot]": "reviewer",
}
DefaultIdentities are the factory App logins, as on GitHub.
Functions ¶
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 ¶
NewAdapter returns an adapter with no connections.
func (*Adapter) 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 ¶
func (a *Adapter) Connect(ctx context.Context, p v1alpha1.Provider, _ provider.SecretResolver) (provider.Conn, error)
Connect implements provider.Adapter: it binds p to the Conn named p.Metadata.Name, creating it if needed. Secrets are not used.
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 (*Conn) Apply ¶
func (c *Conn) Apply(ctx context.Context, e provider.EffectRequest) (provider.EffectResult, error)
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 ¶
Deliveries returns every delivery the provider made (emitted, posted or undelivered), in order.
func (*Conn) Effects ¶
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 ¶
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 bad body 400.
func (*Conn) Health ¶
func (c *Conn) Health() provider.HealthStatus
Health implements provider.Conn: ok unless SetHealth said otherwise.
func (*Conn) List ¶
List implements provider.Conn: the objects whose repo matches scope.repos (any repo when empty) and no scope.exclude glob, that are open or carry a projection, sorted by ref. Channels and branches are not modelled, nor GitHub's 90-day window.
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) Normalise ¶
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 ¶
Observe implements provider.Conn: a copy of the seeded (and since changed) object.
func (*Conn) Project ¶
Project implements provider.Conn: it stores the projection on the object (replacing the work item's previous one; Observe returns it in Projections) 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) Recover ¶
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 ¶
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.
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 ¶
SetOrgRole sets the members of an org with a role (e.g. the admins).
func (*Conn) SetUserGroup ¶
SetUserGroup sets the members of a user group (Slack).
func (*Conn) Undelivered ¶
Undelivered records webhooks the provider made but the dispatcher never received (the restart gap): only Recover delivers them.
type Method ¶
type Method string
Method names a Conn method, for FailNext.
const ( MethodRecover Method = "Recover" MethodNormalise Method = "Normalise" MethodObserve Method = "Observe" MethodList Method = "List" 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.