Movatterモバイル変換


[0]ホーム

URL:


coderdtest

package
v2.23.0Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License:AGPL-3.0Imports:96Imported by:0

Details

Repository

github.com/coder/coder

Links

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FirstUserParams =codersdk.CreateFirstUserRequest{Email:    "testuser@coder.com",Username: "testuser",Password: "SomeSecurePassword!",Name:     "Test User",}
View Source
var TrialUserParams =codersdk.CreateFirstUserTrialInfo{FirstName:   "John",LastName:    "Doe",PhoneNumber: "9999999999",JobTitle:    "Engineer",CompanyName: "Acme Inc",Country:     "United States",Developers:  "10-50",}

Functions

funcAccessControlStorePointeradded inv2.5.1

func AccessControlStorePointer() *atomic.Pointer[dbauthz.AccessControlStore]

funcAgentsNotReadyadded inv2.22.0

func AgentsNotReady(agentcodersdk.WorkspaceAgent)bool

AgentsNotReady checks that the latest lifecycle state of an agent is anything except "Ready".

funcAgentsReadyadded inv2.22.0

func AgentsReady(agentcodersdk.WorkspaceAgent)bool

AgentsReady checks that the latest lifecycle state of an agent is "Ready".

funcAuthzUserSubjectadded inv2.5.0

func AuthzUserSubject(usercodersdk.User, orgIDuuid.UUID)rbac.Subject

AuthzUserSubject does not include the user's groups.

funcAwaitTemplateVersionJobCompletedadded inv2.2.1

func AwaitTemplateVersionJobCompleted(ttesting.TB, client *codersdk.Client, versionuuid.UUID)codersdk.TemplateVersion

AwaitTemplateVersionJobCompleted waits for the build to be completed. This may resultfrom cancelation, an error, or from completing successfully.

funcAwaitTemplateVersionJobRunningadded inv2.3.0

func AwaitTemplateVersionJobRunning(ttesting.TB, client *codersdk.Client, versionuuid.UUID)codersdk.TemplateVersion

AwaitTemplateVersionJobRunning waits for the build to be picked up by a provisioner.

funcAwaitWorkspaceAgentsdeprecated

func AwaitWorkspaceAgents(ttesting.TB, client *codersdk.Client, workspaceIDuuid.UUID, agentNames ...string) []codersdk.WorkspaceResource

AwaitWorkspaceAgents waits for all resources with agents to be connected. Ifspecific agents are provided, it will wait for those agents to be connectedbut will not fail if other agents are not connected.

Deprecated: Use NewWorkspaceAgentWaiter

funcAwaitWorkspaceBuildJobCompletedadded inv2.2.1

func AwaitWorkspaceBuildJobCompleted(ttesting.TB, client *codersdk.Client, builduuid.UUID)codersdk.WorkspaceBuild

AwaitWorkspaceBuildJobCompleted waits for a workspace provision job to reach completed status.

funcCreateAnotherUser

func CreateAnotherUser(ttesting.TB, client *codersdk.Client, organizationIDuuid.UUID, roles ...rbac.RoleIdentifier) (*codersdk.Client,codersdk.User)

CreateAnotherUser creates and authenticates a new user.Roles can include org scoped roles with 'roleName:<organization_id>'

funcCreateAnotherUserMutators

func CreateAnotherUserMutators(ttesting.TB, client *codersdk.Client, organizationIDuuid.UUID, roles []rbac.RoleIdentifier, mutators ...func(r *codersdk.CreateUserRequestWithOrgs)) (*codersdk.Client,codersdk.User)

funcCreateFirstUser

func CreateFirstUser(ttesting.TB, client *codersdk.Client)codersdk.CreateFirstUserResponse

CreateFirstUser creates a user with preset credentials and authenticateswith the passed in codersdk client.

funcCreateGroupadded inv2.4.0

func CreateGroup(ttesting.TB, client *codersdk.Client, organizationIDuuid.UUID, namestring, members ...codersdk.User)codersdk.Group

CreateGroup creates a group with the given name and members.

funcCreateTemplate

func CreateTemplate(ttesting.TB, client *codersdk.Client, organizationuuid.UUID, versionuuid.UUID, mutators ...func(*codersdk.CreateTemplateRequest))codersdk.Template

CreateTemplate creates a template with the "echo" provisioner forcompatibility with testing. The name assigned is randomly generated.

funcCreateTemplateVersion

func CreateTemplateVersion(ttesting.TB, client *codersdk.Client, organizationIDuuid.UUID, res *echo.Responses, mutators ...func(*codersdk.CreateTemplateVersionRequest))codersdk.TemplateVersion

CreateTemplateVersion creates a template import provisioner jobwith the responses provided. It uses the "echo" provisioner for compatibilitywith testing.

funcCreateWorkspace

func CreateWorkspace(ttesting.TB, client *codersdk.Client, templateIDuuid.UUID, mutators ...func(*codersdk.CreateWorkspaceRequest))codersdk.Workspace

CreateWorkspace creates a workspace for the user and template provided.A random name is generated for it.To customize the defaults, pass a mutator func.

funcCreateWorkspaceBuild

func CreateWorkspaceBuild(t *testing.T,client *codersdk.Client,workspacecodersdk.Workspace,transitiondatabase.WorkspaceTransition,mutators ...func(*codersdk.CreateWorkspaceBuildRequest),)codersdk.WorkspaceBuild

CreateWorkspaceBuild creates a workspace build for the given workspace and transition.

funcMustTransitionWorkspace

func MustTransitionWorkspace(ttesting.TB, client *codersdk.Client, workspaceIDuuid.UUID, from, todatabase.WorkspaceTransition, muts ...func(req *codersdk.CreateWorkspaceBuildRequest))codersdk.Workspace

TransitionWorkspace is a convenience method for transitioning a workspace from one state to another.

funcMustWorkspace

func MustWorkspace(ttesting.TB, client *codersdk.Client, workspaceIDuuid.UUID)codersdk.Workspace

MustWorkspace is a convenience method for fetching a workspace that should exist.

funcNew

func New(ttesting.TB, options *Options) *codersdk.Client

New constructs a codersdk client connected to an in-memory API instance.

funcNewAWSInstanceIdentity

func NewAWSInstanceIdentity(ttesting.TB, instanceIDstring) (awsidentity.Certificates, *http.Client)

NewAWSInstanceIdentity returns a metadata client and ID token validator for fakinginstance authentication for AWS.

funcNewAzureInstanceIdentity

func NewAzureInstanceIdentity(ttesting.TB, instanceIDstring) (x509.VerifyOptions, *http.Client)

NewAzureInstanceIdentity returns a metadata client and ID token validator for fakinginstance authentication for Azure.

funcNewGoogleInstanceIdentity

func NewGoogleInstanceIdentity(ttesting.TB, instanceIDstring, expiredbool) (*idtoken.Validator, *metadata.Client)

NewGoogleInstanceIdentity returns a metadata client and ID token validator for fakinginstance authentication for Google Cloud.nolint:revive

funcNewOptions

func NewOptions(ttesting.TB, options *Options) (func(http.Handler),context.CancelFunc, *url.URL, *coderd.Options)

funcNewProvisionerDaemon

func NewProvisionerDaemon(ttesting.TB, coderAPI *coderd.API)io.Closer

NewProvisionerDaemon launches a provisionerd instance configured to workwell with coderd testing. It registers the "echo" provisioner forquick testing.

funcNewTaggedProvisionerDaemonadded inv2.13.0

func NewTaggedProvisionerDaemon(ttesting.TB, coderAPI *coderd.API, namestring, provisionerTags map[string]string, opts ...coderd.MemoryProvisionerDaemonOption)io.Closer

funcNewWithAPI

func NewWithAPI(ttesting.TB, options *Options) (*codersdk.Client,io.Closer, *coderd.API)

NewWithAPI constructs an in-memory API instance and returns a client to talk to it.Most tests never need a reference to the API, but AuthorizationTest in this module uses it.Do not expose the API or wrath shall descend upon thee.

funcNewWithDatabaseadded inv2.4.0

func NewWithDatabase(ttesting.TB, options *Options) (*codersdk.Client,database.Store)

NewWithDatabase constructs a codersdk client connected to an in-memory API instance.The database is returned to provide direct data manipulation for tests.

funcNewWithProvisionerCloser

func NewWithProvisionerCloser(ttesting.TB, options *Options) (*codersdk.Client,io.Closer)

NewWithProvisionerCloser returns a client as well as a handle to closethe provisioner. This is a temporary function while work is done tostandardize how provisioners are registered with coderd. The optionto include a provisioner is set to true for convenience.

funcRandomNameadded inv2.13.0

func RandomName(ttesting.TB)string

funcRandomRBACAction

func RandomRBACAction()policy.Action

funcRandomRBACObject

func RandomRBACObject()rbac.Object

funcRandomRBACSubject

func RandomRBACSubject()rbac.Subject

funcRandomUsernameadded inv2.3.2

func RandomUsername(ttesting.TB)string

funcRequestExternalAuthCallbackadded inv2.2.1

func RequestExternalAuthCallback(ttesting.TB, providerIDstring, client *codersdk.Client, opts ...func(*http.Request)) *http.Response

RequestExternalAuthCallback makes a request with the proper OAuth2 state cookieto the external auth callback endpoint.

funcSDKError

func SDKError(ttesting.TB, errerror) *codersdk.Error

SDKError coerces err into an SDK error.

funcUpdateActiveTemplateVersionadded inv2.3.0

func UpdateActiveTemplateVersion(ttesting.TB, client *codersdk.Client, templateID, versionIDuuid.UUID)

funcUpdateTemplateMetaadded inv2.4.0

func UpdateTemplateMeta(ttesting.TB, client *codersdk.Client, templateIDuuid.UUID, metacodersdk.UpdateTemplateMeta)codersdk.Template

UpdateTemplateMeta updates the template meta for the given template.

funcUpdateTemplateVersion

func UpdateTemplateVersion(ttesting.TB, client *codersdk.Client, organizationIDuuid.UUID, res *echo.Responses, templateIDuuid.UUID)codersdk.TemplateVersion

UpdateTemplateVersion creates a new template version with the "echo" provisionerand associates it with the given templateID.

funcVerifySwaggerDefinitions

func VerifySwaggerDefinitions(t *testing.T, router chi.Router, swaggerComments []SwaggerComment)

Types

typeActionObjectPair

type ActionObjectPair struct {Actionpolicy.ActionObjectrbac.Object}

typeAuthCall

type AuthCall struct {rbac.AuthCallErrerror// contains filtered or unexported fields}

typeAuthCallsadded inv2.21.1

type AuthCalls []AuthCall

typeDeterministicUUIDGeneratoradded inv2.16.0

type DeterministicUUIDGenerator struct {Named map[string]uuid.UUID}

DeterministicUUIDGenerator allows "naming" uuids for unit tests.An example of where this is useful, is when a tabled test referencesa UUID that is not yet known. An alternative to this would be tohard code some UUID strings, but these strings are not human friendly.

funcNewDeterministicUUIDGeneratoradded inv2.16.0

func NewDeterministicUUIDGenerator() *DeterministicUUIDGenerator

func (*DeterministicUUIDGenerator)IDadded inv2.16.0

typeFakeAccessControlStoreadded inv2.5.1

type FakeAccessControlStore struct{}

func (FakeAccessControlStore)GetTemplateAccessControladded inv2.5.1

func (FakeAccessControlStore)SetTemplateAccessControladded inv2.5.1

typeFakeAuthorizer

type FakeAuthorizer struct {ConditionalReturn func(context.Context,rbac.Subject,policy.Action,rbac.Object)error// contains filtered or unexported fields}

FakeAuthorizer is an Authorizer that will return an error based on the"ConditionalReturn" function. By default, **no error** is returned.Meaning 'FakeAuthorizer' by default will never return "unauthorized".

func (*FakeAuthorizer)AlwaysReturn

func (d *FakeAuthorizer) AlwaysReturn(errerror) *FakeAuthorizer

AlwaysReturn is the error that will be returned by Authorize.

func (*FakeAuthorizer)Authorize

func (d *FakeAuthorizer) Authorize(ctxcontext.Context, subjectrbac.Subject, actionpolicy.Action, objectrbac.Object)error

func (*FakeAuthorizer)OverrideSQLFilteradded inv2.19.0

func (d *FakeAuthorizer) OverrideSQLFilter(filterstring) *FakeAuthorizer

OverrideSQLFilter sets the SQL filter that will always be returned by CompileToSQL.

func (*FakeAuthorizer)Prepare

typeOptions

type Options struct {// AccessURL denotes a custom access URL. By default we use the httptest// server's URL. Setting this may result in unexpected behavior (especially// with running agents).AccessURL                      *url.URLAppHostnamestringAWSCertificatesawsidentity.CertificatesAuthorizerrbac.AuthorizerAzureCertificatesx509.VerifyOptionsGithubOAuth2Config             *coderd.GithubOAuth2ConfigRealIPConfig                   *httpmw.RealIPConfigOIDCConfig                     *coderd.OIDCConfigGoogleTokenValidator           *idtoken.ValidatorSSHKeygenAlgorithmgitsshkey.AlgorithmAutobuildTicker                <-chantime.TimeAutobuildStats                 chan<-autobuild.StatsAuditoraudit.AuditorTLSCertificates                []tls.CertificateExternalAuthConfigs            []*externalauth.ConfigTrialGenerator                 func(ctxcontext.Context, bodycodersdk.LicensorTrialRequest)errorRefreshEntitlements            func(ctxcontext.Context)errorTemplateScheduleStoreschedule.TemplateScheduleStoreCoordinatortailnet.CoordinatorCoordinatorResumeTokenProvidertailnet.ResumeTokenProviderHealthcheckFunc    func(ctxcontext.Context, apiKeystring) *healthsdk.HealthcheckReportHealthcheckTimeouttime.DurationHealthcheckRefreshtime.Duration// All rate limits default to -1 (unlimited) in tests if not set.APIRateLimitintLoginRateLimitintFilesRateLimitint// OneTimePasscodeValidityPeriod specifies how long a one time passcode should be valid for.OneTimePasscodeValidityPeriodtime.Duration// IncludeProvisionerDaemon when true means to start an in-memory provisionerDIncludeProvisionerDaemonboolProvisionerDaemonVersionstringProvisionerDaemonTags       map[string]stringMetricsCacheRefreshIntervaltime.DurationAgentStatsRefreshIntervaltime.DurationDeploymentValues            *codersdk.DeploymentValues// Set update check options to enable update check.UpdateCheckOptions *updatecheck.Options// Overriding the database is heavily discouraged.// It should only be used in cases where multiple Coder// test instances are running against the same database.Databasedatabase.StorePubsubpubsub.Pubsub// APIMiddleware inserts middleware before api.RootHandler, this can be// useful in certain tests where you want to intercept requests before// passing them on to the API, e.g. for synchronization of execution.APIMiddleware func(http.Handler)http.HandlerConfigSSHcodersdk.SSHConfigResponseSwaggerEndpointbool// Logger should only be overridden if you expect errors// as part of your test.Logger       *slog.LoggerStatsBatcherworkspacestats.BatcherWebpushDispatcherwebpush.DispatcherWorkspaceAppsStatsCollectorOptionsworkspaceapps.StatsCollectorOptionsAllowWorkspaceRenamesboolNewTicker                          func(durationtime.Duration) (<-chantime.Time, func())DatabaseRolluper                   *dbrollup.RolluperWorkspaceUsageTrackerFlush         chanintWorkspaceUsageTrackerTick          chantime.TimeNotificationsEnqueuernotifications.EnqueuerAPIKeyEncryptionCachecryptokeys.EncryptionKeycacheOIDCConvertKeyCachecryptokeys.SigningKeycacheClockquartz.ClockTelemetryReportertelemetry.Reporter}

typePreparedRecorder

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

PreparedRecorder is the prepared version of the RecordingAuthorizer.It records the Authorize() calls to the original recorder. If the calleruses CompileToSQL, all recording stops. This is to support parity betweenmemory and SQL backed dbs.

func (*PreparedRecorder)Authorize

func (s *PreparedRecorder) Authorize(ctxcontext.Context, objectrbac.Object)error

func (*PreparedRecorder)CompileToSQL

typeProvisionerdCloseradded inv2.14.0

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

ProvisionerdCloser wraps a provisioner daemon as an io.Closer that can be called multiple times

funcNewProvisionerDaemonCloseradded inv2.14.0

func NewProvisionerDaemonCloser(d *provisionerd.Server) *ProvisionerdCloser

func (*ProvisionerdCloser)Closeadded inv2.14.0

func (c *ProvisionerdCloser) Close()error

typeRBACAsserter

type RBACAsserter struct {Subjectrbac.SubjectRecorder *RecordingAuthorizer}

RBACAsserter is a helper for asserting that the correct RBAC checks areperformed. This struct is tied to a given user, and only authorizes callsfor this user are checked.

funcAssertRBAC

func AssertRBAC(t *testing.T, api *coderd.API, client *codersdk.Client)RBACAsserter

AssertRBAC returns an RBACAsserter for the given user. This asserter willallow asserting that the correct RBAC checks are performed for the given user.All checks that are not run against this user will be ignored.

func (RBACAsserter)AllCalls

func (aRBACAsserter) AllCalls()AuthCalls

AllCalls is for debugging. If you are not sure where calls are coming from,call this and use a debugger or print them. They have small callstackson them to help locate the 'Authorize' call.Only calls to Authorize by the given subject will be returned.Note that duplicate rbac calls are handled by the rbac.Cacher(), butwill be recorded twice. So AllCalls() returns calls regardless if theywere returned from the cached or not.

func (RBACAsserter)AssertChecked

func (aRBACAsserter) AssertChecked(t *testing.T, actionpolicy.Action, objects ...interface{})

AssertChecked will assert a given rbac check was performed. It does not careabout order of checks, or any other checks. This is useful when you do notcare about asserting every check that was performed.

func (RBACAsserter)AssertInOrder

func (aRBACAsserter) AssertInOrder(t *testing.T, actionpolicy.Action, objects ...interface{})

AssertInOrder must be called in the correct order of authz checks. If the objectsor actions are not in the correct order, the test will fail.

func (RBACAsserter)Reset

func (aRBACAsserter) Reset()RBACAsserter

Reset will clear all previously recorded authz calls.This is helpful when wanting to ignore checks run in test setup.

typeRecordingAuthorizer

type RecordingAuthorizer struct {sync.RWMutexCalled  []AuthCallWrappedrbac.Authorizer}

RecordingAuthorizer wraps any rbac.Authorizer and records all Authorize()calls made. This is useful for testing as these calls can later be asserted.

func (*RecordingAuthorizer)AllAsserted

func (r *RecordingAuthorizer) AllAsserted()error

AllAsserted returns an error if all calls to Authorize() have not beenasserted and checked. This is useful for testing to ensure that allAuthorize() calls are checked in the unit test.

func (*RecordingAuthorizer)AllCalls

func (r *RecordingAuthorizer) AllCalls(actor *rbac.Subject) []AuthCall

AllCalls is useful for debugging.

func (*RecordingAuthorizer)AssertActor

func (r *RecordingAuthorizer) AssertActor(t *testing.T, actorrbac.Subject, did ...ActionObjectPair)

AssertActor asserts in order. If the order of authz calls does not match,this will fail.

func (*RecordingAuthorizer)AssertOutOfOrder

func (r *RecordingAuthorizer) AssertOutOfOrder(t *testing.T, actorrbac.Subject, did ...ActionObjectPair)

AssertOutOfOrder asserts that the given actor performed the given actionon the given objects. It does not care about the order of the calls.When marking authz calls as asserted, it will mark the first matchingcalls first.

func (*RecordingAuthorizer)Authorize

func (r *RecordingAuthorizer) Authorize(ctxcontext.Context, subjectrbac.Subject, actionpolicy.Action, objectrbac.Object)error

func (*RecordingAuthorizer)Pair

Pair is on the RecordingAuthorizer to be easy to find and keep the pkginterface smaller.

func (*RecordingAuthorizer)Prepare

func (r *RecordingAuthorizer) Prepare(ctxcontext.Context, subjectrbac.Subject, actionpolicy.Action, objectTypestring) (rbac.PreparedAuthorized,error)

func (*RecordingAuthorizer)Reset

func (r *RecordingAuthorizer) Reset()

Reset clears the recorded Authorize() calls.

typeSwaggerComment

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

funcParseSwaggerComments

func ParseSwaggerComments(dirs ...string) ([]SwaggerComment,error)

typeWaitForAgentFnadded inv2.22.0

type WaitForAgentFn func(agentcodersdk.WorkspaceAgent)bool

WaitForAgentFn represents a boolean assertion to be made against each agentthat a given WorkspaceAgentWaited knows about. Each WaitForAgentFn should applythe check to a single agent, but it should be named for plural, because `func (w WorkspaceAgentWaiter) WaitFor`applies the check to all agents that it is aware of. This ensures that the public API of the waiterreads correctly. For example:

waiter := coderdtest.NewWorkspaceAgentWaiter(t, client, r.Workspace.ID)waiter.WaitFor(coderdtest.AgentsReady)

typeWorkspaceAgentWaiteradded inv2.8.0

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

WorkspaceAgentWaiter waits for all resources with agents to be connected. Ifspecific agents are provided using AgentNames(), it will wait for those agentsto be connected but will not fail if other agents are not connected.

funcNewWorkspaceAgentWaiteradded inv2.8.0

func NewWorkspaceAgentWaiter(ttesting.TB, client *codersdk.Client, workspaceIDuuid.UUID)WorkspaceAgentWaiter

NewWorkspaceAgentWaiter returns an object that waits for agents to connect whenyou call Wait() on it.

func (WorkspaceAgentWaiter)AgentNamesadded inv2.8.0

AgentNames instructs the waiter to wait for the given, named agents to be connected and willreturn even if other agents are not connected.

func (WorkspaceAgentWaiter)MatchResourcesadded inv2.8.0

MatchResources instructs the waiter to wait until the workspace has resources that cause theprovided matcher function to return true.

func (WorkspaceAgentWaiter)Waitadded inv2.8.0

Wait waits for the agent(s) to connect and fails the test if they do not within testutil.WaitLong

func (WorkspaceAgentWaiter)WaitForadded inv2.22.0

func (wWorkspaceAgentWaiter) WaitFor(criteria ...WaitForAgentFn)

Source Files

View all Source files

Directories

PathSynopsis
Package promhelp provides helper functions for asserting Prometheus metric values in unit tests.
Package promhelp provides helper functions for asserting Prometheus metric values in unit tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp