testutils

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: Apache-2.0 Imports: 77 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RepoResourceTypeTest authz.RepoResourceType = "test"
	TestAdminRole        constants.BusinessRole = "TEST_ADMIN"
	TestReadAllowedRole  constants.BusinessRole = "TEST_READ_ALLOWED"
	TestWriteAllowedRole constants.BusinessRole = "TEST_WRITE_ALLOWED"
	TestBlockedRole      constants.BusinessRole = "TEST_BLOCKED"
)
View Source
const (
	DaysToExpiration              = 7
	TestTenantCertCommonName      = "testkms-cmk"
	TestLocalityID                = "12345678-90ab-cdef-1234-567890abcdef"
	TestDefaultKeystoreCommonName = "default.kms.cmk"
	TestRoleArn                   = "arn:aws:iam::123456789012:role/ExampleRole"
	TestTrustAnchorArn            = "arn:aws:rolesanywhere:eu-west-2:123456789012:trust-anchor/12345678-90ab-cdef-1234"
	TestProfileArn                = "arn:aws:rolesanywhere:eu-west-2:123456789012:profile/12345678-90ab-cdef-1234"
)
View Source
const (
	DefaultThrottleInterval = 5 * time.Second
)
View Source
const MaxPSQLSchemaName = 64
View Source
const TestCertURL = "https://aia.pki.co.test.com/aia/TEST%20Cloud%20Root%20CA.crt"
View Source
const TestHostPrefix = "https://kms.test/cmk/v1/"
View Source
const (
	TestTenant = "test"
)

Variables

View Source
var (
	ErrRegisterFailed   = errors.New("failed to register callback")
	ErrUnregisterFailed = errors.New("failed to unregister callback")
)
View Source
var ErrFailedConversion = errors.New("failed to convert to TCPAddr")
View Source
var RepoActionResourceTypes map[authz.RepoAction]authz.RepoResourceType
View Source
var SupportedRegions = []config.Region{
	{Name: "Region 1", TechnicalName: "region-1"},
	{Name: "Region 2", TechnicalName: "region-2"},
}
View Source
var SupportedRegionsMap = RegionsToMapSlice(SupportedRegions)
View Source
var TestBaseConfig = commoncfg.BaseConfig{
	Logger: commoncfg.Logger{
		Format: "json",
		Level:  "info",
	},
}
View Source
var TestDB = config.Database{
	Host: commoncfg.SourceRef{
		Source: commoncfg.EmbeddedSourceValue,
		Value:  "localhost",
	},
	User: commoncfg.SourceRef{
		Source: commoncfg.EmbeddedSourceValue,
		Value:  "postgres",
	},
	Secret: commoncfg.SourceRef{
		Source: commoncfg.EmbeddedSourceValue,
		Value:  "secret",
	},
	Name: "cmk",
	Port: "5433",
	Parameters: config.DBParameters{
		SSL: config.DBSSL{
			Mode: "disable",
		},
	},
}
View Source
var TestModelName = "test_models"
View Source
var TestRegistryConfig = &commoncfg.GRPCClient{
	Enabled: true,
	Address: "localhost:9092",
	SecretRef: &commoncfg.SecretRef{
		Type: commoncfg.InsecureSecretType,
	},
}

TestRegistryConfig is a default registry config for testing purposes

View Source
var TestSessionManagerConfig = &commoncfg.GRPCClient{
	Enabled: true,
	Address: "localhost:9091",
	SecretRef: &commoncfg.SecretRef{
		Type: commoncfg.InsecureSecretType,
	},
}

TestSessionManagerConfig is a default session manager config for testing purposes

View Source
var ValidKeystoreAccountInfo = testplugins.ValidKeystoreAccountInfo

ValidKeystoreAccountInfo is test account data used by the keystore operator.

Functions

func CleanPath added in v0.9.0

func CleanPath(path string) string

CleanPath returns a sanitized version of the path for use in test names.

func CreateCACertificatePEM

func CreateCACertificatePEM(
	t *testing.T,
) []byte

func CreateCertificateChain

func CreateCertificateChain(
	t *testing.T,
	subject pkix.Name,
	pkey *rsa.PrivateKey,
) string

func CreateCertificatePEM

func CreateCertificatePEM(
	t *testing.T,
	csr *x509.CertificateRequest,
	pkey *rsa.PrivateKey,
) []byte

func CreateCtxWithTenant

func CreateCtxWithTenant(tenant string) context.Context

func CreateDBTenant

func CreateDBTenant(
	tb testing.TB,
	dbCon *multitenancy.DB,
	tenant *model.Tenant,
)

func CreateTestEntities

func CreateTestEntities(ctx context.Context, tb testing.TB, r repo.Repo, entities ...repo.Resource)

func DeleteTestEntities

func DeleteTestEntities(ctx context.Context, tb testing.TB, r repo.Repo, entities ...repo.Resource)

func GenerateTestKeyPair added in v0.9.0

func GenerateTestKeyPair() (*rsa.PrivateKey, *rsa.PublicKey, error)

GenerateTestKeyPair generates an RSA key pair for testing Returns a 2048-bit RSA private key suitable for RS256 signing

func GetAllowedRoles added in v0.9.0

func GetAllowedRoles(
	resourceType authz.APIResourceType,
	action authz.APIAction,
) []constants.BusinessRole

GetAllowedRoles returns roles that have the given resource type + action based on the API policy data.

func GetAuthClientMap added in v0.3.0

func GetAuthClientMap(ctx context.Context, tb testing.TB, r repo.Repo, opts ...AuthClientOpt) map[any]any

GetAuthClientMap does the same as the NewAuthClient, except it returns the ClientMap directly. It can be used for simple tests when a separate AuthClient is not required

func GetBlockedRoles added in v0.9.0

func GetBlockedRoles(
	resourceType authz.APIResourceType,
	action authz.APIAction,
) []constants.BusinessRole

GetBlockedRoles returns roles that do NOT have the given resource type + action.

func GetClientMap added in v0.3.0

func GetClientMap(identifier string, groupNames []string) map[any]any

GetClientMap returns a client map created with the provided identifier and group names It does not create anything in the database

func GetFreePort

func GetFreePort() (int, error)

GetFreePort asks the kernel for a free open port that is ready to use.

func GetFreePortString

func GetFreePortString() (string, error)

func GetGrouplessClientMap added in v0.3.0

func GetGrouplessClientMap() map[any]any

GetGrouplessClientMap returns a client map with a random identifier and no groupnames It does not create anything in the database

func GetInvalidClientMap added in v0.3.0

func GetInvalidClientMap(opts ...ClientMapOpt) map[any]any

GetInvalidClientMap returns a client map with random identifier and random groupnames It does not create anything in the database

func GetJSONBody

func GetJSONBody[t any](tb testing.TB, w *httptest.ResponseRecorder) t

GetJSONBody is used to get a response out of an HTTP Body encoded as JSON For error responses use cmkapi.ErrorMessage as it's type

func GetTestURL

func GetTestURL(tb testing.TB, tenant, path string) string

func InjectBusinessUserDataIntoContext added in v0.9.0

func InjectBusinessUserDataIntoContext(ctx context.Context, identifier string, groups []string) context.Context

InjectBusinessUserDataIntoContext adds identifier, groups to the context for testing.

func MakeHTTPRequest

func MakeHTTPRequest(tb testing.TB, server cmkapi.ServeMux, opt RequestOptions) *httptest.ResponseRecorder

MakeHTTPRequest creates an HTTP method and gets its response for it On POST/PATCH methods, RequestOptions body should use WithString/WithJSON methods

func NewAMQPClient

func NewAMQPClient(
	tb testing.TB,
	amqpCfg AMQPCfg,
) (*amqp.Client, config.AMQP)

func NewAPIServer

func NewAPIServer(
	tb testing.TB,
	dbCon *multitenancy.DB,
	testCfg TestAPIServerConfig,
) *daemon.ServeMux

NewAPIServer creates a new API server with the given database connection

func NewCertificate

func NewCertificate(m func(*model.Certificate)) *model.Certificate

func NewDefaultWorkflowConfig added in v0.3.0

func NewDefaultWorkflowConfig(enabled bool) *model.WorkflowConfig

NewDefaultWorkflowConfig creates a default WorkflowConfig for testing with commonly used default values

func NewEvent added in v0.4.0

func NewEvent(m func(*model.Event)) *model.Event

func NewGRPCSuite

func NewGRPCSuite(
	tb testing.TB,
	registrars ...ServiceRegistrar,
) (
	*grpc.Server,
	*commongrpc.DynamicClientConn,
)

NewGRPCSuite creates a new gRPC server and client connection for testing purposes. Returns the server and client connection for use in tests.

func NewGroup

func NewGroup(m func(*model.Group)) *model.Group

func NewHTTPRequest

func NewHTTPRequest(tb testing.TB, opt RequestOptions) *http.Request

NewHTTPRequest builds an HTTP Request it sets default content-types for certain Methods

func NewImportParams

func NewImportParams(m func(*model.ImportParams)) *model.ImportParams

func NewIsolatedDB

func NewIsolatedDB(tb testing.TB, cfg config.Database) config.Database

NewIsolatedDB creates a new database on a postgres instance and returns it

This is intended only for tests that call functions establishing DB connection

func NewKey

func NewKey(m func(*model.Key)) *model.Key

func NewKeyConfig

func NewKeyConfig(m func(*model.KeyConfiguration),
	opts ...KeyConfigOpt,
) *model.KeyConfiguration

func NewKeyLabel

func NewKeyLabel(m func(l *model.KeyLabel)) *model.KeyLabel

func NewKeyVersion

func NewKeyVersion(m func(*model.KeyVersion)) *model.KeyVersion

func NewKeystore

func NewKeystore(m func(*model.Keystore)) *model.Keystore

func NewKeystoreConfig

func NewKeystoreConfig(m func(*model.KeystoreConfig)) *model.KeystoreConfig

func NewLogBuffer added in v0.9.0

func NewLogBuffer() (*slog.Logger, *bytes.Buffer)

NewLogBuffer returns a slog.Logger and a buffer that captures log output. Use slog.SetDefault(logger) to capture logs from code using the default logger.

func NewMigrator

func NewMigrator() db.Migrator

func NewMutator

func NewMutator[T any](baseProv func() T) func(mutatorFn ...func(*T)) T

NewMutator provides a function that can be used in table driven tests. It returns a function that can be used to mutate an object, where the object is provided by initTProv.

func NewRepoAuthzLoader added in v0.5.0

func NewSignedBusinessUserDataHeaders added in v0.9.0

func NewSignedBusinessUserDataHeaders(
	tb testing.TB,
	clientData *auth.ClientData,
	privateKey *rsa.PrivateKey,
	keyID int,
) http.Header

NewSignedBusinessUserDataHeaders generates HTTP headers from an auth.ClientData struct.

func NewSystem

func NewSystem(m func(*model.System)) *model.System

func NewTag

func NewTag(m func(*model.Tag)) *model.Tag

func NewTenant

func NewTenant(m func(t *model.Tenant)) *model.Tenant

func NewTestDB

func NewTestDB(tb testing.TB, cfg TestDBConfig, opts ...TestDBConfigOpt) (*multitenancy.DB, []string, config.Database)

NewTestDB sets up a test database connection and creates tenants as needed. It returns a pointer to the multitenancy.DB instance, a slice of tenant IDs and it's config. By default, it uses TestDB configuration. Use opts to customize the setup. This function is intended for use in unit tests.

func NewTestPlugins added in v0.5.0

func NewTestPlugins(opts ...testplugins.RegistryOption) serviceapi.Registry

NewTestPlugins returns a serviceapi.Registry pre-configured with default test service implementations. Pass RegistryOptions to override specific services.

func NewUserManager

func NewUserManager() manager.User

func NewWorkflow

func NewWorkflow(m func(*model.Workflow)) *model.Workflow

func NewWorkflowApprover

func NewWorkflowApprover(m func(approver *model.WorkflowApprover)) *model.WorkflowApprover

func NewWorkflowApproverGroup added in v0.9.0

func NewWorkflowApproverGroup(m func(*model.WorkflowApproverGroup)) *model.WorkflowApproverGroup

func NewWorkflowConfig

func NewWorkflowConfig(m func(m *model.TenantConfig)) *model.TenantConfig

func RegionsToMapSlice

func RegionsToMapSlice(regions []config.Region) []map[string]string

func RunTestQuery

func RunTestQuery(db *multitenancy.DB, tenant string, queries ...string)

RunTestQuery runs a query in the database with the specified tenant context

func SetupLoggerWithBuffer

func SetupLoggerWithBuffer() *slog.Logger

SetupLoggerWithBuffer returns a logger that writes to a buffer

func SetupTestBinary added in v0.7.0

func SetupTestBinary(tb testing.TB, statusServer string, f func() error)

func StartPostgresSQL

func StartPostgresSQL(
	tb testing.TB,
	cfg *config.Database,
	opts ...testcontainers.ContainerCustomizer,
)

func StartRabbitMQ

func StartRabbitMQ(
	tb testing.TB,
	opts ...testcontainers.ContainerCustomizer,
) string

func StartRedis

func StartRedis(
	tb testing.TB,
	cfg *config.Scheduler,
	opts ...testcontainers.ContainerCustomizer,
)

func SubstitutePathParams added in v0.9.0

func SubstitutePathParams(path string) string

SubstitutePathParams replaces path parameters (e.g., {keyID}) with dummy UUIDs so the path can be used in an HTTP request for route matching.

func WaitForServer added in v0.7.0

func WaitForServer(tb testing.TB, statusServer string)

func WithBody added in v0.9.0

func WithBody(tb testing.TB, body string) io.Reader

WithBody converts a JSON string to an io.Reader for use as a request body. Returns nil if the body is empty.

func WithBusinessUserData added in v0.9.0

func WithBusinessUserData(
	tb testing.TB,
	keyStorage *TestSigningKeyStorage,
	authClient AuthBusinessUserData,
	opts ...ClientMapOpt,
) http.Header

WithBusinessUserData builds signed client-data headers for the given auth client.

func WithJSON

func WithJSON(tb testing.TB, i any) io.Reader

WithJSON is a helper function that marshals an object to JSON and returns an io.Reader. It is intended to be used as the Body field in RequestOptions when making HTTP requests in tests.

func WithString

func WithString(tb testing.TB, i any) io.Reader

WithString is a helper function that converts a string to an io.Reader. It is intended to be used as the Body field in RequestOptions when making HTTP requests in tests.

func WithTenantID

func WithTenantID(ctx context.Context, db *multitenancy.DB, tenantID string, fn func(tx *multitenancy.DB) error) error

Types

type AMQPCfg

type AMQPCfg struct {
	Target string
	Source string
}

type AuthBusinessUserData added in v0.9.0

type AuthBusinessUserData struct {
	Group      *model.Group
	GroupID    string // For convenience. Just a string version of the Group.ID
	Identifier string
}

AuthBusinessUserData contains a group and an identifier associated with an AuthClient

func NewAuthClient added in v0.3.0

func NewAuthClient(ctx context.Context, tb testing.TB, r repo.Repo, opts ...AuthClientOpt) AuthBusinessUserData

NewAuthClient creates an AuthClient using random strings for values and creates the group in the database

func (AuthBusinessUserData) GetClientMap added in v0.9.0

func (cd AuthBusinessUserData) GetClientMap(opts ...ClientMapOpt) map[any]any

GetClientMap gets the ClientMap from the AuthClient. This can be used to authenticate

type AuthClientOpt added in v0.3.0

type AuthClientOpt func(*AuthBusinessUserData)

AuthClientOpt are options which can be used with NewAuthClient

func RoleAuthClientOpt added in v0.9.0

func RoleAuthClientOpt(role constants.BusinessRole) AuthClientOpt

RoleAuthClientOpt maps a role to the corresponding AuthClientOpt.

func WithAuditorRole added in v0.3.0

func WithAuditorRole() AuthClientOpt

WithAuditorRole provides an option for getting an AuthClient with NewAuthClient, or the ClientMap with GetAuthClientMap. It specifies TenantAuditorRole for the group

func WithIdentifier added in v0.3.0

func WithIdentifier(identifier string) AuthClientOpt

WithIdentifier provides an option when getting an AuthClient with NewAuthClient, or the ClientMap with GetAuthClientMap. It allows the default random value for the AuthClient Identifier to be overridden with the provided value

func WithKeyAdminRole added in v0.3.0

func WithKeyAdminRole() AuthClientOpt

WithKeyAdminRole provides an option for getting an AuthClient with NewAuthClient, or the ClientMap with GetAuthClientMap. It specifies KeyAdminRole for the group

func WithTenantAdminRole added in v0.3.0

func WithTenantAdminRole() AuthClientOpt

WithTenantAdminRole provides an option for getting an AuthClient with NewAuthClient, or the ClientMap with GetAuthClientMap. It specifies TenantAdminRole for the group

type AuthzTestEndpoint added in v0.9.0

type AuthzTestEndpoint struct {
	// Method is the HTTP method (e.g., http.MethodGet)
	Method string
	// Endpoint is the URL path with any required path params filled in
	// (e.g., "/keys?keyConfigurationID=xxx")
	Endpoint string
	// Body is an optional JSON request body for POST/PATCH/PUT requests
	Body string
}

AuthzTestEndpoint defines an API endpoint to test for authorization failures.

type ClientMapOpt added in v0.3.0

type ClientMapOpt func(*auth.ClientData)

ClientMapOpt are options which can be used, for example, when retrieving the BusinessUserData from an AuthClient

func WithAdditionalGroup added in v0.3.0

func WithAdditionalGroup(groupName string) ClientMapOpt

WithAdditionalGroup provides an option for getting a ClientMap from an AuthClient. It adds an additional group to the BusinessUserData Groups

func WithOverriddenGroup added in v0.3.0

func WithOverriddenGroup(numGroups int) ClientMapOpt

WithOverriddenGroup provides an option for getting a ClientMap from an AuthClient. It overrides the AuthClient Groups. This can be used, for example, when testing for invalid groups for a given AuthClient identifier

func WithOverriddenIdentifier added in v0.3.0

func WithOverriddenIdentifier(identifier string) ClientMapOpt

WithOverriddenIdentifier provides an option for getting a ClientMap from an AuthClient. It overrides the AuthClient Identifier. This can be used, for example, when testing for other users in (or not in) the AuthClient Group

type CryptoCert

type CryptoCert struct {
	Subject string
	RootCA  string
}

type ErrorForced

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

ErrorForced - a helper to force an error in the database using gorm

func NewDBErrorForced

func NewDBErrorForced(db *multitenancy.DB, forcedErr error) *ErrorForced

NewDBErrorForced - creates a new ErrorForced instance.

func (*ErrorForced) Register

func (e *ErrorForced) Register()

Register - registers the error callback.

func (*ErrorForced) Unregister

func (e *ErrorForced) Unregister()

Unregister - unregisters the error callback.

func (*ErrorForced) WithCreate

func (e *ErrorForced) WithCreate() *ErrorForced

WithCreate - forces the error in the create callback.

func (*ErrorForced) WithDelete

func (e *ErrorForced) WithDelete() *ErrorForced

WithDelete - forces the error in the delete callback.

func (*ErrorForced) WithQuery

func (e *ErrorForced) WithQuery() *ErrorForced

WithQuery - forces the error in the query callback.

func (*ErrorForced) WithRaw

func (e *ErrorForced) WithRaw() *ErrorForced

WithRaw - forces the error in the raw callback.

func (*ErrorForced) WithRow

func (e *ErrorForced) WithRow() *ErrorForced

WithRow - forces the error in the row callback.

func (*ErrorForced) WithUpdate

func (e *ErrorForced) WithUpdate() *ErrorForced

WithUpdate - forces the error in the update callback.

type KeyConfigOpt added in v0.3.0

type KeyConfigOpt func(*model.KeyConfiguration)

func WithAuthBusinessUserDataKC added in v0.9.0

func WithAuthBusinessUserDataKC(authClient AuthBusinessUserData) KeyConfigOpt

WithAuthBusinessUserDataKC provides an option for the NewKeyConfig function This option will initialise the KeyConfig with the AuthClient Group

func WithIDMPluginKC added in v0.9.0

func WithIDMPluginKC(idm *testplugins.TestIdentityManagement) KeyConfigOpt

WithIDMPluginKC returns a KeyConfigOpt that registers the key configuration's CreatorID in the given IDM plugin so GetUser lookups succeed.

type MockOperatorError added in v0.9.0

type MockOperatorError struct {
	Code    string
	Message string
}

MockOperatorError is the failure the mock operator reports when a task is marked failed. Code and Message are joined with a colon so the resulting ErrorMessage matches the "CODE:message" contract ParseOrbitalError expects. An empty Code yields a bare Message — useful for simulating legacy unstructured failures.

func (MockOperatorError) String added in v0.9.0

func (e MockOperatorError) String() string

String renders the error in "CODE:message" form, or just Message when Code is empty.

type MockOperatorOption added in v0.9.0

type MockOperatorOption func(*mockOperatorConfig)

MockOperatorOption configures TestMockAMQPOperator.

func WithFailureError added in v0.9.0

func WithFailureError(e MockOperatorError) MockOperatorOption

WithFailureError overrides the default "simulated failure" message returned when the operator is configured with success=false.

type OrbitalJob

type OrbitalJob struct {
	ID           uuid.UUID
	ExternalID   string
	Data         []byte
	Type         string
	Status       string
	ErrorMessage string
	UpdatedAt    int64
	CreatedAt    int64
}

func (OrbitalJob) CheckAuthz added in v0.5.0

func (OrbitalJob) CheckAuthz(ctx context.Context,
	authzHandler *authz.Handler[authz.RepoResourceType, authz.RepoAction],
	action authz.RepoAction,
) (bool, error)

func (OrbitalJob) IsSharedModel

func (OrbitalJob) IsSharedModel() bool

func (OrbitalJob) TableName

func (OrbitalJob) TableName() string

type RequestOptions

type RequestOptions struct {
	Method            string // HTTP Method
	Endpoint          string
	Tenant            string      // TenantID
	Body              io.Reader   // Only need to be set for POST/PATCH. Used with the WithString and WithJSON
	Headers           http.Header // Use this for authentication.
	AdditionalContext map[any]any // Use this in case we want to inject some key-value pairs to the request context.
}

type ServiceRegistrar

type ServiceRegistrar func(*grpc.Server)

ServiceRegistrar registers a service with a gRPC server

type TLSFiles

type TLSFiles struct {
	Dir            string
	RootCACertPath string
	RootCAKeyPath  string
	ServerCertPath string
	ServerKeyPath  string
	ClientCertPath string
	ClientKeyPath  string
}

func CreateTLSFiles

func CreateTLSFiles(t *testing.T) TLSFiles

type TestAPIServerConfig

type TestAPIServerConfig struct {
	Registry serviceapi.Registry           // Registry is optional; defaults to testplugins.NewRegistry()
	GRPCCon  *commongrpc.DynamicClientConn // GRPCClient only set if needed
	Config   config.Config
	// Enable ClientDataMiddleware (default: false for backward compatibility).
	EnableBusinessUserDataMW bool
	SigningKeyStorage        keyvalue.ReadOnlyStringToBytesStorage // Optional: provide custom signing key storage
}

type TestDBConfig

type TestDBConfig struct {

	// WithOrbital creates an entry for an orbital tenant
	// This should only be used in tests where we want to access orbital table entries with the repo interface
	WithOrbital bool

	// If true create DB instance for test instead of tenant
	// This should be used whenever each test is testing either:
	// - Shared Tables
	// - Multiple Tenants
	CreateDatabase bool

	// Shared schema version to migrate up to
	// If it's nil migrate to latest version
	SharedVersion *int64

	// Tenant schema version to migrate up to
	// If it's nil migrate to latest version
	TenantVersion *int64

	// TenantRole specifies the role for generated tenants
	// If empty, defaults to ROLE_LIVE
	TenantRole model.TenantRole

	// GORM Logger
	Logger logger.Interface
	// contains filtered or unexported fields
}

type TestDBConfigOpt

type TestDBConfigOpt func(*TestDBConfig)

func WithGenerateTenants

func WithGenerateTenants(count int) TestDBConfigOpt

WithGenerateTenants creates count tenants on a separate database

func WithInitTenants

func WithInitTenants(tenants ...model.Tenant) TestDBConfigOpt

WithInitTenants creates the provided tenants on the DB No default tenants are generated on provided tenants

func WithTenantRole added in v0.3.0

func WithTenantRole(role model.TenantRole) TestDBConfigOpt

WithTenantRole specifies the role for generated tenants If not set, defaults to ROLE_LIVE

type TestMockAMQPOperator

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

func NewMockAMQPOperator

func NewMockAMQPOperator(
	t *testing.T,
	numReconcile int,
	success bool,
	connConfig amqp.ConnectionInfo,
	opts ...MockOperatorOption,
) *TestMockAMQPOperator

func (*TestMockAMQPOperator) Reset

func (o *TestMockAMQPOperator) Reset()

Reset clears the internal state for test isolation

func (*TestMockAMQPOperator) Start

func (o *TestMockAMQPOperator) Start(ctx context.Context)

func (*TestMockAMQPOperator) Stop

func (o *TestMockAMQPOperator) Stop(ctx context.Context)

type TestModel

type TestModel struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey"`
	Name        string    `gorm:"type:varchar(255);unique"`
	Description string
	Data        json.RawMessage `gorm:"type:jsonb"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

TestModel represents a model for testing Migration and CRUD operations

func (TestModel) CheckAuthz added in v0.5.0

func (m TestModel) CheckAuthz(ctx context.Context,
	authzHandler *authz.Handler[authz.RepoResourceType, authz.RepoAction],
	action authz.RepoAction,
) (bool, error)

func (TestModel) IsSharedModel

func (TestModel) IsSharedModel() bool

func (TestModel) TableName

func (TestModel) TableName() string

func (TestModel) TableResourceType added in v0.5.0

func (TestModel) TableResourceType() authz.RepoResourceType

type TestRoleGetter added in v0.9.0

type TestRoleGetter struct {
	DefaultRole constants.BusinessRole
}

TestRoleGetter is a mock RoleGetter for testing that always returns a default role

func NewTestRoleGetter added in v0.9.0

func NewTestRoleGetter() *TestRoleGetter

NewTestRoleGetter creates a TestRoleGetter with the default role set to TenantAdminRole.

func (*TestRoleGetter) GetRoleFromIAM added in v0.9.0

func (t *TestRoleGetter) GetRoleFromIAM(ctx context.Context, iamIdentifiers []string) (
	constants.BusinessRole, error,
)

GetRoleFromIAM returns the configured default role (or TenantAdminRole if not set)

type TestSigningKeyStorage added in v0.9.0

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

TestSigningKeyStorage holds test signing keys in memory

func NewTestSigningKeyStorage added in v0.9.0

func NewTestSigningKeyStorage(tb testing.TB) *TestSigningKeyStorage

NewTestSigningKeyStorage creates or returns a shared signing key storage with pre-generated test keys. Generates 1 key pair (keyID 0) on first call, then reuses the same keys for all subsequent tests. This significantly speeds up test execution by avoiding redundant RSA key generation. Returns storage that implements keyvalue.ReadOnlyStringToBytesStorage interface

func (*TestSigningKeyStorage) Cleanup added in v0.9.0

func (t *TestSigningKeyStorage) Cleanup()

Cleanup stops the loader and removes temporary files

func (*TestSigningKeyStorage) Get added in v0.9.0

func (t *TestSigningKeyStorage) Get(keyID string) ([]byte, bool)

Get retrieves a public key by ID Returns (value, found) to match keyvalue.ReadStorage interface

func (*TestSigningKeyStorage) GetPrivateKey added in v0.9.0

func (t *TestSigningKeyStorage) GetPrivateKey(keyID int) (*rsa.PrivateKey, bool)

GetPrivateKey retrieves a private key by ID for test signing

func (*TestSigningKeyStorage) IsEmpty added in v0.9.0

func (t *TestSigningKeyStorage) IsEmpty() bool

IsEmpty returns whether the storage is empty

func (*TestSigningKeyStorage) List added in v0.9.0

func (t *TestSigningKeyStorage) List() []string

List returns all key IDs in the storage

Jump to

Keyboard shortcuts

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