{"modulePath":"github.com/panyam/goapplib/storage","version":"v0.7.44","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package githubtest\n\nPackage githubtest is a fake GitHub for tests of code that reads and writes repos: the mounts GitHub driver, the storage example app, and consumers' own tests. It serves the REST routes the driver uses (a repo, a commit, a branch's commits, the tags, a tarball, and the Contents API) and the GraphQL tags query over repos held in memory, and each write makes a real commit on its branch. It serves the hooks API too, and Push delivers a signed push to each hook made through it. PushRequest and SignedRequest build signed webhook deliveries for an app's handler.\n\nA private repo answers only a request with an accepted token, as GitHub does, with 404 for anything else. Once a private repo has grants (Repo.Grant), only a granted token reads it. Every request is recorded with the token it carried, so a test can check that a connection's token reached each one.\n\nIt serves the Git LFS batch API for downloads (lfs.go), so a repo can hold LFS files, whose tarball, raw and contents answers carry only the pointer, as GitHub's do.\n\nIt serves a GitHub App's sign-in on the same host, at the paths oneauth's GithubOAuth2.SetEnterpriseURL points at: the web flow with PKCE, the device flow, refresh, /user and org membership. AddApp registers the App, AddUser makes a person, and SignInAs or User.Approve stands in for the person in the browser. Each sign-in issues the person a token, which Repo.GrantUser and Repo.HookManagerUsers name by login. Every API route also answers under /api/v3, as on a GitHub Enterprise Server host.\n\nAddApp returns the App, and App.SetPermissions and App.Install model what a real App may do (apps.go). Then a sign-in token through the App reads only repos the App is installed on, the API answers 403 to a call the App has no permission for, and the fake issues installation tokens to an App JWT. App.SetWebhook gives the App a webhook that Push delivers to.\n\nLoadSeed and Seed.Apply build a fake from a JSON seed file, and Seeded.Control answers a script driving it from outside the process. cmd/fakegithub serves a seeded fake as a command.\n\noneauth's outbound/githubtest mints installation tokens and user tokens for a connection, with no sign-in or repos. A test that drives a connection end to end uses both, with AcceptToken trusting the tokens the other mints.\n\n## Functions\n\n```go\nfunc LFSPointer(content string) (pointer, oid string)\n```\nLFSPointer returns the Git LFS pointer file for content, and its oid.\n\n```go\nfunc ReadDir(dir string) (map[string]string, error)\n```\nReadDir returns every file under dir by its slash path relative to dir, for Repo.Commit or AddRepo. It reads through an os.Root, so a link inside dir can't reach a file outside it.\n\n```go\nfunc SignedRequest(target string, secret []byte, event string, body []byte) *http.Request\n```\nSignedRequest builds a webhook delivery to target as GitHub sends one: a POST of body with the event name in X-GitHub-Event and X-Hub-Signature-256 set to the HMAC-SHA256 of body under secret. Serve it to an app's handler with httptest.NewRecorder, or send it with http.DefaultClient.\n\n## Types\n\n```go\ntype App struct {\n\n\t// ClientID is the App's OAuth client id, which the sign-in endpoints check.\n\tClientID string\n\n\t// ID is the App's numeric id. An App JWT names it, or ClientID, as its iss.\n\tID int64\n\t// contains filtered or unexported fields\n}\n```\nApp is a GitHub App registered on the fake. AddApp makes one.\n\nAn App starts unmodelled. Its sign-in tokens then read what the person can read, and the membership check answers them, as before Apps had permissions here. SetPermissions or Install makes it modelled. Then, as on GitHub:\n\n  - a sign-in token through the App reads a private repo only where the App is installed and the person can read it, and gets 404 on any other private repo;\n  - a repo route that reads files needs the \"contents\" permission, and a write needs \"contents\" at \"write\". Without it the API answers 403 \"Resource not accessible by integration\";\n  - GET /orgs/{org}/members/{login} needs \"members\" at \"read\" or above, with the same 403.\n\nA public repo answers any token, installed or not. GitHub always grants \"metadata\", so the fake never checks it. The hooks API checks no permission.\n\n```go\nfunc (a *App) Install(account string, repos ...string) *Installation\n```\nInstall installs the App on account, on each of repos (names without the owner), or on every repo of account when repos is empty, including repos added later. It makes the App modelled and returns the new installation.\n\n```go\nfunc (a *App) Installations() []*Installation\n```\nInstallations returns the App's installations in the order Install made them.\n\n```go\nfunc (a *App) KeyPEM() []byte\n```\nKeyPEM returns the App's private key as PKCS#1 PEM (\"RSA PRIVATE KEY\"), as GitHub hands it out.\n\n```go\nfunc (a *App) SetKey(k *rsa.PrivateKey)\n```\nSetKey sets the App's private key, which App JWTs must be signed with. Without it, the fake makes a 2048-bit key the first time it needs one.\n\n```go\nfunc (a *App) SetPermissions(perms map[string]string)\n```\nSetPermissions sets the App's permissions, such as {\"contents\": \"read\", \"members\": \"read\"}. Levels are \"read\", \"write\" and \"admin\", each including the ones before. It makes the App modelled.\n\n```go\nfunc (a *App) SetWebhook(url, secret string, events ...string)\n```\nSetWebhook sets the App's webhook. Repo.Push delivers a push to it, signed with secret, when the App is installed on the repo and events holds \"push\" or \"\\*\". The body carries the installation, as an App's webhook does.\n\n```go\ntype Hook struct {\n\tID          int64\n\tURL         string\n\tContentType string\n\tSecret      string\n\tEvents      []string\n\tActive      bool\n\tToken       string\n}\n```\nHook is a webhook made on a repo through the hooks API. Token is the token that last made or changed it, so a test can check that the app used the right connection.\n\n```go\ntype Installation struct {\n\n\t// ID names the installation in /app/installations/{id}/access_tokens and in webhooks.\n\tID int64\n\n\t// Account is the user or org login the App is installed on.\n\tAccount string\n\t// contains filtered or unexported fields\n}\n```\nInstallation is an App installed on one account, on all its repos or on a chosen list.\n\n```go\nfunc (in *Installation) PushRequest(r *Repo, target string, secret []byte, branch string) *http.Request\n```\nPushRequest builds the signed push event the App's webhook gets for branch of r, as Repo.PushRequest does, with the installation in the body.\n\n```go\nfunc (in *Installation) Repos() []string\n```\nRepos returns the names of the repos the installation lists, sorted, or nil when it covers every repo of its account.\n\n```go\ntype Option func(*options)\n```\nOption configures a fake that New starts.\n\n```go\nfunc WithBaseURL(u string) Option\n```\nWithBaseURL sets the origin the fake puts in every URL it hands out: Server.URL, RawURL, LFSURL, the LFS batch hrefs, pagination Link headers and the device flow's verification\\_uri. Use an address the app under test can reach, such as \"[http://host.docker.internal](http://host.docker.internal):\\\u003cport\u003e\". u is a scheme, a host and an optional port. New fails the test if u has a path, query or fragment. The test process itself may not resolve u, so it reaches the fake through ListenURL.\n\n```go\nfunc WithHookClient(c *http.Client) Option\n```\nWithHookClient sets the client that Repo.Push delivers webhooks with, such as one that trusts a test CA for a hook served over TLS. The default is http.DefaultClient.\n\n```go\nfunc WithListener(l net.Listener) Option\n```\nWithListener serves the fake on l instead of a fresh 127.0.0.1 port. A test whose app runs in a container listens on \"0.0.0.0:0\" or the docker bridge's gateway, so the container can reach it. The fake closes l when the test ends.\n\n```go\nfunc WithTLS(cfg *tls.Config) Option\n```\nWithTLS serves the fake over HTTPS, so URL and ListenURL start with \"https://\". cfg carries the certificate, such as one naming the address an app in a container dials. A nil cfg, or one with no certificates, gets httptest's own certificate, which Client trusts. An app that refuses a plain-HTTP GitHub Enterprise host off loopback, as oneauth's SetEnterpriseURL does, needs this.\n\n```go\ntype Repo struct {\n\tOwner   string\n\tName    string\n\tPrivate bool\n\t// contains filtered or unexported fields\n}\n```\nRepo is one repository in the fake. Its methods are safe to call while the server runs.\n\n```go\nfunc (r *Repo) AddTarEntries(sha string, es ...TarEntry)\n```\nAddTarEntries adds entries to the tarball of commit sha only. The Contents API doesn't see them.\n\n```go\nfunc (r *Repo) Commit(branch string, put map[string]string, del []string) string\n```\nCommit makes a commit on branch, creating the branch if needed. It starts from the branch's current files, sets each of put, and removes each of del. It returns the new commit's sha.\n\n```go\nfunc (r *Repo) CommitLFS(branch, p, content string) (sha, oid string)\n```\nCommitLFS commits p on branch as a Git LFS pointer to content, and keeps content as its LFS object. It returns the commit and the object's oid.\n\n```go\nfunc (r *Repo) Deliver(branch string) error\n```\nDeliver sends the push event for branch's head to the repo's hooks and to each installed App's webhook, as Push does after its commit. It returns the first delivery that fails or answers other than 2xx.\n\n```go\nfunc (r *Repo) File(branch, p string) (string, bool)\n```\nFile returns the contents of p at the head of branch.\n\n```go\nfunc (r *Repo) Grant(tokens ...string)\n```\nGrant lets each of tokens read the repo, and accepts each one as AddToken does. Once a private repo has a grant, it answers only granted tokens, and gives any other token 404, accepted or not, as GitHub does for a repo the token can't see. A private repo with no grants answers any accepted token. A public repo answers everyone either way.\n\n```go\nfunc (r *Repo) GrantUser(logins ...string)\n```\nGrantUser lets each of logins read the repo through any token they get by signing in, so the grant holds across refreshes. It limits a private repo as Grant does, and the two add up: a repo with grants of either kind answers a granted token or a granted person's token.\n\n```go\nfunc (r *Repo) Head(branch string) string\n```\nHead returns the commit sha branch points at, or \"\" for a missing branch.\n\n```go\nfunc (r *Repo) HookManagerUsers(logins ...string)\n```\nHookManagerUsers lets each of logins manage the repo's hooks through any token they get by signing in. It limits who may manage hooks as HookManagers does, and the two add up.\n\n```go\nfunc (r *Repo) HookManagers(tokens ...string)\n```\nHookManagers limits who may manage the repo's hooks to tokens, and accepts each one as AddToken does. Any other token gets 404 from the hooks API, as GitHub answers a token without admin rights on the repo. With no managers, any accepted token that can see the repo manages its hooks.\n\n```go\nfunc (r *Repo) Hooks() []Hook\n```\nHooks returns a copy of the repo's hooks, oldest first.\n\n```go\nfunc (r *Repo) Push(branch string, put map[string]string, del []string) (string, error)\n```\nPush commits put and del on branch, as Commit does, then delivers a signed push event to each active hook that wants push events, and to the webhook of each App installed on the repo that wants them (apps.go), one at a time, before it returns. GitHub delivers later and in the background; delivering first lets a test check the app's state right after Push. Each delivery is JSON, whatever the hook's content type. Push returns the new commit, and the first delivery that fails or answers other than 2xx.\n\n```go\nfunc (r *Repo) PushRequest(target string, secret []byte, branch string) *http.Request\n```\nPushRequest builds a signed push event to target for branch's head, with its parent as before, as GitHub sends after a push of one commit. It panics on a missing branch.\n\n```go\nfunc (r *Repo) SetCommitTime(sha string, t time.Time)\n```\nSetCommitTime sets commit sha's date, so a test can make the order of tags by date differ from their order by name. It panics on a sha the repo doesn't have.\n\n```go\nfunc (r *Repo) Source() string\n```\nSource returns the repo's mounts source, \"github://owner/name\".\n\n```go\nfunc (r *Repo) Symlink(branch, p, target string) string\n```\nSymlink makes a commit on branch adding a link at p to target.\n\n```go\nfunc (r *Repo) Tag(name, sha string, annotated bool)\n```\nTag points the tag name at commit sha, replacing any tag of that name. An annotated tag is served as GitHub serves one, through a tag object. It panics on a sha the repo doesn't have.\n\n```go\ntype Request struct {\n\tMethod string\n\tPath   string\n\n\t// Token is the bearer or \"token\" credential the request carried, or \"\" for none.\n\tToken string\n}\n```\nRequest is one request the fake answered.\n\n```go\ntype Seed struct {\n\tApp    *SeedApp   `json:\"app\"`\n\tUsers  []SeedUser `json:\"users\"`\n\tTokens []string   `json:\"tokens\"`\n\tRepos  []SeedRepo `json:\"repos\"`\n\n\t// Dir is where a relative dir or key_file is read from. LoadSeed sets it to the seed file's\n\t// folder.\n\tDir string `json:\"-\"`\n}\n```\nSeed describes a fake GitHub Enterprise Server: people, an App, fixed tokens and repos with tagged commits. LoadSeed reads one from a JSON file, and Apply builds it on a fake. The JSON is:\n\n\t{\n\t  \"app\":    {\"client_id\": \"Iv1.exercise\", \"client_secret\": \"...\",\n\t             \"key_file\": \"app.pem\",\n\t             \"permissions\": {\"contents\": \"read\", \"members\": \"read\"},\n\t             \"installations\": [{\"account\": \"hw\", \"repos\": [\"baseboard\"]}],\n\t             \"webhook\": {\"url\": \"https://app.test/hooks/github\", \"secret\": \"...\", \"events\": [\"push\"]}},\n\t  \"users\":  [{\"login\": \"alice\", \"orgs\": [\"acme\"]}],\n\t  \"tokens\": [\"server-token\"],\n\t  \"repos\":  [{\"repo\": \"hw/baseboard\", \"private\": true, \"readers\": [\"alice\"],\n\t              \"tokens\": [\"server-token\"],\n\t              \"commits\": [{\"tag\": \"rev-b\", \"dir\": \"rev-b\", \"lfs\": [\"board.kicad_pcb\"]}]}]\n\t}\n\nEverything is optional except each repo's name and at least one commit. The App's permissions, installations and webhook model it as App describes. Without them the App only signs people in. Without key\\_file, the fake makes the App's key, and Seeded.Control's GET / hands it out.\n\nEach commit replaces the files on main with dir's, and tags the commit when tag is set. A relative dir or key\\_file is read beside the seed file. A commit's lfs lists paths in dir that go in as Git LFS pointers, with their contents kept as LFS objects and a .gitattributes line each. readers are the logins a repo is granted to, and tokens are fixed tokens it is granted to, such as a server connection's.\n\n```go\nfunc LoadSeed(path string) (*Seed, error)\n```\nLoadSeed reads the seed file at path. A field the format doesn't have is an error, so a typo doesn't pass unnoticed.\n\n```go\nfunc (sd *Seed) Apply(s *Server) (*Seeded, error)\n```\nApply builds sd on s and returns it. It fails on a repo without owner/name or commits, a missing dir, an lfs path that isn't in its dir, or an unreadable key\\_file.\n\n```go\ntype SeedApp struct {\n\tClientID      string             `json:\"client_id\"`\n\tClientSecret  string             `json:\"client_secret\"`\n\tKeyFile       string             `json:\"key_file\"`\n\tPermissions   map[string]string  `json:\"permissions\"`\n\tInstallations []SeedInstallation `json:\"installations\"`\n\tWebhook       *SeedWebhook       `json:\"webhook\"`\n}\n```\nSeedApp is a Seed's GitHub App.\n\n```go\ntype SeedCommit struct {\n\tTag string   `json:\"tag\"`\n\tDir string   `json:\"dir\"`\n\tLFS []string `json:\"lfs\"`\n}\n```\nSeedCommit is one commit to main: dir's files, tagged Tag when set, with LFS's paths as LFS pointers.\n\n```go\ntype SeedInstallation struct {\n\tAccount string   `json:\"account\"`\n\tRepos   []string `json:\"repos\"`\n}\n```\nSeedInstallation installs the App on Account, on Repos (names without the owner), or on every repo of Account when Repos is empty.\n\n```go\ntype SeedRepo struct {\n\tRepo    string       `json:\"repo\"`\n\tPrivate bool         `json:\"private\"`\n\tReaders []string     `json:\"readers\"`\n\tTokens  []string     `json:\"tokens\"`\n\tCommits []SeedCommit `json:\"commits\"`\n}\n```\nSeedRepo is a repo and its history on main.\n\n```go\ntype SeedUser struct {\n\tLogin string   `json:\"login\"`\n\tOrgs  []string `json:\"orgs\"`\n}\n```\nSeedUser is a person who can sign in, a member of each of Orgs.\n\n```go\ntype SeedWebhook struct {\n\tURL    string   `json:\"url\"`\n\tSecret string   `json:\"secret\"`\n\tEvents []string `json:\"events\"`\n}\n```\nSeedWebhook is the App's webhook. App.SetWebhook says when a push reaches it.\n\n```go\ntype Seeded struct {\n\tServer *Server\n\n\t// App is the seed's App, or nil.\n\tApp *App\n\t// contains filtered or unexported fields\n}\n```\nSeeded is a fake built from a Seed. Its methods are safe to call while the fake serves.\n\n```go\nfunc (e *Seeded) Commits() map[string]map[string]string\n```\nCommits returns each repo's tags and the commits they name, as {\"hw/baseboard\": {\"rev-b\": sha}}.\n\n```go\nfunc (e *Seeded) Control() http.Handler\n```\nControl answers requests that play GitHub's other side, for a script driving the fake from outside the process:\n\n\tGET  /         {\"web\": ..., \"api\": \".../api/v3\", \"raw\": \".../raw\", \"commits\": {\"hw/baseboard\": {\"rev-b\": \"\u003csha\u003e\"}},\n\t                \"app\": {\"id\": 1, \"client_id\": ..., \"key_pem\": ..., \"installations\": [{\"id\": 1, \"account\": \"hw\", \"repos\": [...]}]}}\n\tPOST /approve  login=alice\u0026code=ABCD-1234: alice types the device code and approves the App\n\tPOST /push     repo=...\u0026branch=main\u0026dir=...[\u0026hook=\u003curl\u003e\u0026secret=\u003csecret\u003e]: commit dir's files to\n\t               branch, deliver the push to the repo's hooks and the App's webhook, then to hook\n\n\"app\" is there only when the seed has one. /push answers {\"sha\": \"\\\u003cnew commit\u003e\", \"status\": \\\u003chook's HTTP status, or 0\u003e}, or 502 when a delivery fails.\n\n```go\nfunc (e *Seeded) Replace(name, dir string) (string, error)\n```\nReplace commits dir's files to main of the seeded repo name, deleting the files the last commit had that dir doesn't, and returns the new commit. It delivers nothing; Repo.Deliver does.\n\n```go\nfunc (e *Seeded) Repo(name string) *Repo\n```\nRepo returns the seeded repo named \"owner/name\", or nil.\n\n```go\nfunc (e *Seeded) User(login string) *User\n```\nUser returns the seeded person with login, or nil.\n\n```go\ntype Server struct {\n\t*httptest.Server\n\t// contains filtered or unexported fields\n}\n```\nServer is the fake. Its URL is the API base a driver is pointed at, and the origin of every URL the fake hands out.\n\n```go\nfunc New(t testing.TB, opts ...Option) *Server\n```\nNew starts a fake and stops it when the test ends. With no options it listens on a fresh 127.0.0.1 port, and URL is that address.\n\n```go\nfunc (s *Server) AcceptToken(f func(token string) bool)\n```\nAcceptToken also accepts any token f approves, such as one oneauth's fake minted (its ValidInstallationToken or ValidUserToken).\n\n```go\nfunc (s *Server) AddApp(clientID, clientSecret string) *App\n```\nAddApp registers a GitHub App's OAuth client and returns the App. The sign-in endpoints answer only a registered client, and give any other client id, or a wrong secret, GitHub's incorrect\\_client\\_credentials error. Registering a client id again replaces its secret and keeps the App.\n\n```go\nfunc (s *Server) AddRepo(owner, name string, private bool, files map[string]string) *Repo\n```\nAddRepo creates owner/name with one commit on branch \"main\" holding files, and returns it.\n\n```go\nfunc (s *Server) AddToken(tok string)\n```\nAddToken makes tok an accepted token.\n\n```go\nfunc (s *Server) AddUser(login string, orgs ...string) *User\n```\nAddUser makes a person who can sign in, a member of each of orgs. Each sign-in issues the person a new access token and refresh token, and the fake accepts the access token as AddToken does, until ExpireTokens or a refresh retires it. Repo.GrantUser and Repo.HookManagerUsers name the person, so a grant holds across refreshes.\n\n```go\nfunc (s *Server) CorruptLFS(on bool)\n```\nCorruptLFS makes each object download with one byte added, so a test can check that a driver refuses bytes that don't match the pointer.\n\n```go\nfunc (s *Server) CorruptRaw(on bool)\n```\nCorruptRaw makes the raw host and the git blobs endpoint send each file with one byte added, so a test can check that a driver refuses bytes that don't match their git blob id.\n\n```go\nfunc (s *Server) ExpireTokens(login string)\n```\nExpireTokens ends every access token issued to login, so each one gets 401 Bad credentials, as GitHub answers an expired token. The person's refresh tokens still work, so a test can watch the app refresh. A token given to AddToken or Grant is unaffected.\n\n```go\nfunc (s *Server) FailLFS(status int, message string)\n```\nFailLFS makes the next batch request answer with status and message, such as 403 with GitHub's quota message.\n\n```go\nfunc (s *Server) FailNext(status int)\n```\nFailNext makes the next request answer with status and no body, then serve normally. 403 sets x-ratelimit-remaining to 0, as GitHub's rate limit does.\n\n```go\nfunc (s *Server) LFSURL() string\n```\nLFSURL is the web host whose \"/{owner}/{repo}.git/info/lfs/objects/batch\" serves the LFS batch API. Point a driver at it with WithLFSURL.\n\n```go\nfunc (s *Server) ListenURL() string\n```\nListenURL is the address the fake listens on, as \"[http://host:port](http://host:port)\", or \"[https://host:port](https://host:port)\" with WithTLS. It equals URL unless WithBaseURL set another origin.\n\n```go\nfunc (s *Server) RawURL() string\n```\nRawURL is the fake's raw host, which serves a file by owner, repo, commit and path as raw.githubusercontent.com does. Point a driver at it with WithRawURL.\n\n```go\nfunc (s *Server) RemoveLFSObject(oid string)\n```\nRemoveLFSObject deletes an object, so the batch API reports it missing.\n\n```go\nfunc (s *Server) Requests() []Request\n```\nRequests returns every request answered so far, oldest first.\n\n```go\nfunc (s *Server) SetDeviceInterval(d time.Duration)\n```\nSetDeviceInterval sets how often a device-flow client may poll, for device codes issued after the call. GitHub's interval is five seconds. The fake's default is one second, so a test that waits through DeviceAccessToken runs quickly.\n\n```go\nfunc (s *Server) SignInAs(login string)\n```\nSignInAs makes the web flow's authorize step sign in as login, as if that person were signed in to GitHub in the browser and approved the app. Until a test calls it, authorize redirects back with error=access\\_denied. It panics on a login AddUser didn't make.\n\n```go\ntype TarEntry struct {\n\tName     string // relative to the tarball's top folder\n\tType     byte   // tar.TypeReg, tar.TypeSymlink, ...\n\tBody     string\n\tLinkname string\n}\n```\nTarEntry is an extra entry a test adds to a commit's tarball, such as a link or a path that climbs out, to check that a driver refuses it.\n\n```go\ntype User struct {\n\tLogin string\n\tID    int64\n\n\t// Name and Email are what /user answers. AddUser sets Name to Login and leaves Email empty,\n\t// which /user answers as null, as GitHub does for a private email.\n\tName  string\n\tEmail string\n\t// contains filtered or unexported fields\n}\n```\nUser is a person who can sign in to the fake. AddUser makes one.\n\n```go\nfunc (u *User) Approve(userCode string) bool\n```\nApprove stands in for the person typing userCode at the verification URL and approving the app. The next poll for that device code gets a token for u. It reports false for a user code the fake didn't issue or one already used.\n\n","path":"github.com/panyam/goapplib/storage/mounts/github/githubtest","name":"githubtest","synopsis":"Package githubtest is a fake GitHub for tests of code that reads and writes repos: the mounts GitHub driver, the storage example app, and consumers' own tests.","isRedistributable":true}
