testutils

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	DaysToExpiration              = 7
	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 CertIssuer = MockPlugin{
	// contains filtered or unexported fields
}
View Source
var ErrFailedConversion = errors.New("failed to convert to TCPAddr")
View Source
var IdentityManagementGroupMembership = map[string][]IdentityManagementUserRef{
	"SCIM-Group-ID-001": {
		{"00000000-0000-0000-0000-100000000001", "user1@example.com"},
		{"00000000-0000-0000-0000-100000000002", "user2@example.com"},
	},
	"SCIM-Group-ID-002": {
		{"00000000-0000-0000-0000-100000000003", "user3@example.com"},
		{"00000000-0000-0000-0000-100000000004", "user4@example.com"},
	},
}
View Source
var IdentityManagementGroups = map[string]string{
	"KMS_001": "SCIM-Group-ID-001",
	"KMS_002": "SCIM-Group-ID-002",
}
View Source
var IdentityPlugin = MockPlugin{
	// contains filtered or unexported fields
}
View Source
var KeyStorePlugin = MockPlugin{
	// contains filtered or unexported fields
}
View Source
var KeystoreProviderPlugin = MockPlugin{
	// contains filtered or unexported fields
}
View Source
var Notification = MockPlugin{
	// contains filtered or unexported fields
}
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 SystemInfo = MockPlugin{
	// contains filtered or unexported fields
}
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",
}
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 = map[string]string{
	"AccountID": "111122223333",
	"UserID":    "123456789012",
}

Functions

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 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 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 GetPluginDir

func GetPluginDir(dir string) string

func GetTestURL

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

func InjectClientDataIntoContext

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

InjectClientDataIntoContext 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,
) cmkapi.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 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 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 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 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 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 SetupMockPlugins

func SetupMockPlugins(mocks ...MockPlugin) []plugincatalog.PluginConfig

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 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 AuthClientData added in v0.3.0

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

AuthClientData 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) AuthClientData

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

func (AuthClientData) GetClientMap added in v0.3.0

func (cd AuthClientData) 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(*AuthClientData)

AuthClientOpt are options which can be used with NewAuthClient

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 ClientMapOpt added in v0.3.0

type ClientMapOpt func(*auth.ClientData)

ClientMapOpt are options which can be used, for example, when retrieving the ClientData 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 ClientData 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 IdentityManagementUserRef

type IdentityManagementUserRef struct {
	ID    string
	Email string
}

type KeyConfigOpt added in v0.3.0

type KeyConfigOpt func(*model.KeyConfiguration)

func WithAuthClientDataKC added in v0.3.0

func WithAuthClientDataKC(authClient AuthClientData) KeyConfigOpt

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

type MockPlugin

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

type OrbitalJob

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

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           map[string]string
	AdditionalContext map[any]any
}

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 {
	Plugins []MockPlugin                  // HashiCorp plugins only set if needed
	GRPCCon *commongrpc.DynamicClientConn // GRPCClient only set if needed
	Config  config.Config
}

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

	// If true create an isolated PSQL instance
	// In most cases this should not be set as it will take a longer time
	// as the container needs to build and startup
	WithIsolatedService 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 ...amqp.ClientOption,
) *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
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

TestModel represents a model for testing Migration and CRUD operations

func (TestModel) IsSharedModel

func (TestModel) IsSharedModel() bool

func (TestModel) TableName

func (TestModel) TableName() string

Directories

Path Synopsis
testplugins
keystoreman command
keystoreop command
notification command

Jump to

Keyboard shortcuts

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