Help us shape the future of Go! Take the 2026 Go Developer Survey

gitlabtest

package
v4.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package gitlabtest is an in-memory GitLab behind httptest, for tests.

It serves the REST paths the client uses and models the platform facts of docs/architecture.md §2 the server depends on: 404 for a private project, the catch-all route shape, offset and keyset pagination with their edges, 429 in both body shapes, a moved project, OAuth with immediately rotating refresh tokens, and quick actions run from a note. Everything in it is generated (§9.1).

Index

Constants

View Source
const (
	// BoardDevelopment is alpha's unscoped board, with a list of every
	// kind and positions GitLab's order does not follow.
	BoardDevelopment = 98001
	// BoardSprint is scoped to a milestone, a label and a weight, and
	// hides its Closed list.
	BoardSprint = 98002
	// BoardUpcoming is scoped to GitLab's Upcoming filter, an assignee
	// and no weight.
	BoardUpcoming = 98003
	// IterationID is the iteration a list names.
	IterationID = 98100
)

Board ids a test can state literally.

View Source
const (
	// PipelineFailed is a failed pipeline on ProjectAlpha's main.
	PipelineFailed = 61001
	// JobPassed passed; JobFailed failed its script and has a long log
	// with the synthetic token in it; JobAllowed failed and was allowed
	// to; JobManual waits for a person.
	JobPassed  = 70001
	JobFailed  = 70002
	JobAllowed = 70003
	JobManual  = 70004
	// BridgeFailed is a trigger job on PipelineFailed whose downstream
	// pipeline, DownstreamFailed, failed.
	BridgeFailed     = 79001
	DownstreamFailed = 62001
	// FakeToken is the synthetic token JobFailed's log prints.
	FakeToken = "glpat-" + "EXAMPLE0000000000000000000"
	// LogFiller is how many lines of test output JobFailed's log holds,
	// enough to be longer than one default window.
	LogFiller = 2500
)

Fixture CI ids tests address.

View Source
const (
	// ProjectAlpha is public; alice maintains it. It has issues, merge
	// requests, discussions, files, branches and commits.
	ProjectAlpha = "example-group/alpha"
	// ProjectBeta is private under a subgroup; alice is a member.
	ProjectBeta = "example-group/sub/beta"
	// ProjectSecret is private and alice is not a member, so it answers
	// 404 exactly as a missing project does.
	ProjectSecret = "example-group/secret"
	// ProjectMoved is the old path of ProjectAlpha: a GET redirects, any
	// other method is 405.
	ProjectMoved = "example-group/old-alpha"
	// GroupTop and GroupSub are the two groups.
	GroupTop = "example-group"
	GroupSub = "example-group/sub"
	// DefaultUser is who a default token and an authorization act as.
	DefaultUser = "alice"
)

Fixture names tests address.

View Source
const (

	// DeletedLabelID is a label alpha's first issue carried and that was
	// deleted since.
	DeletedLabelID = 96999

	// SecretLabel is ProjectSecret's label, which alpha's first issue
	// once carried and alice cannot read.
	SecretLabel = "secret-label"
)

Ids a test can state literally: event ids, and the label and milestone a seeded event names that no longer exist.

View Source
const (
	// MilestoneActive and MilestoneClosed are ProjectAlpha's; the group
	// milestone is GroupTop's.
	MilestoneActive = 90001
	MilestoneClosed = 90002
	MilestoneGroup  = 90003
	// GroupLabel is a label GroupTop defines for every project under it.
	GroupLabel = "group-wide"
	// TodoAssigned, TodoReview and TodoDone are alice's to-do items.
	TodoAssigned = 95001
	TodoReview   = 95002
	TodoDone     = 95003
)

Fixture ids tests address.

View Source
const (
	TagRelease = "v1.0"
	TagPlain   = "v0.9"
)

Tags on ProjectAlpha: an annotated, protected tag with a release on release/1.0's head, and a lightweight one on main's head.

View Source
const (
	// ReportFailures is how many cases failed in JobFailed's report,
	// each with a long output, so the failures fill more than one
	// budget. One errored case comes on top.
	ReportFailures = 24
	// ReportSuiteError is the message for JobAllowed's report, which
	// GitLab could not parse.
	ReportSuiteError = "JUnit XML parsing failed: 1:1: FATAL: Document is empty."
)

Fixture test report sizes tests address.

View Source
const (
	// SnippetAlpha is bob's snippet in ProjectAlpha, two files long.
	SnippetAlpha = 80001
	// SnippetPersonal is alice's private personal snippet.
	SnippetPersonal = 80002
	// WikiNested is a wiki page whose slug holds a slash.
	WikiNested = "guides/setup"
)

Fixture ids and names tests address.

View Source
const ClientID = "gitlabtest-application-id"

ClientID is the OAuth application's id.

View Source
const ConflictSHA = "c0ffee0000000000000000000000000000000000"

ConflictSHA is a commit whose cherry-pick or revert conflicts on every branch.

Variables

View Source
var Users = []string{"alice", "bob", "carol", "dave"}

Users is the synthetic user list, in id order from 1001.

Functions

This section is empty.

Types

type Fault

type Fault struct {
	Method string
	Path   string
	Times  int
	Status int
	Header http.Header
	Body   string
	// Delay holds the answer before its headers are written.
	Delay time.Duration
	// StallAfter writes the headers and part of Body, then waits this
	// long before the rest.
	StallAfter time.Duration
	// AfterApply serves the request first, so a write lands, then
	// discards that answer and sends the fault's: the answer to a write
	// that succeeded was lost.
	AfterApply bool
	// Query, when set, limits the fault to requests whose raw query
	// contains it, such as "page=2&".
	Query string
	// Pass serves the request as usual after Delay: a slow answer, not
	// a wrong one.
	Pass bool
	// Skip lets that many matching requests through before the fault
	// applies, to fail a later read of the same path.
	Skip int
	// Before runs as the request arrives, before it is served: a change
	// made elsewhere between a client's read and its write.
	Before func()
}

Fault is an injected answer. It replaces the next Times requests whose method (empty for any) and escaped path under /api/v4 (prefix match, "/projects" matches "/projects/2001/issues") match; "/graphql" is the GraphQL endpoint.

func Application429

func Application429(path string, retryAfter, times int) Fault

Application429 is an application limit's 429: JSON, with Retry-After and no RateLimit-* headers.

func RackAttack429

func RackAttack429(path string, retryAfter, times int) Fault

RackAttack429 is the instance throttle's 429: a plain-text body with Retry-After and RateLimit-* headers.

type Options

type Options struct {
	// TotalLimit is the count past which X-Total and X-Total-Pages are
	// dropped. GitLab's is 10,000; a test sets a small one.
	TotalLimit int
	// OffsetCap is the offset past which an endpoint with keyset
	// pagination answers 405. GitLab's is 50,000.
	OffsetCap int
	// ExtraProjects adds public projects example-group/bulk-0001… for
	// paging tests.
	ExtraProjects int
	// AlphaIssues, AlphaMergeRequests and AlphaCommits size ProjectAlpha.
	// Defaults 25, 3 and 30.
	AlphaIssues        int
	AlphaMergeRequests int
	AlphaCommits       int
	// Version and Enterprise are what /metadata reports. Default
	// "19.4.0", Community Edition.
	Version    string
	Enterprise bool

	// Confidential makes the OAuth application confidential: the token
	// endpoint then refuses a request without ClientSecret.
	Confidential bool
	ClientSecret string
	// RedirectURIs are the application's registered redirect URIs.
	// Default http://127.0.0.1/callback.
	RedirectURIs []string
	// AuthorizeAs is the user an authorization signs in as. Default alice.
	AuthorizeAs string
	// AccessTokenTTL is expires_in. Default 7,200 s.
	AccessTokenTTL time.Duration
	// Now is the clock. Default time.Now.
	Now func() time.Time
	// MoveDropsQuery makes the redirect for a moved project carry the
	// new path without the request's query string.
	MoveDropsQuery bool
	// ExternalTracker gives ProjectAlpha an external issue tracker whose
	// issues are named like EXT-7.
	ExternalTracker bool
}

Options shape the instance. Zero values take the defaults.

type Request

type Request struct {
	Method        string
	EscapedPath   string
	RawQuery      string
	Authorization string
	UserAgent     string
	// IfUnmodifiedSince is the header a conditional delete sends.
	IfUnmodifiedSince string
}

Request is one request the instance received.

type Server

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

Server is the in-memory instance. URL is its base, and the instance to configure is that URL.

func New

func New(t testing.TB, opts Options) *Server

New starts an instance and stops it when the test ends.

func (*Server) AddBoards

func (s *Server) AddBoards(projectPath string, n int) bool

AddBoards gives a project n more boards, each with a list for each of its labels, so a listing pages and meets its budget. It reports whether the project exists.

func (*Server) AddChildPipeline

func (s *Server) AddChildPipeline(projectPath string, parent int64, status string) int64

AddChildPipeline starts a child pipeline of parent in the same project, by a trigger job, and returns its id.

func (*Server) AddDraft

func (s *Server) AddDraft(projectPath string, iid int64, user string, d gitlab.DraftNote) (int64, bool)

AddDraft plants a draft by user, as one written in GitLab's web view.

func (*Server) AddLabelEvents

func (s *Server) AddLabelEvents(projectPath, kind string, iid int64, n int) bool

AddLabelEvents adds n label events to an issue (kind "issue") or a merge request (kind "mr"), an hour apart from the hour after its newest event, adding and removing the label docs in turn.

func (*Server) AddLabelEventsFor

func (s *Server) AddLabelEventsFor(projectPath, kind string, iid int64, n int, label string) bool

AddLabelEventsFor is AddLabelEvents with a label named by the instance's first label of that name, in any project.

func (*Server) AddMergeRequest

func (s *Server) AddMergeRequest(projectPath, title, author string) (int64, bool)

AddMergeRequest opens a merge request from a new branch at the project's main, by author, and returns its iid.

func (*Server) AddMergeRequestBlocks

func (s *Server) AddMergeRequestBlocks(projectPath string, blocked int64, blocking ...int64) bool

AddMergeRequestBlocks makes a merge request of a project wait for others of the same project, as many POST …/blocks would.

func (*Server) AddStateEvent

func (s *Server) AddStateEvent(projectPath, kind string, iid int64, state string, at time.Time) bool

AddStateEvent adds a state event to an issue (kind "issue") or a merge request (kind "mr") at a given time.

func (*Server) AddSuggestion

func (s *Server) AddSuggestion(projectPath string, iid int64, author, path string, from, to int, replacement string) (int64, int64, bool)

AddSuggestion adds a diff thread by author on a merge request, on path at the merge request's head, whose comment suggests replacement for lines from to to of the source branch's file. It returns the comment's and the suggestion's ids.

func (*Server) AddTestJob

func (s *Server) AddTestJob(projectPath string, pipeline int64, name, status string, cases []gitlab.TestCase) int64

AddTestJob adds a finished job with a JUnit report to a pipeline and returns its id.

func (*Server) ApplySuggestionAs

func (s *Server) ApplySuggestionAs(user string, id int64) bool

ApplySuggestionAs applies a suggestion as user does in GitLab's page, with GitLab's default message; it reports whether it did.

func (*Server) Approvals

func (s *Server) Approvals(projectPath string, iid int64, user string) (gitlab.Approvals, bool)

Approvals is a merge request's approvals as user sees them.

func (*Server) BranchHead

func (s *Server) BranchHead(projectPath, branch string) (gitlab.Commit, bool)

BranchHead returns a branch's head commit.

func (*Server) Comment

func (s *Server) Comment(projectPath, kind string, iid int64, user, body string) (gitlab.Note, bool)

Comment plants a comment by user on an issue (kind "issue") or a merge request (kind "mr"), as content someone else wrote. It runs no quick action: it is a fixture, not a write through the API.

func (*Server) Discussions

func (s *Server) Discussions(projectPath, kind string, iid int64) []gitlab.Discussion

Discussions returns a copy of an issue's (kind "issue") or a merge request's (kind "mr") discussions.

func (*Server) Drafts

func (s *Server) Drafts(projectPath string, iid int64) []gitlab.DraftNote

Drafts returns a copy of every draft on a merge request, whoever wrote it.

func (*Server) DropDraft

func (s *Server) DropDraft(projectPath string, iid, id int64) bool

DropDraft deletes a draft as GitLab does when it publishes one whose comment does not save, for a test to stage that loss.

func (*Server) EditDraft

func (s *Server) EditDraft(projectPath string, iid, id int64, note string) bool

EditDraft changes a draft's text, as its author would in GitLab.

func (*Server) EditWikiPage

func (s *Server) EditWikiPage(projectPath, slug, content string) bool

EditWikiPage changes a page's content, as an edit made elsewhere does.

func (*Server) FileAt

func (s *Server) FileAt(projectPath, branch, path string) (string, bool)

FileAt returns a file's content on a branch.

func (*Server) Inject

func (s *Server) Inject(f Fault)

Inject adds a fault.

func (*Server) Issue

func (s *Server) Issue(projectPath string, iid int64) (gitlab.Issue, bool)

Issue returns a copy of an issue, for a test to check what a write did.

func (s *Server) IssueLinks() int

IssueLinks counts the links the instance holds.

func (*Server) Job

func (s *Server) Job(projectPath string, id int64) (gitlab.Job, bool)

Job is a job as the instance holds it.

func (*Server) JobInputsSent

func (s *Server) JobInputsSent() map[string]any

JobInputsSent are the input values the last job retry or play sent.

func (*Server) LockDiscussion

func (s *Server) LockDiscussion(projectPath, kind string, iid int64) bool

LockDiscussion locks an item's discussion, as discussion_locked does.

func (*Server) MakeInternal

func (s *Server) MakeInternal(projectPath, kind string, iid, noteID int64) bool

MakeInternal marks a comment internal: only Planner and up read it.

func (*Server) MergeRequest

func (s *Server) MergeRequest(projectPath string, iid int64) (gitlab.MergeRequest, bool)

MergeRequest returns a copy of a merge request, for a test to check what a write did.

func (*Server) MergeRequestBlocks

func (s *Server) MergeRequestBlocks() int

MergeRequestBlocks counts the merge request dependencies the instance holds.

func (*Server) PendingTodos

func (s *Server) PendingTodos(user string) []int64

PendingTodos returns the ids of user's pending to-do items.

func (*Server) Pipeline

func (s *Server) Pipeline(projectPath string, id int64) (gitlab.PipelineDetail, bool)

Pipeline is a pipeline as the instance holds it.

func (*Server) ProjectID

func (s *Server) ProjectID(path string) int64

ProjectID returns a fixture project's numeric id.

func (*Server) PushFile

func (s *Server) PushFile(projectPath, branch, path, content string) (string, bool)

PushFile commits one file's new content to a branch, as someone else's push does, and returns the commit's sha.

func (*Server) PushTo

func (s *Server) PushTo(projectPath, branch string) (string, bool)

PushTo adds a commit to a branch, as someone else's push does.

func (*Server) React

func (s *Server) React(projectPath, kind string, iid, noteID int64, user, name string) bool

React adds user's reaction named name on an item, or on its comment noteID when that is not 0, as another user's call would.

func (*Server) Reactions

func (s *Server) Reactions(projectPath, kind string, iid, noteID int64) []string

Reactions lists the reactions on an item, or on its comment noteID when that is not 0, as "user:name", oldest first.

func (*Server) Rebase

func (s *Server) Rebase(projectPath string, iid int64) bool

Rebase rebases a merge request at once, as rebase_merge_request asks GitLab to.

func (*Server) Rebases

func (s *Server) Rebases() int

Rebases counts the rebases asked for.

func (*Server) Refreshes

func (s *Server) Refreshes() int

Refreshes counts refresh grants that succeeded, for a test of the cross-process lock.

func (*Server) Release

func (s *Server) Release(projectPath, tag string) (gitlab.Release, bool)

Release is a project's release of a tag.

func (*Server) Reply

func (s *Server) Reply(projectPath string, iid int64, discussionID, user, body string) (gitlab.Note, bool)

Reply plants a reply by user in a merge request's thread, as content someone wrote. It runs no quick action.

func (*Server) Requests

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

Requests returns what the instance received so far.

func (*Server) ResetRequests

func (s *Server) ResetRequests()

ResetRequests forgets the recorded requests.

func (*Server) ReviewerState

func (s *Server) ReviewerState(projectPath string, iid int64, user string) string

ReviewerState is the reviewer state a user last submitted with a review of a merge request, "" for none.

func (*Server) Revoke

func (s *Server) Revoke(token string)

Revoke revokes an access or refresh token.

func (*Server) SetAllowCollaboration

func (s *Server) SetAllowCollaboration(projectPath string, iid int64, on bool) bool

SetAllowCollaboration lets the target project's developers push to a fork merge request's source branch, as its author allows.

func (*Server) SetAutoMRPipelines

func (s *Server) SetAutoMRPipelines(projectPath string, on bool) bool

SetAutoMRPipelines makes a project's CI give merge requests pipelines of their own, which GitLab starts when one opens and on each push to its source branch, as the live run's workflow rule does.

func (*Server) SetAutoMerge

func (s *Server) SetAutoMerge(projectPath string, iid int64, user string) bool

SetAutoMerge sets a merge request to merge when its pipeline succeeds, as user, as a merge with auto_merge does while the pipeline runs.

func (*Server) SetDraftPosition

func (s *Server) SetDraftPosition(projectPath string, iid, id int64, pos *gitlab.Position) bool

SetDraftPosition replaces a draft's position, as GitLab may hold one.

func (*Server) SetGroupPrivate

func (s *Server) SetGroupPrivate(path string) bool

SetGroupPrivate makes a group private.

func (*Server) SetHeadPipelineStatus

func (s *Server) SetHeadPipelineStatus(projectPath string, iid int64, status string) bool

SetHeadPipelineStatus sets the status of a merge request's head pipeline, as CI running or failing does.

func (*Server) SetIssuesAccess

func (s *Server) SetIssuesAccess(projectPath, level string) bool

SetIssuesAccess sets who sees a project's issues: enabled, private or disabled.

func (*Server) SetJobLog

func (s *Server) SetJobLog(projectPath string, id int64, status, log string, archived bool) bool

SetJobLog replaces a job's log and state. An archived log is also a trace artifact of its size, as GitLab lists one once it archives the log.

func (*Server) SetMRDiffs

func (s *Server) SetMRDiffs(projectPath string, iid int64, diffs []gitlab.Diff) bool

SetMRDiffs replaces the files a merge request changes.

func (*Server) SetMRSourceProject

func (s *Server) SetMRSourceProject(projectPath string, iid int64, sourcePath string) bool

SetMRSourceProject makes a merge request come from another project, as one from a fork does.

func (*Server) SetMRState

func (s *Server) SetMRState(projectPath string, iid int64, state string) bool

SetMRState puts a merge request in a state: locked, as while GitLab merges it, or merged, which clears its auto-merge.

func (*Server) SetMediaAuth

func (s *Server) SetMediaAuth(projectPath string, on *bool) bool

SetMediaAuth sets a project's "Require authentication to view media files"; nil leaves it out of the project's answer. It reports whether the project exists.

func (*Server) SetMemberLevel

func (s *Server) SetMemberLevel(projectPath, user string, level int) bool

SetMemberLevel gives a user an access level in a project, 20 for Reporter or 30 for Developer; 0 removes the user. It reports whether the project exists.

func (*Server) SetMergePipelines

func (s *Server) SetMergePipelines(projectPath string, on bool) bool

SetMergePipelines turns merged results pipelines on or off for a project, as its setting on a Premium tier does.

func (*Server) SetMergeRequestsAccess

func (s *Server) SetMergeRequestsAccess(projectPath, level string) bool

SetMergeRequestsAccess sets who reads a project's merge requests: enabled, or private for members with the Reporter role or higher.

func (*Server) SetMergeStatus

func (s *Server) SetMergeStatus(projectPath string, iid int64, status string) bool

SetMergeStatus sets a merge request's detailed_merge_status, as GitLab's checks do.

func (*Server) SetPipelineStatus

func (s *Server) SetPipelineStatus(projectPath string, id int64, status string) bool

SetPipelineStatus sets a pipeline's status, as CI running does.

func (*Server) SetResetApprovalsOnPush

func (s *Server) SetResetApprovalsOnPush(projectPath string, on bool) bool

SetResetApprovalsOnPush turns the project's reset_approvals_on_push on or off.

func (*Server) SetSnippetVisibility

func (s *Server) SetSnippetVisibility(id int64, visibility string) bool

SetSnippetVisibility sets a snippet's visibility, as a change made in GitLab's own pages does.

func (*Server) SetSuiteError

func (s *Server) SetSuiteError(projectPath string, job int64, msg string) bool

SetSuiteError makes a job's JUnit report one GitLab could not parse, with msg as its suite error.

func (*Server) SetTestSummaryLags

func (s *Server) SetTestSummaryLags(projectPath string, lags bool) bool

SetTestSummaryLags holds back a project's test report summaries, as they are before the worker that writes them has run.

func (*Server) SnippetFiles

func (s *Server) SnippetFiles(id int64) [][2]string

SnippetFiles is a snippet's files, each its path and content, in order; nil when there is no such snippet.

func (*Server) SnippetUpdatedAt

func (s *Server) SnippetUpdatedAt(id int64) time.Time

SnippetUpdatedAt is a snippet's updated_at as kept, to the microsecond.

func (*Server) SnippetVisibility

func (s *Server) SnippetVisibility(id int64) string

SnippetVisibility is a snippet's visibility, "" when there is none.

func (*Server) Subscribed

func (s *Server) Subscribed(projectPath, kind string, iid int64, user string) bool

Subscribed reports whether user is subscribed to an issue (kind "issue") or a merge request (kind "mr"), as GitLab would answer them.

func (*Server) Suggestion

func (s *Server) Suggestion(id int64) (gitlab.Suggestion, bool)

Suggestion is a suggestion as the instance holds it.

func (*Server) TodoState

func (s *Server) TodoState(id int64) string

TodoState returns a to-do item's state, "" for an unknown one.

func (*Server) Token

func (s *Server) Token() string

Token issues an access token for alice with the api scope.

func (*Server) TokenFor

func (s *Server) TokenFor(user string, scopes ...string) string

TokenFor issues an access token for a user with the given scopes.

func (*Server) TouchNote

func (s *Server) TouchNote(projectPath, kind string, iid, noteID int64, at time.Time) bool

TouchNote moves a note's updated_at, as an edit made elsewhere does.

func (*Server) TouchSnippet

func (s *Server) TouchSnippet(id int64, at time.Time) bool

TouchSnippet moves a snippet's updated_at, as an edit made elsewhere does.

func (*Server) Uploads

func (s *Server) Uploads(projectPath string) []Upload

Uploads returns the uploads made to a project, oldest first.

func (*Server) WikiPage

func (s *Server) WikiPage(projectPath, slug string) (gitlab.WikiPage, bool)

WikiPage is a wiki page as the instance holds it.

type Upload

type Upload struct {
	ID      int64
	Project string // the project's full path
	User    string
	// Filename is the name GitLab stored, after sanitizing it.
	Filename string
	// ContentType is what the file part said it was.
	ContentType string
	Secret      string
	Data        []byte
}

Upload is a file an account uploaded to a project.

Jump to

Keyboard shortcuts

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