githubtest

package
v0.3.1 Latest Latest
Warning

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

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

Documentation

Overview

Package githubtest is an httptest GitHub for the GitHub adapter's tests. It serves the App endpoints the token minter uses (GET /app, GET /repos/{owner}/{repo}/installation, GET /orgs/{org}/installation, GET /users/{user}/installation and POST /app/installations/{id}/access_tokens) and the webhook deliveries (GET /app/hook/deliveries[/{id}]), verifying every App JWT against the App's public key. With the installation tokens it minted, it serves org members and team members, releases, closed pull requests and commit comparisons (api.go), and issues and PRs with their labels and comments, issue search, deployments, an installation's repos and the GraphQL queries the adapter makes, from an object model or canned responses (objects.go). It checks that each token covers the request: the repo and the permission for repo routes, members: read for org routes. The effects' routes (effects.go) create and change issues, PRs, sub-issues, reviews and review threads in the same model. It records each request for assertions and can be made to fail.

It is safe for concurrent use. Getters return copies.

Index

Constants

View Source
const (
	RouteApp             = "app"
	RouteInstallation    = "installation"
	RouteOrgInstallation = "org_installation"
	RouteAccessToken     = "access_tokens"
	RouteDeliveries      = "deliveries"
	RouteDelivery        = "delivery"
	RouteMembers         = "members"
	RouteTeamMembers     = "team_members"
	RouteReleases        = "releases"
	RoutePulls           = "pulls"
	RouteCompare         = "compare"
	// The object routes (objects.go).
	RouteUserInstallation  = "user_installation"
	RouteInstallationRepos = "installation_repos"
	RouteIssue             = "issue"
	RouteComments          = "comments"
	RouteCreateComment     = "create_comment"
	RouteUpdateComment     = "update_comment"
	RouteAddLabels         = "add_labels"
	RouteRemoveLabel       = "remove_label"
	RouteGraphQL           = "graphql"
	RouteDeployments       = "deployments"
	RouteDeploymentStatus  = "deployment_statuses"
	// The effect routes (effects.go).
	RouteRepo         = "repo"
	RouteListIssues   = "list_issues"
	RouteCreateIssue  = "create_issue"
	RouteUpdateIssue  = "update_issue"
	RouteComment      = "comment"
	RouteSubIssues    = "sub_issues"
	RouteAddSubIssue  = "add_sub_issue"
	RoutePull         = "pull"
	RouteCreatePull   = "create_pull"
	RouteUpdatePull   = "update_pull"
	RouteMerge        = "merge"
	RouteReviews      = "reviews"
	RouteReview       = "review"
	RouteCreateReview = "create_review"
)

Routes, for FailNext and Count.

View Source
const (
	MergeReviewRequired = "review-required"
	MergeNotMergeable   = "not-mergeable"
)

Merge blocks (Object.MergeBlock).

View Source
const TokenTTL = time.Hour

TokenTTL is the lifetime of the tokens the server mints, as on GitHub.

View Source
const WebURL = "https://github.test"

WebURL is the base of the html_url links the server returns.

Variables

This section is empty.

Functions

func AppKey

func AppKey(t testing.TB) ([]byte, *rsa.PrivateKey)

AppKey returns a throwaway RSA key and its PKCS#1 PEM encoding (GitHub's format), generated once per test binary.

func NewAppKey

func NewAppKey(t testing.TB) ([]byte, *rsa.PrivateKey)

NewAppKey returns a fresh throwaway RSA key and its PEM encoding, for a second App.

Types

type CheckSuite

type CheckSuite struct {
	Status     string
	Conclusion string
	Runs       int
}

CheckSuite is one check suite of a commit: Status (QUEUED, IN_PROGRESS, COMPLETED, …), Conclusion once completed (SUCCESS, FAILURE, …) and how many check runs it has.

type Claims

type Claims struct {
	Issuer    string
	IssuedAt  time.Time
	ExpiresAt time.Time
}

Claims are the claims of a verified App JWT.

type Comment

type Comment struct {
	ID     int64
	Author User
	Body   string
}

Comment is one conversation comment on an issue or a PR, or one comment of a review thread.

type Delivery

type Delivery struct {
	ID          int64
	GUID        string
	DeliveredAt time.Time
	Redelivery  bool
	Event       string
	Action      string
	StatusCode  int
	// Headers and Payload are the request GitHub sent.
	Headers map[string]string
	Payload json.RawMessage
}

Delivery is one webhook delivery of an App, as GET /app/hook/deliveries[/{id}] serves it.

type Deployment

type Deployment struct {
	ID          int64
	SHA         string
	Ref         string
	Environment string
	Statuses    []DeploymentStatus
}

Deployment is a repo's deployment, with its statuses newest first.

type DeploymentStatus

type DeploymentStatus struct {
	State          string
	EnvironmentURL string
}

DeploymentStatus is one status of a deployment.

type Failure

type Failure struct {
	Status  int
	Message string
	Header  http.Header
}

Failure is a canned response for the next request on a route.

type GraphQLRequest

type GraphQLRequest struct {
	Operation string
	Variables map[string]any
}

GraphQLRequest is one GraphQL request received.

type Installation

type Installation struct {
	ID    int64
	AppID int64
	// Owner is the account the App is installed on ("compliance-framework").
	Owner string
	// Repos are the repo names (without owner) the installation covers; empty means all.
	Repos []string
	// Permissions are what the installation was granted.
	Permissions map[string]string
	// User is true for an installation on a user account: GET /orgs/{owner}/installation
	// answers 404 for it.
	User bool
}

Installation is one App installation on an account.

type Object

type Object struct {
	// Repo is "owner/name".
	Repo   string
	Number int
	PR     bool
	// ID is the REST id (sub-issues are added by it); zero is numbered.
	ID    int64
	Title string
	Body  string
	// State is "open", "closed" or "merged" (PRs); StateReason is why an issue was closed.
	State       string
	StateReason string
	Labels      []string
	Author      User
	UpdatedAt   time.Time
	Draft       bool
	// Head is the PR's head commit, HeadRef its branch; Base is the base branch.
	Head     string
	HeadRef  string
	Base     string
	Comments []Comment
	// SubIssues are the numbers of the issue's sub-issues (in the same repo).
	SubIssues []int
	Reviews   []Review
	Threads   []Thread
	// CheckSuites are the PR head commit's check suites, as GraphQL's Commit.checkSuites shows
	// them.
	CheckSuites []CheckSuite
	// MergeBlock makes PUT …/merge refuse with 405: MergeReviewRequired or MergeNotMergeable.
	MergeBlock string
	// MergeMethod and MergeCommit are set by a merge.
	MergeMethod string
	MergeCommit string
}

Object is an issue or a PR in the object model. The REST routes read and change it, and GraphQL queries without a canned response are answered from it (labels, author, state, comments; a PR's draft, head, base, threads and head check suites, with no reviews).

type PullRequest

type PullRequest struct {
	Number      int
	MergedAt    time.Time
	MergeCommit string
	Base        string
}

PullRequest is a closed pull request, as GET /repos/{owner}/{repo}/pulls?state=closed lists it. A zero MergedAt is a PR closed without merging.

type Release

type Release struct {
	Tag        string
	Prerelease bool
	Draft      bool
}

Release is a repo's release, as GET /repos/{owner}/{repo}/releases lists it.

type Repo

type Repo struct {
	AllowMergeCommit bool
	AllowSquashMerge bool
	AllowRebaseMerge bool
	DefaultBranch    string
}

Repo is a repository's settings, as GET /repos/{owner}/{repo} shows them.

type Request

type Request struct {
	Method string
	Path   string
	// Body is the raw request body.
	Body []byte
	// Claims are the JWT's claims; zero when the request carried no valid JWT.
	Claims Claims
}

Request is one request the server received, with the App JWT it carried.

type Review

type Review struct {
	ID       int64
	Author   User
	State    string
	Body     string
	CommitID string
	// Comments are the review's inline comments.
	Comments []ReviewComment
}

Review is one review of a PR. State is APPROVED, CHANGES_REQUESTED or COMMENTED.

type ReviewComment

type ReviewComment struct {
	Path string
	Line int
	Side string
	Body string
}

ReviewComment is one inline comment of a review.

type Server

type Server struct {
	*httptest.Server
	// contains filtered or unexported fields
}

Server is an httptest GitHub.

func NewServer

func NewServer(t testing.TB, c clock.Clock) *Server

NewServer starts a server stamping token expiry with c; it is closed with the test.

func (*Server) AddAccountRepos

func (s *Server) AddAccountRepos(owner string, names ...string)

AddAccountRepos names an account's repos, which an installation on all of its repos lists.

func (*Server) AddApp

func (s *Server) AddApp(appID int64, key *rsa.PublicKey)

AddApp registers an App and its public key.

func (*Server) AddDelivery

func (s *Server) AddDelivery(appID int64, d Delivery)

AddDelivery records a delivery of the App's webhook (EnableHook is implied).

func (*Server) AddDeployment

func (s *Server) AddDeployment(repo string, d Deployment)

AddDeployment adds a deployment to repo; the newest is the one added last.

func (*Server) AddInstallation

func (s *Server) AddInstallation(in Installation)

AddInstallation installs an App on an account.

func (*Server) AddObject

func (s *Server) AddObject(o Object)

AddObject adds (or replaces) an issue or a PR. Comment IDs of zero are numbered; a zero UpdatedAt is the clock's now and an empty State is "open".

func (*Server) AddOrgMember

func (s *Server) AddOrgMember(org, login, role string)

AddOrgMember makes login a member of org with role "admin" or "member".

func (*Server) AddPulls

func (s *Server) AddPulls(repo string, prs ...PullRequest)

AddPulls adds closed pull requests to repo ("owner/name"), listed in the order given.

func (*Server) AddReleases

func (s *Server) AddReleases(repo string, rels ...Release)

AddReleases adds releases to repo ("owner/name"), listed in the order given.

func (*Server) AddTeam

func (s *Server) AddTeam(org, slug string, logins ...string)

AddTeam creates the team org/slug with members logins.

func (*Server) Count

func (s *Server) Count(route string) int

Count is the number of requests received on route, failed ones included.

func (*Server) EnableHook

func (s *Server) EnableHook(appID int64)

EnableHook gives an App a webhook, so its deliveries can be listed (an App without one gets 404, as on GitHub).

func (*Server) FailNext

func (s *Server) FailNext(route string, f Failure)

FailNext makes the next request on route answer f instead.

func (*Server) Gate

func (s *Server) Gate() (release func())

Gate holds every access-token request until the returned release func is called, so a test can pile concurrent callers onto one request.

func (*Server) GraphQLRequests

func (s *Server) GraphQLRequests() []GraphQLRequest

GraphQLRequests returns the GraphQL requests received, in order.

func (*Server) InFlight

func (s *Server) InFlight() int

InFlight is the number of access-token requests held by the gate.

func (*Server) Object

func (s *Server) Object(repo string, n int) (Object, bool)

Object returns a copy of an object in the model.

func (*Server) Requests

func (s *Server) Requests() []Request

Requests returns every request received, in order.

func (*Server) SetAncestor

func (s *Server) SetAncestor(repo, ancestor, descendant string)

SetAncestor records that commit ancestor is an ancestor of descendant in repo: the compare API then answers "ahead" for ancestor...descendant and "behind" the other way. Equal commits are "identical"; anything else is "diverged".

func (*Server) SetGraphQL

func (s *Server) SetGraphQL(op string, vars map[string]any, response []byte)

SetGraphQL sets the canned response of a GraphQL operation ("Observe", "ObserveThreads", …) for exactly these variables (compared as JSON), e.g. one recorded from GitHub.

func (*Server) SetInstallationPermissions

func (s *Server) SetInstallationPermissions(id int64, perms map[string]string)

SetInstallationPermissions changes what an installation was granted.

func (*Server) SetPageSize

func (s *Server) SetPageSize(n int)

SetPageSize caps every list page (default 100, GitHub's maximum), so tests can paginate.

func (*Server) SetRepo

func (s *Server) SetRepo(repo string, r Repo)

SetRepo sets a repo's settings (default: every merge method, branch main).

func (*Server) SetSlug

func (s *Server) SetSlug(appID int64, slug string)

SetSlug sets an App's slug (default "app-<id>"): it acts as "<slug>[bot]".

func (*Server) TokenRequests

func (s *Server) TokenRequests() []TokenRequest

TokenRequests returns the access-token requests received, in order.

func (*Server) Tokens

func (s *Server) Tokens() []string

Tokens returns every token value the server minted, in order.

func (*Server) UpdateObject

func (s *Server) UpdateObject(repo string, n int, fn func(*Object))

UpdateObject changes an object in the model out of band (a human labelling it, say).

type Thread

type Thread struct {
	ID       string
	Resolved bool
	Comments []Comment
}

Thread is one review thread of a PR, by its GraphQL node ID.

type TokenRequest

type TokenRequest struct {
	InstallationID int64
	// Body is the raw request body, for exact assertions.
	Body         []byte
	Repositories []string
	// HasRepositories is false when the body had no "repositories" field at all.
	HasRepositories bool
	Permissions     map[string]string
}

TokenRequest is one access-token request, decoded.

type User

type User struct {
	Login string
	Bot   bool
}

User is an account: a person, or an App's bot account (Bot, with the REST login "<slug>[bot]"; GraphQL spells it "<slug>").

Jump to

Keyboard shortcuts

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