testutil

package
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package testutil provides testing utilities for dsops.

Package testutil provides test utilities and helpers for dsops tests.

This package contains shared test infrastructure including configuration builders, logger helpers, fixture loaders, and Docker environment management.

Package testutil provides testing utilities and helpers for dsops tests.

This file implements the provider contract test framework that validates all providers implement the provider.Provider interface correctly and consistently.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertCommandSuccess

func AssertCommandSuccess(t *testing.T, err error, output string, expectedInOutput string)

AssertCommandSuccess verifies that a command executed successfully.

This checks that the error is nil and optionally that the output contains expected content.

Example usage:

output, err := exec.Command("dsops", "plan").CombinedOutput()
AssertCommandSuccess(t, err, string(output), "DATABASE_URL")

Parameters:

  • t: Testing context
  • err: Error from command execution
  • output: Command output (stdout/stderr combined)
  • expectedInOutput: Optional substring to check in output (empty string skips)

func AssertErrorContains

func AssertErrorContains(t *testing.T, err error, substr string)

AssertErrorContains verifies that an error occurred and contains a substring.

This is a convenience wrapper for error assertion with message checking.

Example usage:

err := someOperation()
AssertErrorContains(t, err, "connection failed")

Parameters:

  • t: Testing context
  • err: The error to check
  • substr: Substring that should appear in the error message

func AssertFileContainsAll

func AssertFileContainsAll(t *testing.T, path string, substrings []string)

AssertFileContainsAll verifies that a file contains all specified substrings.

Example usage:

AssertFileContainsAll(t, "config.yaml", []string{"version: 1", "secretStores:"})

Parameters:

  • t: Testing context
  • path: Path to the file
  • substrings: Substrings that must all be present

func AssertFileContents

func AssertFileContents(t *testing.T, path string, expected string)

AssertFileContents verifies that a file exists and contains expected content.

This is a convenience wrapper for file content assertions.

Example usage:

AssertFileContents(t, "output.txt", "expected content")

Parameters:

  • t: Testing context
  • path: Path to the file
  • expected: Expected file contents

func AssertLinesContain

func AssertLinesContain(t *testing.T, output string, expectedLines []string)

AssertLinesContain verifies that specific lines are present in multi-line output.

This is useful for testing command output or log files line-by-line.

Example usage:

output := "line1\nline2\nline3"
AssertLinesContain(t, output, []string{"line1", "line3"})

Parameters:

  • t: Testing context
  • output: Multi-line string
  • expectedLines: Lines that should be present (partial match)

func AssertNoSecretLeak

func AssertNoSecretLeak(t *testing.T, output string, secrets []string)

AssertNoSecretLeak verifies that multiple secret values are redacted in output.

This is useful for testing that all secrets in a configuration are properly redacted in logs or error messages.

Example usage:

secrets := []string{"password123", "api-key-456", "token-789"}
AssertNoSecretLeak(t, logOutput, secrets)

Parameters:

  • t: Testing context
  • output: The string to check
  • secrets: List of secret values that should all be redacted

func AssertSecretRedacted

func AssertSecretRedacted(t *testing.T, output, secretValue string)

AssertSecretRedacted verifies that a secret value does not appear in a string.

This is a specialized assertion for security testing. It checks that the secret value is not present in the output, and that the [REDACTED] marker is present instead.

Example usage:

output := someOperation()
AssertSecretRedacted(t, output, "password123")

Parameters:

  • t: Testing context
  • output: The string to check (log output, error message, etc.)
  • secretValue: The secret that should be redacted

func CleanupTestFiles

func CleanupTestFiles(t *testing.T, paths ...string)

CleanupTestFiles cleans up test files and directories.

This is typically not needed when using t.TempDir(), but can be useful for cleaning up files created outside the temp directory.

Example usage:

CleanupTestFiles(t, "output.txt", "temp_dir/")

Parameters:

  • t: Testing context
  • paths: Files or directories to remove

func IsDockerAvailable

func IsDockerAvailable() bool

IsDockerAvailable checks if Docker is available and running

func LoadTestConfig

func LoadTestConfig(t *testing.T, path string) *config.Definition

LoadTestConfig loads a configuration from a file path.

This is a convenience wrapper around config loading for tests. It handles errors by failing the test immediately.

Parameters:

  • t: Testing context
  • path: Path to the configuration file

Returns the loaded Configuration Definition.

func RandomString

func RandomString(prefix string, length int) string

RandomString generates a random string with a prefix and random suffix.

This is useful for generating unique names for test resources (users, tables, etc.) to avoid conflicts between parallel tests.

Example usage:

username := RandomString("test_user", 8)
// Returns something like: "test_user_a7f9k2d5"

Parameters:

  • prefix: String to prepend to the random suffix
  • length: Length of the random suffix (default 8 if 0)

Returns:

  • A string in the format: prefix_randomsuffix

func RunProviderContractTests

func RunProviderContractTests(t *testing.T, tc ProviderTestCase)

RunProviderContractTests runs all contract tests for a provider.

This function executes the complete provider contract test suite:

  • Name() returns consistent value
  • Resolve() retrieves secrets correctly
  • Describe() returns metadata without values
  • Capabilities() returns valid capabilities
  • Validate() checks configuration
  • Error handling is consistent
  • Concurrency safety (no race conditions)

Example usage:

tc := testutil.ProviderTestCase{
    Name:     "vault",
    Provider: vaultProvider,
    TestData: map[string]provider.SecretValue{
        "secret/test": {Value: "test-secret-123"},
    },
}
testutil.RunProviderContractTests(t, tc)

func SetupTestEnv

func SetupTestEnv(t *testing.T, vars map[string]string)

SetupTestEnv sets environment variables for the duration of a test.

The original environment is restored automatically when the test completes. This uses t.Cleanup() to ensure cleanup happens even if the test fails.

Example usage:

SetupTestEnv(t, map[string]string{
    "AWS_REGION": "us-east-1",
    "VAULT_ADDR": "http://localhost:8200",
})

Parameters:

  • t: Testing context
  • vars: Map of environment variable names to values

func SkipIfDockerUnavailable

func SkipIfDockerUnavailable(t *testing.T)

SkipIfDockerUnavailable skips the test if Docker is not available

func WithEnv

func WithEnv(t *testing.T, vars map[string]string, fn func())

WithEnv executes a function with temporary environment variables.

This is useful for testing code that reads environment variables. The environment is restored automatically after the function returns.

Example usage:

WithEnv(t, map[string]string{"DEBUG": "true"}, func() {
    // Code here sees DEBUG=true
    someFunction()
})
// DEBUG is restored to original value here

Parameters:

  • t: Testing context
  • vars: Environment variables to set
  • fn: Function to execute with the environment

func WriteTestConfig

func WriteTestConfig(t *testing.T, yamlContent string) string

WriteTestConfig is a convenience function for writing a YAML string to a file.

This is useful for tests that have hand-written YAML test cases. The file is created in a temporary directory and cleaned up automatically.

Parameters:

  • t: Testing context
  • yamlContent: Raw YAML configuration string

Returns the absolute path to the written configuration file.

Example:

path := WriteTestConfig(t, `
version: 1
secretStores:
  test:
    type: literal
    values:
      API_KEY: "test-key"
`)

Types

type BitwardenMockResponses

type BitwardenMockResponses struct{}

BitwardenMockResponses provides pre-configured responses for Bitwarden CLI.

func (BitwardenMockResponses) Item

func (BitwardenMockResponses) Item(id, name, username, password string) MockResponse

Item returns a mock Bitwarden item response.

func (BitwardenMockResponses) StatusLocked

func (BitwardenMockResponses) StatusLocked() MockResponse

StatusLocked returns a mock response for a locked Bitwarden vault.

func (BitwardenMockResponses) StatusUnauthenticated

func (BitwardenMockResponses) StatusUnauthenticated() MockResponse

StatusUnauthenticated returns a mock response for unauthenticated state.

func (BitwardenMockResponses) StatusUnlocked

func (BitwardenMockResponses) StatusUnlocked() MockResponse

StatusUnlocked returns a mock response for an unlocked Bitwarden vault.

type CommandExecutor

type CommandExecutor = exec.CommandExecutor

Re-export the interface and real executor from pkg/exec for backward compatibility. This allows existing code to continue importing from testutil while we migrate.

type DockerTestEnv

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

DockerTestEnv manages Docker Compose lifecycle for integration tests

func StartDockerEnv

func StartDockerEnv(t *testing.T, services []string) *DockerTestEnv

StartDockerEnv starts Docker Compose services for integration testing

func (*DockerTestEnv) GetPort added in v0.2.3

func (e *DockerTestEnv) GetPort(service string, containerPort int) int

GetPort returns the host port for a service's container port Returns the container port as fallback if not found (for backward compatibility)

func (*DockerTestEnv) LocalStackClient

func (e *DockerTestEnv) LocalStackClient() *LocalStackTestClient

LocalStackClient returns a LocalStack test client

func (*DockerTestEnv) LocalStackConfig

func (e *DockerTestEnv) LocalStackConfig() map[string]interface{}

LocalStackConfig returns LocalStack configuration Includes dummy credentials that LocalStack accepts for testing

func (*DockerTestEnv) LocalStackEndpoint added in v0.2.3

func (e *DockerTestEnv) LocalStackEndpoint() string

LocalStackEndpoint returns the LocalStack endpoint with dynamic port

func (*DockerTestEnv) MailhogAPIAddr added in v0.2.3

func (e *DockerTestEnv) MailhogAPIAddr() string

MailhogAPIAddr returns the MailHog HTTP API address with dynamic port

func (*DockerTestEnv) MailhogSMTPAddr added in v0.2.3

func (e *DockerTestEnv) MailhogSMTPAddr() string

MailhogSMTPAddr returns the MailHog SMTP address with dynamic port

func (*DockerTestEnv) MongoClient

func (e *DockerTestEnv) MongoClient() *MongoTestClient

MongoClient returns a MongoDB test client

func (*DockerTestEnv) MongoDBConnString added in v0.2.3

func (e *DockerTestEnv) MongoDBConnString() string

MongoDBConnString returns the MongoDB connection string with dynamic port

func (*DockerTestEnv) PostgresClient

func (e *DockerTestEnv) PostgresClient() *PostgresTestClient

PostgresClient returns a PostgreSQL test client

func (*DockerTestEnv) PostgresConfig

func (e *DockerTestEnv) PostgresConfig() map[string]interface{}

PostgresConfig returns PostgreSQL configuration

func (*DockerTestEnv) PostgresConnString added in v0.2.3

func (e *DockerTestEnv) PostgresConnString() string

PostgresConnString returns the PostgreSQL connection string with dynamic port

func (*DockerTestEnv) Stop

func (e *DockerTestEnv) Stop()

Stop stops and removes Docker Compose services

func (*DockerTestEnv) VaultAddress added in v0.2.3

func (e *DockerTestEnv) VaultAddress() string

VaultAddress returns the Vault address with dynamic port

func (*DockerTestEnv) VaultClient

func (e *DockerTestEnv) VaultClient() *VaultTestClient

VaultClient returns a Vault test client

func (*DockerTestEnv) VaultConfig

func (e *DockerTestEnv) VaultConfig() map[string]interface{}

VaultConfig returns Vault configuration for provider testing

func (*DockerTestEnv) WaitForHealthy

func (e *DockerTestEnv) WaitForHealthy(timeout time.Duration) error

WaitForHealthy waits for all services to be healthy

type DopplerMockResponses

type DopplerMockResponses struct{}

DopplerMockResponses provides pre-configured responses for Doppler CLI.

func (DopplerMockResponses) SecretsDownload

func (DopplerMockResponses) SecretsDownload() MockResponse

SecretsDownload returns a mock Doppler secrets response.

type LocalStackTestClient

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

LocalStackTestClient wraps AWS SDK for LocalStack testing

func (*LocalStackTestClient) CreateSecret

func (l *LocalStackTestClient) CreateSecret(name string, value map[string]interface{}) error

CreateSecret creates a secret in AWS Secrets Manager (LocalStack)

func (*LocalStackTestClient) GetParameter

func (l *LocalStackTestClient) GetParameter(name string) (string, error)

GetParameter retrieves a parameter from SSM Parameter Store

func (*LocalStackTestClient) GetSecretValue

func (l *LocalStackTestClient) GetSecretValue(name string) (map[string]interface{}, error)

GetSecretValue retrieves a secret from Secrets Manager

func (*LocalStackTestClient) PutParameter

func (l *LocalStackTestClient) PutParameter(name, value string) error

PutParameter puts a parameter in SSM Parameter Store (LocalStack)

type MockCommandExecutor

type MockCommandExecutor struct {

	// Responses maps command patterns to their mock responses.
	// Key format: "command arg1 arg2" (space-separated command and args)
	Responses map[string]MockResponse

	// DefaultResponse is used when no matching pattern is found.
	DefaultResponse *MockResponse

	// RecordedCalls stores all calls made to Execute for verification.
	RecordedCalls []RecordedCall

	// StrictMode causes Execute to fail if no matching response is found.
	StrictMode bool
	// contains filtered or unexported fields
}

MockCommandExecutor provides a configurable mock for testing CLI-based providers.

func NewMockCommandExecutor

func NewMockCommandExecutor() *MockCommandExecutor

NewMockCommandExecutor creates a new mock executor with empty responses.

func (*MockCommandExecutor) AddErrorResponse

func (m *MockCommandExecutor) AddErrorResponse(commandPattern string, errMsg string, exitCode int)

AddErrorResponse adds an error response for a command pattern.

func (*MockCommandExecutor) AddJSONResponse

func (m *MockCommandExecutor) AddJSONResponse(commandPattern string, jsonData string)

AddJSONResponse is a convenience method to add a JSON response.

func (*MockCommandExecutor) AddResponse

func (m *MockCommandExecutor) AddResponse(commandPattern string, response MockResponse)

AddResponse registers a mock response for a specific command pattern.

func (*MockCommandExecutor) AssertCallCount

func (m *MockCommandExecutor) AssertCallCount(t interface{ Error(args ...interface{}) }, commandName string, expected int) bool

AssertCallCount verifies the exact number of times a command was called.

func (*MockCommandExecutor) AssertCalled

func (m *MockCommandExecutor) AssertCalled(t interface{ Error(args ...interface{}) }, commandName string) bool

AssertCalled verifies that a specific command was called at least once.

func (*MockCommandExecutor) AssertNotCalled

func (m *MockCommandExecutor) AssertNotCalled(t interface{ Error(args ...interface{}) }, commandName string) bool

AssertNotCalled verifies that a specific command was never called.

func (*MockCommandExecutor) CallCount

func (m *MockCommandExecutor) CallCount() int

CallCount returns the number of times Execute was called.

func (*MockCommandExecutor) Execute

func (m *MockCommandExecutor) Execute(ctx context.Context, name string, args ...string) ([]byte, []byte, error)

Execute returns the mocked response for the given command.

func (*MockCommandExecutor) GetCalls

func (m *MockCommandExecutor) GetCalls(commandName string) []RecordedCall

GetCalls returns all recorded calls matching the given command name.

func (*MockCommandExecutor) Reset

func (m *MockCommandExecutor) Reset()

Reset clears all recorded calls and responses.

type MockResponse

type MockResponse struct {
	Stdout   []byte
	Stderr   []byte
	Err      error
	ExitCode int // Used to simulate exit codes when Err is nil
}

MockResponse defines the expected output for a mocked command.

type MongoTestClient

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

MongoTestClient wraps MongoDB connection

type OnePasswordMockResponses

type OnePasswordMockResponses struct{}

OnePasswordMockResponses provides pre-configured responses for 1Password CLI.

func (OnePasswordMockResponses) AccountGet

AccountGet returns a mock response for op account get.

func (OnePasswordMockResponses) ItemRead

func (OnePasswordMockResponses) ItemRead(vault, item, username, password string) MockResponse

ItemRead returns a mock 1Password item response.

type PassMockResponses

type PassMockResponses struct{}

PassMockResponses provides pre-configured responses for pass CLI.

func (PassMockResponses) Show

func (PassMockResponses) Show(password string) MockResponse

Show returns a mock password from pass store.

type PostgresTestClient

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

PostgresTestClient wraps PostgreSQL database connection

func (*PostgresTestClient) Close

func (p *PostgresTestClient) Close() error

Close closes the PostgreSQL connection

func (*PostgresTestClient) CreateTestUser

func (p *PostgresTestClient) CreateTestUser(username, password string) error

CreateTestUser creates a test PostgreSQL user

func (*PostgresTestClient) DropTestUser

func (p *PostgresTestClient) DropTestUser(username string) error

DropTestUser drops a test PostgreSQL user

func (*PostgresTestClient) Exec

func (p *PostgresTestClient) Exec(query string, args ...interface{}) error

Exec executes a SQL statement

func (*PostgresTestClient) Query

func (p *PostgresTestClient) Query(query string, args ...interface{}) (*QueryResult, error)

Query executes a SQL query

func (*PostgresTestClient) QueryRow

func (p *PostgresTestClient) QueryRow(query string, args ...interface{}) *QueryRowResult

QueryRow executes a SQL query that returns a single row

func (*PostgresTestClient) UserExists

func (p *PostgresTestClient) UserExists(username string) (bool, error)

UserExists checks if a user exists

type ProviderTestCase

type ProviderTestCase struct {
	// Name is a descriptive name for this test case (usually the provider name)
	Name string

	// Provider is the provider implementation to test
	Provider provider.Provider

	// TestData maps secret keys to their expected values
	// These secrets should exist in the provider's test environment
	TestData map[string]provider.SecretValue

	// SkipValidation skips the Validate() test if true
	// Useful for providers that don't require authentication
	SkipValidation bool

	// SkipConcurrency skips the concurrency test if true
	// Use only if provider explicitly doesn't support concurrent access
	SkipConcurrency bool
}

ProviderTestCase defines a provider under test with its test data.

This structure contains everything needed to run contract tests against a provider implementation.

type QueryResult

type QueryResult struct {
	*sql.Rows
	// contains filtered or unexported fields
}

QueryResult wraps sql.Rows with context cancellation

func (*QueryResult) Close

func (r *QueryResult) Close() error

Close closes the rows and cancels the context

type QueryRowResult

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

QueryRowResult wraps sql.Row with context cancellation This ensures the context is not cancelled until Scan() is called

func (*QueryRowResult) Scan

func (r *QueryRowResult) Scan(dest ...interface{}) error

Scan scans the row and cancels the context

type RealCommandExecutor

type RealCommandExecutor = exec.RealCommandExecutor

type RecordedCall

type RecordedCall struct {
	Command string
	Args    []string
	Context context.Context
}

RecordedCall stores information about a command execution.

type TestConfigBuilder

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

TestConfigBuilder provides a fluent API for building test configurations.

This builder allows programmatic creation of dsops.yaml configurations for testing without manually writing YAML strings. It handles cleanup of temporary files automatically.

Example usage:

builder := NewTestConfig(t).
    WithSecretStore("vault", "vault", map[string]any{
        "addr": "http://localhost:8200",
    }).
    WithEnv("test", map[string]config.Variable{
        "DATABASE_URL": {From: &config.Reference{Store: "store://vault/db/url"}},
    })
defer builder.Cleanup()

cfg := builder.Build()

func NewTestConfig

func NewTestConfig(t *testing.T) *TestConfigBuilder

NewTestConfig creates a new TestConfigBuilder.

The builder starts with a minimal valid configuration (version: 1). Use builder methods to add secret stores, services, and environments.

func (*TestConfigBuilder) Build

func (b *TestConfigBuilder) Build() *config.Definition

Build returns the built configuration Definition.

This returns the in-memory configuration object. Use Write() or WriteYAML() if you need a file on disk.

func (*TestConfigBuilder) Cleanup

func (b *TestConfigBuilder) Cleanup()

Cleanup runs all registered cleanup functions.

This is called automatically by t.Cleanup() when using t.TempDir(), but can also be called manually with defer if needed.

func (*TestConfigBuilder) WithEnv

func (b *TestConfigBuilder) WithEnv(name string, vars map[string]config.Variable) *TestConfigBuilder

WithEnv adds an environment configuration.

Parameters:

  • name: The environment name (e.g., "test", "production")
  • vars: Map of variable names to Variable configurations

Returns the builder for method chaining.

func (*TestConfigBuilder) WithProvider

func (b *TestConfigBuilder) WithProvider(name, providerType string, cfg map[string]any) *TestConfigBuilder

WithProvider adds a legacy provider configuration.

This method exists for backward compatibility testing. New tests should use WithSecretStore instead.

Returns the builder for method chaining.

func (*TestConfigBuilder) WithSecretStore

func (b *TestConfigBuilder) WithSecretStore(name, storeType string, cfg map[string]any) *TestConfigBuilder

WithSecretStore adds a secret store configuration.

Parameters:

  • name: The secret store name (used in references)
  • storeType: The store type (e.g., "vault", "aws.secretsmanager", "literal")
  • cfg: Store-specific configuration fields

Returns the builder for method chaining.

func (*TestConfigBuilder) WithService

func (b *TestConfigBuilder) WithService(name, serviceType string, cfg map[string]any) *TestConfigBuilder

WithService adds a service configuration.

Parameters:

  • name: The service name (used in rotation references)
  • serviceType: The service type (e.g., "postgresql", "mongodb", "stripe")
  • cfg: Service-specific configuration fields

Returns the builder for method chaining.

func (*TestConfigBuilder) WithTransform

func (b *TestConfigBuilder) WithTransform(name string, steps []string) *TestConfigBuilder

WithTransform adds a transform pipeline configuration.

Parameters:

  • name: The transform name
  • steps: Transform step names

Returns the builder for method chaining.

func (*TestConfigBuilder) Write

func (b *TestConfigBuilder) Write() string

Write writes the configuration to a temporary file and returns the path.

The file is created in a temporary directory and will be cleaned up automatically by the testing framework.

Returns the absolute path to the written configuration file.

func (*TestConfigBuilder) WriteYAML

func (b *TestConfigBuilder) WriteYAML(path string) error

WriteYAML writes the configuration to a specific path.

Parameters:

  • path: Absolute or relative path to write the YAML file

Returns an error if writing fails.

type TestFixture

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

TestFixture provides convenient access to test fixtures.

This helper loads pre-defined test data from the tests/fixtures/ directory. It caches loaded fixtures to avoid re-reading files.

Example usage:

fixtures := NewTestFixture(t)
cfg := fixtures.LoadConfig("simple.yaml")
secrets := fixtures.LoadJSON("vault-secrets.json")

func NewTestFixture

func NewTestFixture(t *testing.T) *TestFixture

NewTestFixture creates a new TestFixture helper.

The base directory is automatically determined from the project root.

func (*TestFixture) ConfigPath

func (f *TestFixture) ConfigPath(name string) string

ConfigPath returns the absolute path to a config fixture.

Useful when you need the path itself rather than loading the config. Example: ConfigPath("multi-provider.yaml")

func (*TestFixture) LoadConfig

func (f *TestFixture) LoadConfig(name string) *config.Definition

LoadConfig loads a configuration fixture by name.

The name should be relative to tests/fixtures/configs/ Example: LoadConfig("simple.yaml")

Returns a parsed config.Definition or fails the test.

func (*TestFixture) LoadFile

func (f *TestFixture) LoadFile(name string) []byte

LoadFile loads a raw file fixture.

The name should be relative to tests/fixtures/ Returns the file contents as bytes or fails the test.

func (*TestFixture) LoadJSON

func (f *TestFixture) LoadJSON(name string) map[string]any

LoadJSON loads a JSON fixture and returns it as a map.

The name should be relative to tests/fixtures/ Example: LoadJSON("secrets/vault-secrets.json")

Returns a map[string]any or fails the test.

func (*TestFixture) LoadYAML

func (f *TestFixture) LoadYAML(name string) map[string]any

LoadYAML loads a YAML fixture and returns it as a map.

The name should be relative to tests/fixtures/ Example: LoadYAML("services/postgresql.yaml")

Returns a map[string]any or fails the test.

func (*TestFixture) SecretPath

func (f *TestFixture) SecretPath(name string) string

SecretPath returns the absolute path to a secret fixture.

Example: SecretPath("vault-secrets.json")

func (*TestFixture) ServicePath

func (f *TestFixture) ServicePath(name string) string

ServicePath returns the absolute path to a service fixture.

Example: ServicePath("postgresql.yaml")

type TestLogger

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

TestLogger captures log output for validation in tests.

This logger redirects all logging output to an in-memory buffer, allowing tests to verify that secrets are properly redacted and that expected log messages are produced.

Example usage:

logger := NewTestLogger(t)
logger.Info("Processing secret: %s", logging.Secret("password123"))

output := logger.GetOutput()
logger.AssertContains(t, "[REDACTED]")
logger.AssertNotContains(t, "password123")

func NewTestLogger

func NewTestLogger(t *testing.T) *TestLogger

NewTestLogger creates a new TestLogger with default settings.

Debug mode is disabled by default. Use NewTestLoggerWithDebug if you need to capture debug messages.

func NewTestLoggerWithDebug

func NewTestLoggerWithDebug(t *testing.T, debug bool) *TestLogger

NewTestLoggerWithDebug creates a new TestLogger with debug mode enabled.

When debug is true, Debug() method calls will be captured in the buffer.

func (*TestLogger) AssertContains

func (l *TestLogger) AssertContains(t *testing.T, substr string)

AssertContains asserts that the log output contains the specified substring.

This is a convenience wrapper around testify's Contains assertion.

func (*TestLogger) AssertEmpty

func (l *TestLogger) AssertEmpty(t *testing.T)

AssertEmpty asserts that no log output was captured.

Useful for verifying that quiet operations produce no logs.

func (*TestLogger) AssertLogCount

func (l *TestLogger) AssertLogCount(t *testing.T, level string, count int)

AssertLogCount asserts that a specific log level appears a certain number of times.

Level markers:

  • Info: "✓"
  • Warn: "⚠"
  • Error: "✗"
  • Debug: "[DEBUG]"

func (*TestLogger) AssertNotContains

func (l *TestLogger) AssertNotContains(t *testing.T, substr string)

AssertNotContains asserts that the log output does NOT contain the specified substring.

This is particularly useful for verifying that secrets are redacted.

func (*TestLogger) AssertRedacted

func (l *TestLogger) AssertRedacted(t *testing.T, secretValue string)

AssertRedacted asserts that a secret value is redacted in the log output.

This checks that: 1. The secret value itself does NOT appear in logs 2. The [REDACTED] marker DOES appear in logs

This is the primary assertion for security tests.

func (*TestLogger) Capture

func (l *TestLogger) Capture(fn func()) string

Capture executes a function and captures its log output.

This is useful for testing functions that log internally.

Example:

output := logger.Capture(func() {
    someFunction()
})

func (*TestLogger) Clear

func (l *TestLogger) Clear()

Clear clears the captured log output.

This is useful when reusing the same logger across multiple test cases.

func (*TestLogger) Debug

func (l *TestLogger) Debug(format string, args ...interface{})

Debug logs a debug message if debug mode is enabled.

func (*TestLogger) Error

func (l *TestLogger) Error(format string, args ...interface{})

Error logs an error message.

func (*TestLogger) GetOutput

func (l *TestLogger) GetOutput() string

GetOutput returns the captured log output as a string.

The output includes all log messages captured since the logger was created or since the last Clear() call.

func (*TestLogger) Info

func (l *TestLogger) Info(format string, args ...interface{})

Info logs an informational message.

func (*TestLogger) Lines

func (l *TestLogger) Lines() []string

Lines returns the log output split into individual lines.

Empty lines are filtered out. Useful for line-by-line validation.

func (*TestLogger) Warn

func (l *TestLogger) Warn(format string, args ...interface{})

Warn logs a warning message.

type VaultTestClient

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

VaultTestClient wraps Vault HTTP API for testing

func (*VaultTestClient) Delete

func (v *VaultTestClient) Delete(path string) error

Delete deletes a secret from Vault

func (*VaultTestClient) ListSecrets

func (v *VaultTestClient) ListSecrets(path string) ([]string, error)

ListSecrets lists secrets at a path

func (*VaultTestClient) Read

func (v *VaultTestClient) Read(path string) (map[string]interface{}, error)

Read reads a secret from Vault (KV v2)

func (*VaultTestClient) Write

func (v *VaultTestClient) Write(path string, data map[string]interface{}) error

Write writes a secret to Vault (KV v2)

Jump to

Keyboard shortcuts

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