This document is auto-generated from test source files. Run make test-docs to regenerate.
Run make test-cover for current coverage statistics.
Package: internal/config
- TestLoad_ValidConfig: TestLoad_ValidConfig verifies a complete valid YAML config loads with all fields correctly populated
- TestLoad_EnvironmentVariables: TestLoad_EnvironmentVariables verifies ${VAR} in variables.values is expanded from environment. Note: ${VAR} syntax is ONLY valid in variables.values section. Use {{.vars.X}} elsewhere to access imported variables.
- TestLoad_MissingServerHost: TestLoad_MissingServerHost ensures config loading fails when server.host is omitted
- TestLoad_InvalidPort: TestLoad_InvalidPort validates server.port must be in range 1-65535
- TestLoad_InvalidTimeout: TestLoad_InvalidTimeout checks timeout validation: positive values, max >= default
- TestLoad_NoDatabases: TestLoad_NoDatabases ensures at least one database connection is required
- TestLoad_DuplicateDatabaseNames: TestLoad_DuplicateDatabaseNames ensures database names must be unique across connections
- TestLoad_InvalidDatabaseType: TestLoad_InvalidDatabaseType rejects unsupported database types
- TestLoad_SQLiteMissingPath: TestLoad_SQLiteMissingPath ensures SQLite databases require a path field
- TestLoad_SQLServerMissingFields: TestLoad_SQLServerMissingFields validates SQL Server requires host, port, user, password, database
- TestLoad_InvalidLogLevel: TestLoad_InvalidLogLevel rejects log levels other than debug/info/warn/error
- TestLoad_InvalidIsolationLevel: TestLoad_InvalidIsolationLevel rejects invalid SQL Server isolation level names
- TestDatabaseConfig_IsReadOnly: TestDatabaseConfig_IsReadOnly verifies readonly defaults to true when nil
- TestDatabaseConfig_DefaultSessionConfig: TestDatabaseConfig_DefaultSessionConfig checks implicit defaults based on type and readonly flag
- TestValidIsolationLevels: TestValidIsolationLevels checks the ValidIsolationLevels map contains correct entries
- TestValidDeadlockPriorities: TestValidDeadlockPriorities checks the ValidDeadlockPriorities map for low/normal/high
- TestValidJournalModes: TestValidJournalModes checks ValidJournalModes for SQLite: wal/delete/truncate/memory/off
- TestValidDatabaseTypes: TestValidDatabaseTypes checks ValidDatabaseTypes contains expected database types
- TestLoad_VariablesSection: TestLoad_VariablesSection verifies the variables section with values
- TestLoad_VariablesDefaultValues: TestLoad_VariablesDefaultValues verifies ${VAR:default} syntax works correctly
- TestLoad_VariablesEnvFileSupport: TestLoad_VariablesEnvFileSupport verifies loading variables from env file
- TestLoad_VariablesEnvOverridesFile: TestLoad_VariablesEnvOverridesFile verifies actual env vars override env file values
- TestLoad_UndefinedVariable: TestLoad_UndefinedVariable verifies that referencing an undefined variable in templates causes an error
- TestLoad_UndefinedVariableInNumericField: TestLoad_UndefinedVariableInNumericField verifies undefined variable error in pre-rendered numeric fields
- TestIsArrayType: TestIsArrayType verifies IsArrayType correctly identifies array types
- TestArrayBaseType: TestArrayBaseType verifies ArrayBaseType extracts the base type from array types
- TestValidParameterTypes: TestValidParameterTypes verifies all expected parameter types are in ValidParameterTypes
- TestRateLimitConfig_IsPoolReference: TestRateLimitConfig_IsPoolReference verifies IsPoolReference returns true only when Pool is set
- TestRateLimitConfig_IsInline: TestRateLimitConfig_IsInline verifies IsInline returns true only when both RequestsPerSecond and Burst are positive
Package: internal/db
- TestSQLiteDriver_BatchSemantics: TestSQLiteDriver_BatchSemantics verifies the batch contract on SQLite.
- TestMySQLDriver_BatchSemantics: TestMySQLDriver_BatchSemantics verifies the batch contract on MySQL.
- TestSQLServerDriver_BatchSemantics: TestSQLServerDriver_BatchSemantics verifies the batch contract on SQL Server.
- TestMySQLDriver_BatchVariables: TestMySQLDriver_BatchVariables verifies a MySQL user variable survives a batch.
- TestSQLServerDriver_BatchVariables: TestSQLServerDriver_BatchVariables verifies a T-SQL local variable survives a batch.
- BenchmarkSQLiteDriver_SimpleQuery: BenchmarkSQLiteDriver_SimpleQuery measures minimal "SELECT 1" query performance
- BenchmarkSQLiteDriver_SelectAll: BenchmarkSQLiteDriver_SelectAll measures full table scan of 1000 rows
- BenchmarkSQLiteDriver_SelectWithParam: BenchmarkSQLiteDriver_SelectWithParam measures parameterized single-row lookup
- BenchmarkSQLiteDriver_SelectWithMultipleParams: BenchmarkSQLiteDriver_SelectWithMultipleParams measures query with 3 WHERE parameters
- BenchmarkSQLiteDriver_Insert: BenchmarkSQLiteDriver_Insert measures single row insert performance
- BenchmarkSQLiteDriver_ConcurrentReads: BenchmarkSQLiteDriver_ConcurrentReads measures parallel read operations on file-based db
- BenchmarkSQLiteDriver_BuildArgs: BenchmarkSQLiteDriver_BuildArgs measures named-arg construction speed
- BenchmarkManager_Get: BenchmarkManager_Get measures driver lookup by name across 3 databases
- BenchmarkManager_Get_Concurrent: BenchmarkManager_Get_Concurrent measures parallel driver lookups across 3 databases
- BenchmarkSQLiteDriver_LargeResult_100: BenchmarkSQLiteDriver_LargeResult_100 measures fetching 100 row result set
- BenchmarkSQLiteDriver_LargeResult_1000: BenchmarkSQLiteDriver_LargeResult_1000 measures fetching 1000 row result set
- BenchmarkSQLiteDriver_LargeResult_10000: BenchmarkSQLiteDriver_LargeResult_10000 measures fetching 10000 row result set
- BenchmarkSQLiteDriver_ConcurrentWrites: BenchmarkSQLiteDriver_ConcurrentWrites measures serialized parallel writes with mutex
- TestBindValue: TestBindValue verifies json objects and arrays are marshaled to a JSON string for binding while other values pass through.
- TestExecSplitStatements: TestExecSplitStatements verifies the shared split-execute helper runs each statement of a batch on one connection and reports the final statement's result.
- TestExecSplitStatements_EmptyBatch: TestExecSplitStatements_EmptyBatch verifies a batch with no executable statements returns an empty result instead of indexing off the end of the slice.
- TestExecSplitStatements_MidBatchErrorIsNotAtomic: TestExecSplitStatements_MidBatchErrorIsNotAtomic documents that a multi-statement batch is not atomic: when a later statement fails, the earlier statements have already run (autocommit) and the error surfaces. Callers that need all-or-nothing must use explicit BEGIN/COMMIT - which is also why the connection is discarded rather than returned to the pool mid-transaction.
- TestNewDriver_SQLite: TestNewDriver_SQLite verifies factory creates SQLite driver with :memory: path
- TestNewDriver_SQLiteExplicit: TestNewDriver_SQLiteExplicit confirms returned driver is *SQLiteDriver type
- TestNewDriver_EmptyTypeReturnsError: TestNewDriver_EmptyTypeReturnsError ensures empty type is rejected
- TestNewDriver_MySQL: TestNewDriver_MySQL verifies factory creates MySQL driver (requires running MySQL)
- TestNewDriver_Postgres_NotImplemented: TestNewDriver_Postgres_NotImplemented confirms postgres type returns not-implemented error
- TestNewDriver_UnknownType: TestNewDriver_UnknownType rejects unrecognized database types like oracle
- TestNewDriver_SQLiteInvalidPath: TestNewDriver_SQLiteInvalidPath ensures SQLite driver requires non-empty path
- TestDriverInterface_SQLite: TestDriverInterface_SQLite validates SQLiteDriver implements all Driver interface methods
- TestDriverInterface_Polymorphism: TestDriverInterface_Polymorphism verifies multiple drivers work through interface
- TestNewDriver_AllTypes: TestNewDriver_AllTypes table-tests factory behavior for all database type values
- TestSQLiteDriver_LikeEscapeLiteralMatch: TestSQLiteDriver_LikeEscapeLiteralMatch verifies ESCAPE '!' semantics on SQLite.
- TestMySQLDriver_LikeEscapeLiteralMatch: TestMySQLDriver_LikeEscapeLiteralMatch verifies ESCAPE '!' semantics on MySQL.
- TestSQLServerDriver_LikeEscapeLiteralMatch: TestSQLServerDriver_LikeEscapeLiteralMatch verifies ESCAPE '!' semantics on SQL Server.
- TestNewManager_SingleDatabase: TestNewManager_SingleDatabase verifies manager creation with one SQLite database
- TestNewManager_MultipleDatabases: TestNewManager_MultipleDatabases tests manager with three databases, validates Get by name
- TestNewManager_EmptyConfig: TestNewManager_EmptyConfig confirms manager handles zero databases gracefully
- TestNewManager_InvalidConfig: TestNewManager_InvalidConfig ensures manager rejects invalid database config
- TestManager_Get: TestManager_Get tests retrieving connections by name and error for unknown names
- TestManager_Ping: TestManager_Ping checks connectivity to all managed databases individually
- TestManager_Reconnect: TestManager_Reconnect tests single connection re-establishment by name
- TestManager_Close: TestManager_Close ensures all connections are released
- TestManager_ConcurrentAccess: TestManager_ConcurrentAccess runs 100 concurrent Get and Ping operations
- TestManager_ConcurrentReconnect: TestManager_ConcurrentReconnect tests concurrent Reconnect calls to prevent race conditions
- TestManager_MixedDatabaseTypes: TestManager_MixedDatabaseTypes manages SQLite connections with different readonly/settings
- TestBuildMySQLDSN_Default: TestBuildMySQLDSN_Default verifies DSN construction with default port and settings
- TestBuildMySQLDSN_CustomPort: TestBuildMySQLDSN_CustomPort verifies custom port is used in DSN
- TestBuildMySQLDSN_TLSOptions: TestBuildMySQLDSN_TLSOptions tests all TLS/encrypt configuration variants
- TestBuildMySQLDSN_SpecialCharsInPassword: TestBuildMySQLDSN_SpecialCharsInPassword verifies password with special chars is included as-is
- TestMySQLDriver_TranslateQuery: TestMySQLDriver_TranslateQuery tests @param to ? positional placeholder translation
- TestMySQLDriver_TranslateQuery_Values: TestMySQLDriver_TranslateQuery_Values verifies parameter values are correctly ordered
- TestMySQLDriver_TranslateQuery_JSONValue: TestMySQLDriver_TranslateQuery_JSONValue verifies a native json object is bound as JSON text, not as an unbindable map.
- TestMySQLDriver_TranslateQuery_NilValue: TestMySQLDriver_TranslateQuery_NilValue verifies nil values are passed through
- TestMySQLDriver_TranslateQueryRenderedSpans: TestMySQLDriver_TranslateQueryRenderedSpans verifies the @param spans index the parser's RENDERED statement, not the original SQL. A non-canonical query (irregular spacing,
id=@id) renders to a canonical form, and translating THAT form - the text the driver actually runs - rewrites the placeholders correctly. This guards the invariant behind renderedStmt/paramRefs: a driver runs hints.Statements (rendered) with spans into that same rendered text. - TestMySQLIsolationToSQL: TestMySQLIsolationToSQL tests conversion of config isolation strings to MySQL syntax
- TestMySQLDriver_ConfigurePool: TestMySQLDriver_ConfigurePool verifies connection pool settings are applied
- TestMySQLDriver_ConfigValidation: TestMySQLDriver_ConfigValidation tests that invalid configs produce errors
- TestNewMySQLDriver_Integration: TestNewMySQLDriver_Integration verifies driver creation against a real MySQL instance
- TestNewMySQLDriver_ReadWrite: TestNewMySQLDriver_ReadWrite confirms explicit readonly=false enables write mode
- TestMySQLDriver_Ping: TestMySQLDriver_Ping confirms Ping returns nil for healthy connection
- TestMySQLDriver_Reconnect: TestMySQLDriver_Reconnect tests connection re-establishment after close
- TestMySQLDriver_Config: TestMySQLDriver_Config verifies Config() returns original configuration
- TestMySQLDriver_Query_Simple: TestMySQLDriver_Query_Simple executes basic SELECT and validates returned columns
- TestMySQLDriver_Query_WithParams: TestMySQLDriver_Query_WithParams verifies @param named parameters work correctly
- TestMySQLDriver_Query_NullParams: TestMySQLDriver_Query_NullParams tests NULL parameter handling for optional filters
- TestMySQLDriver_Query_EmptyResult: TestMySQLDriver_Query_EmptyResult confirms empty result set returns zero-length slice
- TestMySQLDriver_Query_Timeout: TestMySQLDriver_Query_Timeout verifies context deadline expiration stops query
- TestMySQLDriver_Query_SpecialCharacters: TestMySQLDriver_Query_SpecialCharacters ensures SQL injection strings are safely escaped
- TestMySQLDriver_Query_Unicode: TestMySQLDriver_Query_Unicode validates CJK, Cyrillic, Arabic, and emoji preservation
- TestMySQLDriver_WriteOperations_RowsAffected: TestMySQLDriver_WriteOperations_RowsAffected tests that write operations return correct rows affected
- TestMySQLDriver_Query_Concurrent: TestMySQLDriver_Query_Concurrent runs parallel queries against MySQL
- TestMySQLDriver_MultiStatementSplit: TestMySQLDriver_MultiStatementSplit verifies a parameterized multi-statement batch runs via split-and-execute and reports the trailing statement's result.
- TestMySQLDriver_MultiStatementTrailingComment: TestMySQLDriver_MultiStatementTrailingComment verifies a batch ending in a comment still returns the real trailing result rather than the comment's empty query silently clobbering it.
- TestMySQLDriver_BackslashEscapedLiteral: TestMySQLDriver_BackslashEscapedLiteral verifies a string literal containing a backslash-escaped quote and a semicolon is treated as one statement, not mis-split into invalid fragments.
- TestMySQLDriver_MultiStatementRouting: TestMySQLDriver_MultiStatementRouting verifies batch routing on the split path: a write-only batch reports the final statement's affected count and no rows, and an explicit returns:affected hint forces Exec even when the batch ends in a SELECT (the compiled hint must be honored, not ignored).
- TestMySQLDriver_ReadOnlyGuardRejectsWrites: TestMySQLDriver_ReadOnlyGuardRejectsWrites verifies the driver's read-only guard rejects a write on a read-only connection while still serving reads.
- TestNewSQLiteDriver_InMemory: TestNewSQLiteDriver_InMemory verifies in-memory SQLite driver creation with :memory: path
- TestNewSQLiteDriver_ReadWrite: TestNewSQLiteDriver_ReadWrite confirms explicit readonly=false enables write mode
- TestNewSQLiteDriver_MissingPath: TestNewSQLiteDriver_MissingPath ensures empty path is rejected with clear error
- TestBuildSQLiteDSN: TestBuildSQLiteDSN verifies DSN construction: in-memory passthrough, the file: URI prefix that makes mode=ro actually take effect, and path encoding.
- TestNewSQLiteDriver_ReadOnlyRejectsWrites: TestNewSQLiteDriver_ReadOnlyRejectsWrites verifies a read-only connection can read an existing database but rejects writes. The driver's read-only guard rejects the write before it reaches SQLite (mode=ro is deeper defense; that the DSN carries mode=ro is asserted by TestBuildSQLiteDSN, and that it blocks file creation by TestNewSQLiteDriver_ReadOnlyMissingFileNotCreated).
- TestSQLiteEngineRejectsWritesOnReadOnlyDSN: TestSQLiteEngineRejectsWritesOnReadOnlyDSN verifies the mode=ro layer itself: SQLite refuses the write, with no help from the driver's guard. The guard runs first in SQLiteDriver.Query, so without this the engine-level defense the README lists would be untested and a DSN change could drop mode=ro unnoticed.
- TestNewSQLiteDriver_ReadOnlyMissingFileNotCreated: TestNewSQLiteDriver_ReadOnlyMissingFileNotCreated verifies opening a read-only connection to a missing file fails and does not create the file - the mode=ro behavior that makes -validate report a typo'd path instead of it.
- TestSQLiteDriver_BatchRouting: TestSQLiteDriver_BatchRouting verifies multi-statement batches route on their final statement: one ending in a write reports an affected count, one ending in a read returns rows.
- TestSQLiteDriver_MultiStatementWithParams: TestSQLiteDriver_MultiStatementWithParams exercises a parameterized multi-statement batch through the native driver path in a loop. modernc v1.43.0 crashed (SIGSEGV) here; this guards against a regression in the pinned driver version.
- TestSQLiteDriver_LikeParamWildcardsAreNotEscaped: TestSQLiteDriver_LikeParamWildcardsAreNotEscaped documents that a raw bound parameter is not LIKE-escaped, so its wildcards still expand.
- TestNewSQLiteDriver_CustomSettings: TestNewSQLiteDriver_CustomSettings verifies busy_timeout and journal_mode PRAGMAs apply
- TestNewSQLiteDriver_InMemoryIsSingleConnection: TestNewSQLiteDriver_InMemoryIsSingleConnection verifies an in-memory database is pinned to one pooled connection. Each connection to :memory: opens its own empty database, so a second one loses every table the first created.
- TestSQLiteDriver_Query_JSONParam: TestSQLiteDriver_Query_JSONParam verifies a native json object binds as JSON text rather than failing as an unbindable map.
- TestSQLiteDriver_Query_Simple: TestSQLiteDriver_Query_Simple executes basic SELECT and validates returned columns
- TestSQLiteDriver_Query_WithParams: TestSQLiteDriver_Query_WithParams verifies @param named parameters work correctly
- TestSQLiteDriver_Query_NullParams: TestSQLiteDriver_Query_NullParams tests NULL parameter handling for optional filters
- TestSQLiteDriver_Query_EmptyResult: TestSQLiteDriver_Query_EmptyResult confirms empty result set returns zero-length slice
- TestSQLiteDriver_Query_DateTimeHandling: TestSQLiteDriver_Query_DateTimeHandling tests time.Time parameter binding and retrieval
- TestSQLiteDriver_Query_SpecialCharacters: TestSQLiteDriver_Query_SpecialCharacters ensures SQL injection strings are safely escaped
- TestSQLiteDriver_Query_Unicode: TestSQLiteDriver_Query_Unicode validates CJK, Cyrillic, Arabic, and emoji preservation
- TestSQLiteDriver_Query_LargeResult: TestSQLiteDriver_Query_LargeResult tests handling of 10000 row result sets
- TestSQLiteDriver_Query_Timeout: TestSQLiteDriver_Query_Timeout verifies context deadline expiration stops query
- TestSQLiteDriver_Query_Concurrent: TestSQLiteDriver_Query_Concurrent runs 100 parallel queries with file-based SQLite
- TestSQLiteDriver_Ping: TestSQLiteDriver_Ping confirms Ping returns nil for healthy connection
- TestSQLiteDriver_Reconnect: TestSQLiteDriver_Reconnect tests connection re-establishment after close
- TestSQLiteDriver_Config: TestSQLiteDriver_Config verifies Config() returns original configuration
- TestSQLiteDriver_BuildArgs: TestSQLiteDriver_BuildArgs verifies one sql.Named arg is built per distinct param (repeated names deduplicate); SQLite binds @param natively, so the query is unchanged.
- TestSQLiteDriver_WriteOperations_RowsAffected: TestSQLiteDriver_WriteOperations_RowsAffected tests that write operations return correct rows affected
- TestIsolationToSQL: TestIsolationToSQL tests conversion of config isolation strings to SQL Server syntax
- TestDeadlockPriorityToSQL: TestDeadlockPriorityToSQL tests conversion of config deadlock priority strings to SQL Server syntax
- TestSQLServerDriver_BuildArgs: TestSQLServerDriver_BuildArgs verifies parameter extraction from SQL
- TestSQLServerDriver_BuildArgs_Values: TestSQLServerDriver_BuildArgs_Values verifies parameter values are correctly assigned
- TestSQLServerDriver_BuildArgs_JSONValue: TestSQLServerDriver_BuildArgs_JSONValue verifies a native json object is bound as JSON text, not as an unbindable map.
- TestSQLServerDriver_BuildArgs_NilValue: TestSQLServerDriver_BuildArgs_NilValue verifies nil values are handled correctly
- TestSQLServerDriver_MultiStatementWithParams: TestSQLServerDriver_MultiStatementWithParams verifies SQL Server runs a parameterized multi-statement batch natively (no split) and returns the trailing SELECT's rows.
- TestSQLServerDriver_MultiStatementRouting: TestSQLServerDriver_MultiStatementRouting verifies batch routing on the native path: a returns:affected hint forces Exec even when the batch ends in a SELECT, exposing no rows (the compiled hint must be honored).
- TestSQLServerDriver_ReadOnlyGuardRejectsWrites: TestSQLServerDriver_ReadOnlyGuardRejectsWrites verifies the driver's read-only guard rejects a write on a read-only connection. SQL Server has no connection- level read-only for a writable database (ApplicationIntent=ReadOnly only does AG read-routing), so this guard is the sole runtime enforcement.
Package: internal/validate
- TestResult_AddError: TestResult_AddError verifies error accumulation marks result as invalid
- TestResult_AddWarning: TestResult_AddWarning confirms warnings don't affect valid flag
- TestValidateServer: TestValidateServer tests server port and timeout validation rules
- TestValidateDatabase_Empty: TestValidateDatabase_Empty ensures empty database list is rejected
- TestValidateDatabase_Duplicate: TestValidateDatabase_Duplicate ensures duplicate database names are rejected
- TestValidateDatabase_InvalidType: TestValidateDatabase_InvalidType ensures unsupported database types are rejected
- TestValidateDatabase_LintsOff: TestValidateDatabase_LintsOff verifies lints_off accepts known lint ids and rejects an unknown one (a typo would silently silence nothing).
- TestValidateDatabase_SQLite: TestValidateDatabase_SQLite tests SQLite-specific validation: path, journal mode, timeout
- TestValidateDatabase_SQLServer: TestValidateDatabase_SQLServer tests SQL Server validation: host, port, isolation, timeout
- TestValidateDatabase_MySQL: TestValidateDatabase_MySQL tests MySQL-specific validation: host, port, user, password, database, isolation
- TestValidateDatabase_EnvVarWarning: TestValidateDatabase_EnvVarWarning tests unresolved env vars generate warnings
- TestValidateLogging: TestValidateLogging tests log level and rotation settings validation
- TestValidateDebug: TestValidateDebug tests debug config validation rules
- TestRun_ValidConfig: TestRun_ValidConfig tests complete valid configuration passes all checks
- TestRun_InvalidConfig: TestRun_InvalidConfig tests configuration with invalid port fails validation
- TestRun_DBConnectionTest: TestRun_DBConnectionTest verifies SQLite :memory: connection succeeds
- TestRun_DBConnectionFail: TestRun_DBConnectionFail verifies invalid SQLite path fails connection test
- TestRun_SQLiteWritableMissingFileValidatesWithoutCreating: TestRun_SQLiteWritableMissingFileValidatesWithoutCreating verifies that validating a writable, file-backed SQLite database whose file does not yet exist passes (the server creates it on first connect at startup) and does not create the file as a side effect of validation.
- TestRun_SQLiteWritableMissingParentDirFails: TestRun_SQLiteWritableMissingParentDirFails verifies that a writable, file-backed SQLite database whose parent directory does not exist fails validation - SQLite does not create intermediate directories, so the server could not create the file at boot. The failure must surface at validation rather than being deferred to a boot-time "unable to open database file".
- TestRun_SQLiteReadOnlyMissingFileFails: TestRun_SQLiteReadOnlyMissingFileFails verifies that validating a read-only SQLite database whose file does not exist fails - a read-only database can never create its own file, so a missing path is a guaranteed runtime failure that must surface at validation. The file must not be created either.
- TestRun_SQLiteExistingFileValidates: TestRun_SQLiteExistingFileValidates verifies that a writable, file-backed SQLite database whose file already exists passes the connectivity test.
- TestRun_SQLServerUnresolvedEnvVar: TestRun_SQLServerUnresolvedEnvVar tests that SQL Server with unresolved env vars is skipped during connection test
- TestRun_SQLServerUnresolvedPassword: TestRun_SQLServerUnresolvedPassword tests SQL Server with unresolved password env var is skipped
- TestValidateServerCache: TestValidateServerCache tests server-level cache configuration validation
- TestValidateRateLimits: TestValidateRateLimits tests server-level rate limit pool validation
- TestRun_NoWorkflowsWarning: TestRun_NoWorkflowsWarning tests that empty workflows list generates a warning
- TestValidatePublicIDs: TestValidatePublicIDs tests public ID configuration validation
- TestValidatePublicIDFunctionUsageWithoutConfig: ValidatePublicIDFunctionUsageWithoutConfig
Package: internal/server
- TestServer_New: TestServer_New verifies server initialization creates dbManager and httpServer
- TestServer_RunLifecycleWorkflows: TestServer_RunLifecycleWorkflows verifies lifecycle workflows run in order and report failures
- TestDrainContext: TestDrainContext verifies the HTTP drain reserves time for shutdown workflows
- TestServer_Shutdown_RunsShutdownWorkflows: TestServer_Shutdown_RunsShutdownWorkflows verifies Shutdown wiring, not just the runner
- TestServer_HealthHandler: TestServer_HealthHandler tests /health returns status and database connections
- TestServer_MetricsHandler_Disabled: TestServer_MetricsHandler_Disabled tests /_/metrics.json returns not-enabled message when disabled
- TestServer_MetricsJSONHandler_Enabled: TestServer_MetricsJSONHandler_Enabled tests /_/metrics.json returns valid JSON metrics
- TestServer_MetricsPrometheusHandler_Enabled: TestServer_MetricsPrometheusHandler_Enabled tests /_/metrics returns Prometheus format
- TestServer_MetricsPrometheusHandler_Disabled: TestServer_MetricsPrometheusHandler_Disabled tests /_/metrics returns error when disabled
- TestServer_LogLevelHandler: TestServer_LogLevelHandler tests log level GET retrieval and POST update operations
- TestServer_ListEndpointsHandler: TestServer_ListEndpointsHandler tests root path returns service info and workflow listing
- TestServer_ListEndpointsHandler_NotFound: TestServer_ListEndpointsHandler_NotFound tests unknown paths return 404
- TestServer_OpenAPIHandler: TestServer_OpenAPIHandler tests /openapi.json returns valid spec with CORS headers
- TestServer_RecoveryMiddleware: TestServer_RecoveryMiddleware tests panic recovery returns 500 without server crash
- TestServer_GzipMiddleware: TestServer_GzipMiddleware tests gzip compression when Accept-Encoding header set
- TestServer_GzipMiddleware_NoGzip: TestServer_GzipMiddleware_NoGzip tests no compression without Accept-Encoding header
- TestServer_StartShutdown: TestServer_StartShutdown tests server start and graceful shutdown sequence
- TestServer_Integration_WorkflowEndpoint: TestServer_Integration_WorkflowEndpoint tests workflow execution via httptest server
- TestServer_Integration_ParameterizedWorkflow: TestServer_Integration_ParameterizedWorkflow tests parameterized workflow with required and optional params
- TestServer_Integration_WithGzip: TestServer_Integration_WithGzip tests HTTP request/response cycle with gzip encoding
- TestServer_HealthHandler_Degraded: TestServer_HealthHandler_Degraded tests /health returns degraded status when database is unreachable
- TestServer_HealthHandler_DatabaseDown: TestServer_HealthHandler_DatabaseDown tests /_/health shows database as disconnected when ping fails
- TestServer_HealthHandler_MultipleDatabases: TestServer_HealthHandler_MultipleDatabases tests /_/health with multiple database connections
- TestServer_DBHealthHandler: TestServer_DBHealthHandler tests /_/health/{dbname} endpoint
- TestServer_DBHealthHandler_Disconnected: TestServer_DBHealthHandler_Disconnected tests /_/health/{dbname} when db is down
- TestServer_CacheClearHandler: TestServer_CacheClearHandler tests /_/cache/clear endpoint
- TestServer_RegisterWorkflowCaches: TestServer_RegisterWorkflowCaches verifies a workflow that caches gets tracked space in the cache, which is what makes clearing it by name possible, and that a workflow with no cache gets none.
- TestServer_CacheClearHandler_NoCacheConfigured: TestServer_CacheClearHandler_NoCacheConfigured tests cache clear when cache disabled
- TestServer_RateLimitsHandler: TestServer_RateLimitsHandler tests the /_/ratelimits endpoint
- TestServer_RateLimitsHandler_NotConfigured: TestServer_RateLimitsHandler_NotConfigured tests the endpoint when rate limiting is disabled
- TestServer_RateLimitsResetHandler: TestServer_RateLimitsResetHandler tests the /_/ratelimits/reset endpoint
- TestServer_RateLimitResponse: TestServer_RateLimitResponse tests that 429 response includes retry_after_sec
- TestServer_CronWorkflowSetup: TestServer_CronWorkflowSetup verifies cron workflow jobs are registered correctly
- TestServer_CronWorkflowExecution: TestServer_CronWorkflowExecution verifies cron workflow execution path works
- TestServer_NoCronWorkflow: TestServer_NoCronWorkflow verifies server works without cron triggers
- TestStatusWriter_CapturesStatus: StatusWriter CapturesStatus
- TestStatusWriter_DefaultsTo200OnWrite: StatusWriter DefaultsTo200OnWrite
- TestSkipIfRunning: TestSkipIfRunning verifies the cron overlap guard drops an overlapping run without blocking, and admits runs again afterwards.
- TestServer_CronJobFunc: TestServer_CronJobFunc verifies a cron trigger is wrapped according to its on_overlap setting.
- TestValidateMatchesServerStartup: TestValidateMatchesServerStartup verifies -validate accepts exactly the configs the server accepts. A validator more permissive than the engine defers errors to boot; a stricter one refuses valid configs.
- TestShippedMySQLExamplesCompile: TestShippedMySQLExamplesCompile verifies the mysql examples' workflows compile, without needing a MySQL server. validate.Run cannot cover them - it opens a real connection - so this stops at workflow.Build, which touches no database.
- TestShippedExamples: TestShippedExamples verifies every example config validates, starts, and answers with a well-formed body. make validate-examples only proves they validate; a response template can parse and still emit broken JSON.
- TestValidateReportsAllBrokenWorkflows: TestValidateReportsAllBrokenWorkflows verifies validation reports every broken workflow rather than stopping at the first. One -validate run must surface the whole list.
Package: internal/logging
- TestInit_Stdout: TestInit_Stdout verifies logger initialization to stdout sets correct level
- TestInit_FileOutput: TestInit_FileOutput tests logger initialization creates log directory and file
- TestSetLevel: TestSetLevel tests dynamic log level changes including case handling
- TestGetLevel: TestGetLevel verifies GetLevel returns correct string for each slog level
- TestParseLevel: TestParseLevel tests string to slog.Level parsing with case insensitivity
- TestMapToAttrs: TestMapToAttrs tests map to slog attribute slice conversion
- TestLogFunctions: TestLogFunctions tests Debug, Info, Warn, Error output to buffer
- TestLogFunctions_NilFields: TestLogFunctions_NilFields verifies log functions handle nil field maps without panic
- TestClose_NoFile: TestClose_NoFile tests Close handles nil file closer gracefully
- TestClose_WithFile: TestClose_WithFile tests Close properly closes log file handle
- TestInit_InvalidDirectory: TestInit_InvalidDirectory tests Init handles permission-denied paths without panic
Package: internal/metrics
- BenchmarkRecord: BenchmarkRecord measures single metric recording throughput
- BenchmarkRecord_Concurrent: BenchmarkRecord_Concurrent measures parallel metric recording with RunParallel
- BenchmarkRecord_MultipleEndpoints: BenchmarkRecord_MultipleEndpoints measures recording across 5 different endpoints
- BenchmarkGetSnapshot: BenchmarkGetSnapshot measures snapshot retrieval with 10 pre-populated endpoints
- BenchmarkGetSnapshot_Concurrent: BenchmarkGetSnapshot_Concurrent measures parallel snapshot reads under load
- BenchmarkRecord_WithError: BenchmarkRecord_WithError measures error metric recording with status 500
- BenchmarkRecord_WithTimeout: BenchmarkRecord_WithTimeout measures timeout metric recording with status 504
- BenchmarkInit: BenchmarkInit measures collector initialization throughput
- BenchmarkMixedWorkload: BenchmarkMixedWorkload simulates real-world usage: 90% success, 10% error, 1% snapshots
- TestGlobalCollectorSwapsUnderConcurrentReaders: TestGlobalCollectorSwapsUnderConcurrentReaders verifies installing and removing the global collector is safe while other goroutines are reporting through it. A server's health checker, its metrics updater and its request handlers all read the collector for as long as they run, and Init or Clear can land at any point in that window - which is what a service restarting its metrics, or a test clearing them, actually does. Run this with -race; without it the unsynchronized version passes.
- TestInit: TestInit verifies metrics collector initialization with health checker
- TestRecord_NoCollector: TestRecord_NoCollector verifies Record handles nil collector without panic
- TestRecord: TestRecord tests request metric recording and snapshot retrieval
- TestRecord_Error: TestRecord_Error tests error counter increment on 500 status
- TestRecord_Timeout: TestRecord_Timeout tests timeout counter increment on 504 status
- TestRecord_MinMaxDuration: TestRecord_MinMaxDuration tests min/max duration tracking across requests
- TestRecord_Averages: TestRecord_Averages tests average duration calculation for total and query times
- TestGetSnapshot_NoCollector: TestGetSnapshot_NoCollector verifies nil return when collector not initialized
- TestGetSnapshot_RuntimeStats: TestGetSnapshot_RuntimeStats verifies Go runtime stats in snapshot
- TestGetSnapshot_Uptime: TestGetSnapshot_Uptime tests uptime calculation in snapshot
- TestGetSnapshot_DBHealth: TestGetSnapshot_DBHealth tests database health status via checker function
- TestRecord_Concurrent: TestRecord_Concurrent tests thread-safe metric recording with 100 goroutines
- TestRecord_MultipleEndpoints: TestRecord_MultipleEndpoints tests separate stats tracking per endpoint
- TestEndpointStats_Fields: TestEndpointStats_Fields verifies all endpoint stat fields are populated
- TestSnapshot_Timestamp: TestSnapshot_Timestamp verifies snapshot timestamp is set correctly
- TestSnapshot_Version: TestSnapshot_Version verifies version and buildTime are included in snapshot
- TestSnapshot_EmptyVersion: TestSnapshot_EmptyVersion verifies empty version/buildTime are handled correctly
- TestSetRateLimitSnapshotProvider: TestSetRateLimitSnapshotProvider verifies rate limit metrics are included in snapshot
- TestSetRateLimitSnapshotProvider_NoCollector: TestSetRateLimitSnapshotProvider_NoCollector verifies nil collector handling
- TestSnapshot_BothCacheAndRateLimits: TestSnapshot_BothCacheAndRateLimits verifies both cache and rate limit metrics work together
Package: internal/openapi
- TestSpec_BasicStructure: TestSpec_BasicStructure verifies OpenAPI spec has required root elements
- TestSpec_BuiltInPaths: TestSpec_BuiltInPaths verifies /health, /metrics, /config/loglevel paths are present
- TestSpec_DocumentsEveryInternalEndpoint: TestSpec_DocumentsEveryInternalEndpoint verifies every route the server registers appears in the spec, under the methods the handler accepts. The list is the one in setupRoutes, minus the pprof handlers, which are only mounted with debug on.
- TestSpec_WorkflowEndpoints: TestSpec_WorkflowEndpoints tests workflow config generates correct path operations
- TestSpec_SkipsCronOnlyWorkflows: TestSpec_SkipsCronOnlyWorkflows verifies cron-only workflows are excluded from paths
- TestBuildOperation_GET: TestBuildOperation_GET tests GET operation generation with parameters and tags
- TestSpec_MethodMapping: TestSpec_MethodMapping verifies every HTTP method a trigger may declare becomes its own lowercase operation key, not just POST as post and everything else as get.
- TestSpec_MergesMethodsOnOnePath: TestSpec_MergesMethodsOnOnePath verifies triggers sharing a path each contribute an operation to one path item instead of overwriting each other, and that the operationIds stay unique when one workflow serves several methods.
- TestBuildOperation_PathParameters: TestBuildOperation_PathParameters verifies a parameter named in the path is documented in: path and required, while the rest stay in: query.
- TestBuildOperation_RequestBody: TestBuildOperation_RequestBody verifies a JSON request body is documented for the methods that carry one, holds only the non-path parameters, and marks nothing required (a required parameter may arrive in the query string instead).
- TestBuildOperation_RequestBodyOmittedWithoutBodyParams: TestBuildOperation_RequestBodyOmittedWithoutBodyParams verifies a body-carrying method whose only parameters come from the path documents no request body.
- TestBuildOperation_Responses: TestBuildOperation_Responses verifies 400, 500, 504 are always documented and 429 appears only when the trigger declares a rate limit.
- TestBuildOperation_ResponseStepStatusCodes: TestBuildOperation_ResponseStepStatusCodes verifies a response step's status_code is documented, that an unconditional response step replaces the handler's default success body, and that a conditional one leaves it in place.
- TestBuildOperation_HeadHasNoBody: TestBuildOperation_HeadHasNoBody verifies a HEAD operation documents status codes and headers but no body, because net/http discards whatever the response step wrote. Every other method keeps its body.
- TestBuildOperation_DisabledResponseStepIgnored: TestBuildOperation_DisabledResponseStepIgnored verifies a disabled response step contributes no status code, since it never runs.
- TestBuildOperation_ResponseHeaders: TestBuildOperation_ResponseHeaders verifies X-Request-ID is always documented, X-Server-Version only when the binary reports a version, and X-Cache only when the trigger really caches.
- TestBuildOperation_RequestControls: TestBuildOperation_RequestControls verifies _nocache is documented as a boolean and _timeout as an integer that is rejected rather than clamped, both described as query-string only.
- TestBuildOperation_NoCacheDescribedAsInertWithoutCache: TestBuildOperation_NoCacheDescribedAsInertWithoutCache verifies _nocache says so on an endpoint that does not cache, rather than promising an effect it has not.
- TestBuildParamDescription: TestBuildParamDescription tests parameter description includes type and default
- TestParamTypeToSchema: TestParamTypeToSchema tests parameter type to JSON Schema conversion
- TestBuildComponents: TestBuildComponents verifies required schema definitions are present, and that every schema a path refers to is defined.
- TestBuildComponents_WorkflowResponseIsWhatTheHandlerSends: TestBuildComponents_WorkflowResponseIsWhatTheHandlerSends verifies the default success body advertises only the fields the handler actually writes. It reported a data array and a row count for a long time, and neither is ever emitted.
- TestSpec_EverySchemaRefIsDefined: TestSpec_EverySchemaRefIsDefined verifies no path refers to a component schema that buildComponents does not define.
- TestSpec_ValidJSON: TestSpec_ValidJSON verifies spec serializes to valid JSON and back
- TestSpec_TimeoutParameter: TestSpec_TimeoutParameter tests _timeout param has correct default and maximum
- TestSpec_WorkflowDescription: TestSpec_WorkflowDescription tests custom timeout info in spec
- TestParamTypeToSchema_ArrayTypes: TestParamTypeToSchema_ArrayTypes tests array type schema generation
- TestParamTypeToSchema_JSONType: TestParamTypeToSchema_JSONType tests json type schema generation
- TestBuildOperation_DefaultTimeout: TestBuildOperation_DefaultTimeout tests server default timeout used when workflow has none
- TestSpec_RestCrudExample: TestSpec_RestCrudExample generates the spec for a shipped config and checks the things a hand-built config cannot: that six triggers sharing one path survive as six operations, and that their declared status codes come through.
- TestSpec_UniqueOperationIDs: TestSpec_UniqueOperationIDs verifies no two operations in a shipped config share an operationId, which would make the document invalid.
Package: internal/service
- TestDefaultServiceName: TestDefaultServiceName verifies the default service name constant
- TestJoinErrors: TestJoinErrors verifies error joining function
Package: internal/cache
- TestNew: TestNew verifies cache creation with different configurations
- TestCache_GetSet: TestCache_GetSet tests basic cache operations
- TestCache_Delete: TestCache_Delete tests cache entry deletion
- TestCache_Clear: TestCache_Clear tests clearing all entries for an endpoint
- TestCache_ClearAll: TestCache_ClearAll tests clearing entire cache
- TestCache_TTL: TestCache_TTL tests TTL expiration
- TestCache_GetSnapshot: TestCache_GetSnapshot tests metrics snapshot
- TestCache_TTLRemaining: TestCache_TTLRemaining tests remaining TTL calculation
- TestCache_NilSafe: TestCache_NilSafe tests that nil cache is handled safely
- TestCache_MultipleEndpoints: TestCache_MultipleEndpoints tests independent tracking per endpoint
- TestCache_PerEndpointSizeLimit: TestCache_PerEndpointSizeLimit tests per-endpoint size limits trigger eviction
- TestRegisterEndpoint_CronEviction: TestRegisterEndpoint_CronEviction tests cron-based eviction setup
- TestClear_RequiresRegistration: TestClear_RequiresRegistration verifies Clear empties a registered endpoint and reports how many entries went, and that it reports -1 for an endpoint nobody registered rather than claiming to have cleared it. An unregistered endpoint still caches - only ClearAll can empty it.
- TestExpiredEntriesReleaseTheirMetadata: TestExpiredEntriesReleaseTheirMetadata verifies an entry that ristretto expires on its own also loses its per-endpoint metadata. That metadata is only removed by Delete/Clear otherwise, so without the eviction callback a workflow whose cache key varies per request - a client IP, a row id - would accumulate a metadata entry for every key ever cached and never release one.
- TestClose_WithEntriesStillCached: TestClose_WithEntriesStillCached verifies shutting down a cache that still holds entries finishes. Closing clears the store, which fires the eviction callback for every entry left in it, and that callback takes the same lock Close needs - so holding the lock across the close deadlocks shutdown against itself.
- TestRegisterEndpoint_ReplacesPriorRegistration: TestRegisterEndpoint_ReplacesPriorRegistration verifies registering the same endpoint twice replaces the earlier registration, so the second call decides the eviction schedule. The Stop on the replaced cron is not directly observable - robfig's Entries still reports a stopped scheduler's entries - so this covers the replacement, not the goroutine it releases.
- TestCache_UpdateExistingKey: TestCache_UpdateExistingKey tests updating an existing cached entry
- TestCache_DefaultTTL: TestCache_DefaultTTL tests that TTL=0 uses server default TTL
- TestCache_UnregisteredEndpoint: TestCache_UnregisteredEndpoint tests operations on endpoints not explicitly registered
- TestCalculateSize: TestCalculateSize tests size calculation for cache entries
- TestGetOrCompute: TestGetOrCompute tests the GetOrCompute method
- TestGetOrCompute_Error: TestGetOrCompute_Error tests error handling in GetOrCompute
- TestGetOrCompute_NilCache: TestGetOrCompute_NilCache tests GetOrCompute with nil cache
- TestGetOrCompute_Singleflight: TestGetOrCompute_Singleflight tests that singleflight prevents stampedes
- TestCache_EvictFromEndpoint: TestCache_EvictFromEndpoint tests LRU eviction when per-endpoint size is exceeded
- TestCache_EvictionMetrics: TestCache_EvictionMetrics tests that eviction metrics are properly tracked
- TestCache_CronEvictionExecution: TestCache_CronEvictionExecution tests that cron eviction runs and clears cache
- TestCache_ClearTriggersEvictionMetric: TestCache_ClearTriggersEvictionMetric tests that Clear increments eviction count
Package: internal/tmpl
- BenchmarkEngine_CacheKey_Simple: BenchmarkEngine_CacheKey_Simple benchmarks simple cache key like "items:{{.trigger.params.status}}"
- BenchmarkEngine_CacheKey_MultiParam: BenchmarkEngine_CacheKey_MultiParam benchmarks cache key with multiple params
- BenchmarkEngine_CacheKey_WithDefault: BenchmarkEngine_CacheKey_WithDefault benchmarks cache key with default fallback
- BenchmarkEngine_RateLimit_ClientIP: BenchmarkEngine_RateLimit_ClientIP benchmarks simple rate limit key
- BenchmarkEngine_RateLimit_Composite: BenchmarkEngine_RateLimit_Composite benchmarks composite rate limit key
- BenchmarkEngine_RateLimit_HeaderRequired: BenchmarkEngine_RateLimit_HeaderRequired benchmarks rate limit with required header
- BenchmarkEngine_ExecuteInline: BenchmarkEngine_ExecuteInline benchmarks inline (non-cached) template execution
- BenchmarkEngine_Register: BenchmarkEngine_Register benchmarks template registration/compilation
- BenchmarkEngine_Validate: BenchmarkEngine_Validate benchmarks template validation
- BenchmarkEngine_ValidateWithParams: BenchmarkEngine_ValidateWithParams benchmarks template validation with param checking
- BenchmarkContextBuilder_Simple: BenchmarkContextBuilder_Simple benchmarks basic context building
- BenchmarkContextBuilder_WithHeaders: BenchmarkContextBuilder_WithHeaders benchmarks context with many headers
- BenchmarkExtractParamRefs_Simple: BenchmarkExtractParamRefs_Simple benchmarks simple param extraction
- BenchmarkExtractParamRefs_Complex: BenchmarkExtractParamRefs_Complex benchmarks complex param extraction
- BenchmarkFunc_RequireFunc: BenchmarkFunc_RequireFunc benchmarks require function
- BenchmarkFunc_GetOrFunc: BenchmarkFunc_GetOrFunc benchmarks getOr function
- BenchmarkFunc_HasFunc: BenchmarkFunc_HasFunc benchmarks has function
- BenchmarkFunc_JSONFunc: BenchmarkFunc_JSONFunc benchmarks JSON serialization
- BenchmarkFunc_CoalesceFunc: BenchmarkFunc_CoalesceFunc benchmarks coalesce function
- BenchmarkEngine_Concurrent_SameTemplate: BenchmarkEngine_Concurrent_SameTemplate benchmarks concurrent access to same template
- BenchmarkEngine_Concurrent_DifferentTemplates: BenchmarkEngine_Concurrent_DifferentTemplates benchmarks concurrent access to different templates
- BenchmarkContextBuilder_Concurrent: BenchmarkContextBuilder_Concurrent benchmarks concurrent context building
- TestNewContextBuilder: TestNewContextBuilder tests builder creation
- TestContextBuilder_Build: TestContextBuilder_Build tests context creation from HTTP request
- TestContextBuilder_Build_NilParams: TestContextBuilder_Build_NilParams tests build with nil params
- TestContextBuilder_ResolveClientIP_NoProxy: TestContextBuilder_ResolveClientIP_NoProxy tests IP resolution without proxy headers
- TestContextBuilder_ResolveClientIP_WithProxy: TestContextBuilder_ResolveClientIP_WithProxy tests IP resolution with proxy headers
- TestContextBuilder_GetRequestID: TestContextBuilder_GetRequestID tests request ID extraction
- TestContext_ToMap: TestContext_ToMap tests context conversion to map
- TestExtractParamRefs: TestExtractParamRefs tests param reference extraction
- TestContext_Integration: TestContext_Integration tests full context usage with engine
- BenchmarkContextBuilder_Build: BenchmarkContextBuilder_Build benchmarks context creation
- BenchmarkExtractParamRefs: BenchmarkExtractParamRefs benchmarks param extraction
- TestNew: TestNew verifies engine creation with all functions
- TestRequireFunc: TestRequireFunc tests the require helper function
- TestGetOrFunc: TestGetOrFunc tests the getOr helper function
- TestHasFunc: TestHasFunc tests the has helper function
- TestJSONFunc: TestJSONFunc tests JSON serialization
- TestJSONIndentFunc: TestJSONIndentFunc tests indented JSON serialization
- TestDefaultFunc: TestDefaultFunc tests the default helper function
- TestDefaultFuncInTemplates: TestDefaultFuncInTemplates tests both direct and piped forms of default
- TestCoalesceFunc: TestCoalesceFunc tests the coalesce function
- TestEngine_Register: TestEngine_Register tests template registration
- TestEngine_Execute: TestEngine_Execute tests template execution
- TestEngine_Execute_NotRegistered: TestEngine_Execute_NotRegistered tests executing unregistered template
- TestEngine_Execute_EmptyResult: TestEngine_Execute_EmptyResult tests that empty results are rejected
- TestEngine_ExecuteInline: TestEngine_ExecuteInline tests inline template execution
- TestEngine_Validate: TestEngine_Validate tests template validation
- TestEngine_ValidateWithParams: TestEngine_ValidateWithParams tests template validation with param checking
- TestEngine_MathFunctions: TestEngine_MathFunctions tests math helper functions in templates
- TestEngine_StringFunctions: TestEngine_StringFunctions tests string helper functions in templates
- TestEngine_ContextFunctions: TestEngine_ContextFunctions tests context-based helper functions
- TestEngine_RequireFuncError: TestEngine_RequireFuncError tests require function error case
- TestEngine_ConcurrentAccess: TestEngine_ConcurrentAccess tests thread safety
- TestSampleContextMap: TestSampleContextMap tests sample context generation
- TestJSONFunc_Error: TestJSONFunc_Error tests JSON serialization error handling
- TestJSONIndentFunc_Error: TestJSONIndentFunc_Error tests indented JSON serialization error handling
- TestEngine_ExecuteInline_EmptyResult: TestEngine_ExecuteInline_EmptyResult tests that empty results are rejected
- TestEngine_Execute_TemplateError: TestEngine_Execute_TemplateError tests template execution error handling
- TestEngine_Validate_StructuralError: TestEngine_Validate_StructuralError tests validation with structural template errors
- TestToNumber: TestToNumber tests the numeric type conversion helper
- TestEngine_MathFunctions_Float: TestEngine_MathFunctions_Float tests math functions with float values. Uses values that are exactly representable in IEEE 754 floating point to avoid precision issues (10.5 = 21/2, 2.0 = 2/1, results are dyadic rationals).
- TestEngine_MathFunctions_Extended: TestEngine_MathFunctions_Extended tests extended math functions
- TestEngine_NumericFormatFunctions: TestEngine_NumericFormatFunctions tests numeric formatting functions
- TestHeaderFunc: TestHeaderFunc tests header access with canonical form handling
- TestCookieFunc: TestCookieFunc tests cookie access with default value
- TestArrayHelpers: TestArrayHelpers tests first, last, len, pluck, isEmpty functions
- TestTypeConversions: TestTypeConversions tests float, string, bool functions
- TestEngine_NewFunctionsInTemplates: TestEngine_NewFunctionsInTemplates tests new functions work in templates
- TestIPNetworkFunc: TestIPNetworkFunc tests the ipNetwork template function
- TestIPPrefixFunc: TestIPPrefixFunc tests the ipPrefix template function
- TestNormalizeIPFunc: TestNormalizeIPFunc tests the normalizeIP template function
- TestIPFunctionsInTemplates: TestIPFunctionsInTemplates tests that IP functions work in actual templates
- TestUUIDFunc: TestUUIDFunc tests UUID generation through template engine
- TestUUIDShortFunc: TestUUIDShortFunc tests UUID without hyphens
- TestShortIDFunc: TestShortIDFunc tests short ID generation
- TestNanoidFunc: TestNanoidFunc tests NanoID generation
- TestIDFunctionsInTemplates: TestIDFunctionsInTemplates tests UUID/ID functions in actual templates
- TestPublicIDFunc: TestPublicIDFunc tests the publicID template function
- TestPrivateIDFunc: TestPrivateIDFunc tests the privateID template function
- TestPublicPrivateIDRoundTrip: TestPublicPrivateIDRoundTrip tests encoding and decoding produces original value
- TestPublicIDInTemplates: TestPublicIDInTemplates tests publicID/privateID functions in templates
- TestValidationHelpers: ValidationHelpers
- TestEncodingHashingFuncs: EncodingHashingFuncs
- TestStringHelpers: StringHelpers
- TestDateTimeFuncs: DateTimeFuncs
- TestJSONHelpers: JSONHelpers
- TestConditionalHelpers: ConditionalHelpers
- TestDigFunc: DigFunc
- TestDebugHelpers: DebugHelpers
- TestNumericFormatting: NumericFormatting
- TestParseTimeFunc: ParseTimeFunc
- TestMergeFunc: MergeFunc
- TestValuesFunc: ValuesFunc
- TestFormatTimeEdgeCases: FormatTimeEdgeCases
- TestDigFuncEdgeCases: DigFuncEdgeCases
- TestTypeOfNil: TypeOfNil
- TestUrlDecodeError: UrlDecodeError
- TestBase64DecodeError: Base64DecodeError
- TestMatchesInvalidRegex: MatchesInvalidRegex
- TestSubstrEdgeCases: SubstrEdgeCases
- TestTruncateEdgeCases: TruncateEdgeCases
- TestJoinNonSlice: JoinNonSlice
- TestKeysNonMap: KeysNonMap
- TestToIntConversions: ToIntConversions
- TestAndFunc: AndFunc
- TestOrFunc: OrFunc
- TestBooleanOperatorsInTemplates: BooleanOperatorsInTemplates
- TestIsEmailFunc: IsEmailFunc
- TestIsUUIDFunc: IsUUIDFunc
- TestIsURLFunc: IsURLFunc
- TestIsIPFunc: IsIPFunc
- TestIsIPv4Func: IsIPv4Func
- TestIsIPv6Func: IsIPv6Func
- TestIsNumericFunc: IsNumericFunc
- TestMatchesFunc: MatchesFunc
- TestUrlEncodeFunc: UrlEncodeFunc
- TestUrlDecodeFunc: UrlDecodeFunc
- TestUrlDecodeOrFunc: UrlDecodeOrFunc
- TestBase64EncodeFunc: Base64EncodeFunc
- TestBase64DecodeFunc: Base64DecodeFunc
- TestBase64DecodeOrFunc: Base64DecodeOrFunc
- TestSHA256Func: SHA256Func
- TestMD5Func: MD5Func
- TestHmacSHA256Func: HmacSHA256Func
- TestIPNetworkFuncEdgeCases: IPNetworkFuncEdgeCases
- TestIPPrefixFuncEdgeCases: IPPrefixFuncEdgeCases
- TestShortIDFuncCharacterSet: ShortIDFuncCharacterSet
- TestNanoidFuncCharacterSet: NanoidFuncCharacterSet
- TestNanoidFuncEdgeCases: NanoidFuncEdgeCases
- TestExprFuncs: TestExprFuncs verifies ExprFuncs returns all expected functions
- TestExprFuncs_DivOr: TestExprFuncs_DivOr tests the divOr function from ExprFuncs
- TestExprFuncs_ModOr: TestExprFuncs_ModOr tests the modOr function from ExprFuncs
- TestLikeEscapeFunc: TestLikeEscapeFunc verifies LIKE metacharacters are escaped for a literal match, and that each dialect gets exactly the escapes its LIKE recognizes: [ is a metacharacter only in T-SQL, and escaping it elsewhere would emit an escape before an ordinary character, which SQLite leaves undefined.
- TestLikeEscapeInTemplate: TestLikeEscapeInTemplate verifies likeEscape is callable from a template, as it is used in a computed param.
Package: internal/ratelimit
- TestNew: New
- TestAllow_NoLimits: Allow NoLimits
- TestAllow_NamedPool: Allow NamedPool
- TestAllow_InlineConfig: Allow InlineConfig
- TestAllow_MultiplePools: Allow MultiplePools
- TestAllow_DifferentClients: Allow DifferentClients
- TestAllow_HeaderBasedKey: Allow HeaderBasedKey
- TestAllow_MissingTemplateData: Allow MissingTemplateData
- TestAllow_NonexistentPool: Allow NonexistentPool
- TestMetrics: Metrics
- TestMetrics_InlinePool: TestMetrics_InlinePool tests that inline rate limits also track metrics
- TestPoolNames: PoolNames
- TestGetPool: GetPool
- TestBucketCleanup: BucketCleanup
- TestReset: Reset
Package: internal/types
- TestIsArrayType: IsArrayType
- TestArrayBaseType: ArrayBaseType
- TestConvertValue: ConvertValue
- TestConvertJSONValue: ConvertJSONValue
- TestValidateArrayElements: ValidateArrayElements
- TestValidParamTypes: ValidParamTypes
Package: internal/publicid
- TestNewEncoder: NewEncoder
- TestEncodeDecode: EncodeDecode
- TestDifferentIDsProduceDifferentOutput: DifferentIDsProduceDifferentOutput
- TestSameIDDifferentNamespaceProducesDifferentOutput: SameIDDifferentNamespaceProducesDifferentOutput
- TestPrefixHandling: PrefixHandling
- TestDecodeInvalidPrefix: DecodeInvalidPrefix
- TestDecodeUnknownNamespace: DecodeUnknownNamespace
- TestEncodeUnknownNamespace: EncodeUnknownNamespace
- TestDecodeInvalidCharacters: DecodeInvalidCharacters
- TestDecodeInvalidLength: DecodeInvalidLength
- TestHasNamespace: HasNamespace
- TestXTEARoundTrip: XTEARoundTrip
- TestBase62RoundTrip: Base62RoundTrip
- TestConsistentEncoding: ConsistentEncoding
- TestDifferentSecretsProduceDifferentOutput: DifferentSecretsProduceDifferentOutput
Package: internal/sqlutil
- TestAnalyze_Facts: TestAnalyze_Facts verifies the embedded wasm parser returns correct structural facts end-to-end (Go -> wasm -> JSON) for the cases that drove the redesign.
- TestAnalyze_Params: TestAnalyze_Params verifies bind-parameter extraction end-to-end (Go -> wasm), including the per-dialect
@xtokenization split, literal/comment awareness, byte spans covering the whole @name token, and declared-variable exclusion via the AST. - TestExecutable: TestExecutable verifies the parser splits a batch into per-statement executable text and bind parameters, keeping a batch-declared variable out of every statement's params - the case that replaces the old ;-splitter.
- TestAnalyze_Caching: TestAnalyze_Caching verifies repeated analysis of the same SQL is served from the per-parser cache and that CloseParser clears it.
Package: internal/workflow
- TestBuild_ValidWorkflows: TestBuild_ValidWorkflows verifies Build compiles every workflow it accepts.
- TestBuild_ReportsValidationErrors: TestBuild_ReportsValidationErrors verifies validation failures are reported with the workflow index and name, and no workflows are returned.
- TestBuild_ReportsCompileErrors: TestBuild_ReportsCompileErrors verifies a config that validates but fails to compile is rejected by Build. This is the case -validate used to miss.
- TestBuild_DuplicateWorkflowName: TestBuild_RouteClash verifies two workflows sharing a METHOD and path are rejected, naming both workflows. TestBuild_DuplicateWorkflowName verifies two workflows cannot share a name. The name identifies a workflow in the cache, in metrics and in the OpenAPI spec, so a duplicate makes two workflows share one cache namespace and one operationId.
- TestBuild_DistinctNamesOnOnePath: TestBuild_DistinctNamesOnOnePath verifies distinct names sharing a path with different methods still build - the duplicate-name rule is about the name alone.
- TestBuild_RouteClash: Build RouteClash
- TestBuild_RouteClashOnAmbiguousWildcards: TestBuild_RouteClashOnAmbiguousWildcards verifies patterns that are not textually equal but that http.ServeMux still refuses are rejected. The mux signals these by panicking, so missing one crashes the server at startup.
- TestBuild_NoRouteClashForCompatibleWildcards: TestBuild_NoRouteClashForCompatibleWildcards verifies a wildcard and a more specific literal route coexist, as the router allows.
- TestBuild_ReportsRouteClashAlongsideWorkflowErrors: TestBuild_ReportsRouteClashAlongsideWorkflowErrors verifies one pass reports both a broken workflow and a route clash between the workflows that did compile.
- TestBuild_DiagnosticIndexPointsAtConfig: TestBuild_DiagnosticIndexPointsAtConfig verifies a diagnostic index identifies the workflow's position in the config, not in the compiled list.
- TestBuild_NoRouteClashForDifferentMethods: TestBuild_NoRouteClashForDifferentMethods verifies the clash check keys on method as well as path.
- TestBuild_NoRouteClashForNonHTTPTriggers: TestBuild_NoRouteClashForNonHTTPTriggers verifies cron and lifecycle triggers are not treated as routes.
- TestBuild_PrefixesWarnings: TestBuild_PrefixesWarnings verifies warnings survive Build and name their workflow without failing the build.
- TestBuild_NilValidationContext: TestBuild_NilValidationContext verifies a nil context skips the external-resource checks rather than panicking, matching Validate. Callers that want database and rate limit pool names checked must pass one; the server always does.
- TestBuild_Empty: TestBuild_Empty verifies an empty workflow list builds cleanly.
- TestCompile_BasicWorkflow: Compile BasicWorkflow
- TestCompile_ConditionAliases: Compile ConditionAliases
- TestCompile_HTTPCallStep: Compile HTTPCallStep
- TestCompile_BlockWithIteration: Compile BlockWithIteration
- TestCompile_CacheKeyTemplate: Compile CacheKeyTemplate
- TestCompile_DisabledCacheKeyStillCompiled: TestCompile_DisabledCacheKeyStillCompiled verifies a disabled cache still has its key compiled, so a broken key template is a startup error rather than a surprise waiting for whoever clears disabled later.
- TestCompile_InvalidTemplateSyntax: Compile InvalidTemplateSyntax
- TestAliasExpansion: TestAliasExpansion tests alias expansion via AST patching.
- TestAliasChaining: TestAliasChaining tests that aliases can reference other aliases.
- TestCircularDependencyDetection: TestCircularDependencyDetection verifies that circular alias dependencies are detected.
- TestAliasInStringLiteral: TestAliasInStringLiteral verifies aliases are NOT expanded inside string literals.
- TestAliasNotMatchPropertyPath: TestAliasNotMatchPropertyPath verifies aliases don't match property paths.
- TestEmptyAliases: TestEmptyAliases verifies compilation works with no aliases.
- TestEvalCondition: EvalCondition
- TestEvalExpression: EvalExpression
- TestTemplateFuncs: TestTemplateFuncs tests all template functions available in workflow templates.
- TestTemplateFuncs_InWorkflowContext: TestTemplateFuncs_InWorkflowContext tests template functions with realistic workflow data.
- TestExprFunc_isValidPublicID: TestExprFunc_isValidPublicID tests the isValidPublicID expr function.
- TestExprFuncs_InConditions: TestExprFuncs_InConditions tests that common functions from tmpl.ExprFuncs are available and work correctly in condition expressions.
- TestValidateDivisions: TestValidateDivisions tests static validation of division operations
- TestExtractStepRefs: TestExtractStepRefs tests step reference extraction from expressions
- TestResolveQueryRouting: TestResolveQueryRouting verifies returns: modes and the auto classification map to the correct (returnsRows, rowsAreAffected) routing decision, which is decided by the batch's final statement because that is the only result a driver exposes.
- TestCompileStepLikeEscapeDialect: TestCompileStepLikeEscapeDialect verifies a step's templates compile against the dialect of its database: SQL Server escapes the character-class opener [, and the engines whose LIKE has no character classes leave it alone rather than emitting an escape before an ordinary character.
- TestStepConfig_StepType: StepConfig StepType
- TestStepConfig_IsBlock: StepConfig IsBlock
- TestStepConfig_IsQuery: StepConfig IsQuery
- TestStepConfig_IsHTTPCall: StepConfig IsHTTPCall
- TestStepConfig_IsResponse: StepConfig IsResponse
- TestRateLimitRefConfig: RateLimitRefConfig
- TestTriggerConfig_SkipOnOverlap: TestTriggerConfig_SkipOnOverlap verifies on_overlap resolves to skipping unless the trigger explicitly allows concurrent runs.
- TestNewContext: NewContext
- TestContext_SetStepResult: Context SetStepResult
- TestContext_BuildExprEnv_HTTPTrigger: Context BuildExprEnv HTTPTrigger
- TestContext_BuildExprEnv_CronTrigger: Context BuildExprEnv CronTrigger
- TestContext_BuildExprEnv_LifecycleTrigger: TestContext_BuildExprEnv_LifecycleTrigger verifies lifecycle runs expose no request or schedule fields
- TestContext_BuildExprEnv_WithVariables: Context BuildExprEnv WithVariables
- TestContext_BuildExprEnv_NilVariables: Context BuildExprEnv NilVariables
- TestContext_BuildExprEnv_VarsInExpr: Context BuildExprEnv VarsInExpr
- TestContext_BuildTemplateData: Context BuildTemplateData
- TestStepResultToMap: StepResultToMap
- TestHeaderToMap: HeaderToMap
- TestBlockContext: BlockContext
- TestBlockContext_SetStepResult: BlockContext SetStepResult
- TestBlockContext_BuildExprEnv: BlockContext BuildExprEnv
- TestBlockContext_BuildTemplateData: BlockContext BuildTemplateData
- TestContext_BuildExprEnv_ContainsExprFuncs: Context BuildExprEnv ContainsExprFuncs
- TestContext_BuildExprEnv_CookieAccess: Context BuildExprEnv CookieAccess
- TestContext_BuildExprEnv_CookiesInExpr: Context BuildExprEnv CookiesInExpr
- TestExtractSQLParams: ExtractSQLParams
- TestNormalizeJSONResponse: NormalizeJSONResponse
- TestExecuteQueryStep_TemplateError: ExecuteQueryStep TemplateError
- TestExecuteQueryStep_DBError: ExecuteQueryStep DBError
- TestExecuteQueryStep_Success: ExecuteQueryStep Success
- TestExecuteHTTPCallStep_URLTemplateError: ExecuteHTTPCallStep URLTemplateError
- TestExecuteHTTPCallStep_BodyTemplateError: ExecuteHTTPCallStep BodyTemplateError
- TestExecuteHTTPCallStep_HeaderTemplateError: ExecuteHTTPCallStep HeaderTemplateError
- TestExecuteHTTPCallStep_ConnectionError: ExecuteHTTPCallStep ConnectionError
- TestExecuteHTTPCallStep_Non2xxResponse: ExecuteHTTPCallStep Non2xxResponse
- TestExecuteHTTPCallStep_JSONParse: ExecuteHTTPCallStep JSONParse
- TestExecuteHTTPCallStep_TextParse: ExecuteHTTPCallStep TextParse
- TestExecuteHTTPCallStep_FormParse: ExecuteHTTPCallStep FormParse
- TestExecuteHTTPCallStep_InvalidJSON: ExecuteHTTPCallStep InvalidJSON
- TestExecuteHTTPCallStep_DefaultContentType: ExecuteHTTPCallStep DefaultContentType
- TestExecuteHTTPCallStep_CustomHeaders: ExecuteHTTPCallStep CustomHeaders
- TestExecuteHTTPCallStep_RetryOn500: ExecuteHTTPCallStep RetryOn500
- TestExecuteHTTPCallStep_RetryExhausted: ExecuteHTTPCallStep RetryExhausted
- TestExecuteHTTPCallStep_NoRetryOn4xx: ExecuteHTTPCallStep NoRetryOn4xx
- TestExecuteResponseStep_Success: ExecuteResponseStep Success
- TestExecuteResponseStep_TemplateError: ExecuteResponseStep TemplateError
- TestExecuteResponseStep_WriteError: ExecuteResponseStep WriteError
- TestExecuteResponseStep_DefaultStatusCode: ExecuteResponseStep DefaultStatusCode
- TestExecuteHTTPCallStep_ContextCancelledDuringRetry: ExecuteHTTPCallStep ContextCancelledDuringRetry
- TestExecuteHTTPCallStep_RetryWithBodyAndHeaders: ExecuteHTTPCallStep RetryWithBodyAndHeaders
- TestExecuteHTTPCallStep_RetryConnectionError: ExecuteHTTPCallStep RetryConnectionError
- TestExecuteHTTPCallStep_StepTimeout: ExecuteHTTPCallStep StepTimeout
- TestExecuteResponseStep_HeaderTemplateError: ExecuteResponseStep HeaderTemplateError
- TestExecuteResponseStep_CustomHeaders: ExecuteResponseStep CustomHeaders
- TestExecuteQueryStep_PassesQueryOptions: ExecuteQueryStep PassesQueryOptions
- TestNewExecutor: NewExecutor
- TestExecutor_Execute_SimpleQuery: Executor Execute SimpleQuery
- TestExecutor_Execute_DisabledStep: Executor Execute DisabledStep
- TestExecutor_Execute_ConditionalStep: Executor Execute ConditionalStep
- TestExecutor_Execute_StepFailure_Abort: Executor Execute StepFailure Abort
- TestExecutor_Execute_StepFailure_Continue: Executor Execute StepFailure Continue
- TestExecutor_Execute_ResponseStep: Executor Execute ResponseStep
- TestExecutor_Execute_ResponseStepSkippedWithoutClient: TestExecutor_Execute_ResponseStepSkippedWithoutClient verifies response steps are skipped, not failed, for cron and lifecycle runs
- TestExecutor_Execute_HTTPCallStep: Executor Execute HTTPCallStep
- TestExecutor_Execute_ContextCancellation: Executor Execute ContextCancellation
- TestExecutor_Execute_WorkflowTimeout: Executor Execute WorkflowTimeout
- TestExecutor_Execute_HTTPTriggerWithoutResponse: Executor Execute HTTPTriggerWithoutResponse
- TestExecutor_Execute_UnknownStepType: Executor Execute UnknownStepType
- TestExecutor_Execute_BlockStep: Executor Execute BlockStep
- TestExecutor_Execute_BlockStep_IterationError_Abort: Executor Execute BlockStep IterationError Abort
- TestExecutor_Execute_BlockStep_WithoutIteration: Executor Execute BlockStep WithoutIteration
- TestExecutor_Execute_StepNames_Auto: Executor Execute StepNames Auto
- TestExecutor_Execute_LoggingCalls: Executor Execute LoggingCalls
- TestExecutor_StepCache_Hit: Executor StepCache Hit
- TestExecutor_StepCache_CollapsesConcurrentMisses: TestExecutor_StepCache_CollapsesConcurrentMisses verifies workflows running at the same time over one cold step key share a single execution of that step, instead of each issuing the same query. The sharers are served its data, like a cache hit.
- TestExecutor_StepCache_Miss: Executor StepCache Miss
- TestExecutor_StepCache_NilCache: Executor StepCache NilCache
- TestExecutor_ConditionalResponse_NegatedAlias: TestExecutor_ConditionalResponse_NegatedAlias tests that negated condition aliases work correctly
- TestExecutor_ConditionalResponse_FromConfig: TestExecutor_ConditionalResponse_FromConfig tests conditional responses compiled from config (like E2E).
- TestEvaluateStepParams_Integer: EvaluateStepParams Integer
- TestEvaluateStepParams_String: EvaluateStepParams String
- TestEvaluateStepParams_TemplateError: EvaluateStepParams TemplateError
- TestEvaluateStepParams_MultipleParams: EvaluateStepParams MultipleParams
- TestEvaluateStepParams_UsesExistingParamsMap: EvaluateStepParams UsesExistingParamsMap
- TestEvaluateStepParams_TemplateWithData: EvaluateStepParams TemplateWithData
- TestEvaluateStepParams_EmptyParams: EvaluateStepParams EmptyParams
- TestCompileAndEvaluate_ConditionAliases: TestCompileAndEvaluate_ConditionAliases tests that condition aliases and negated aliases are properly compiled and evaluated.
- TestParseInt64: ParseInt64
- TestNewHTTPHandler: NewHTTPHandler
- TestHTTPHandler_ServeHTTP_MethodNotAllowed: HTTPHandler ServeHTTP MethodNotAllowed
- TestHTTPHandler_ServeHTTP_Success: HTTPHandler ServeHTTP Success
- TestHTTPHandler_ServeHTTP_VersionWithBuildTime: HTTPHandler ServeHTTP VersionWithBuildTime
- TestHTTPHandler_ServeHTTP_RequestID_FromHeader: HTTPHandler ServeHTTP RequestID FromHeader
- TestHTTPHandler_ServeHTTP_CorrelationID: HTTPHandler ServeHTTP CorrelationID
- TestHTTPHandler_ParseParameters_QueryString: HTTPHandler ParseParameters QueryString
- TestHTTPHandler_ParseParameters_MissingRequired: HTTPHandler ParseParameters MissingRequired
- TestHTTPHandler_ParseParameters_JSONBody: HTTPHandler ParseParameters JSONBody
- TestHTTPHandler_ParseParameters_InvalidJSON: HTTPHandler ParseParameters InvalidJSON
- TestHTTPHandler_ParseParameters_TypeConversion: HTTPHandler ParseParameters TypeConversion
- TestHTTPHandler_WorkflowError_DefaultResponse: HTTPHandler WorkflowError DefaultResponse
- TestHTTPHandler_NoResponse_EmptySuccess: HTTPHandler NoResponse EmptySuccess
- TestGetOrGenerateRequestID: GetOrGenerateRequestID
- TestGenerateRequestID: GenerateRequestID
- TestSanitizeHeaderValue: SanitizeHeaderValue
- TestResolveClientIP: ResolveClientIP
- TestDBManagerAdapter: DBManagerAdapter
- TestHTTPHandler_ParseParameters_NestedObject: HTTPHandler ParseParameters NestedObject
- TestHTTPHandler_ParseParameters_JSONType: HTTPHandler ParseParameters JSONType
- TestHTTPHandler_ParseParameters_ArrayType: HTTPHandler ParseParameters ArrayType
- TestHTTPHandler_TriggerCache_Hit: HTTPHandler TriggerCache Hit
- TestHTTPHandler_TriggerCache_Miss: HTTPHandler TriggerCache Miss
- TestHTTPHandler_TriggerCache_NilCache: HTTPHandler TriggerCache NilCache
- TestHTTPHandler_TriggerCache_Disabled: TestHTTPHandler_TriggerCache_Disabled verifies cache.disabled turns the trigger cache off without the key being removed: a stored entry that would otherwise hit is ignored, the fresh response is not written back, and no X-Cache header is set.
- TestHTTPHandler_TriggerCache_TimeoutBoundsTheWait: TestHTTPHandler_TriggerCache_TimeoutBoundsTheWait verifies _timeout still bounds a request that misses a cached trigger. Such a request joins the shared run rather than starting its own, and the shared run deliberately keeps the workflow's deadline - so the caller's own deadline has to bound how long it waits, or _timeout would do nothing at all on a cached endpoint.
- TestHTTPHandler_TriggerCache_ReportsRemainingTTL: TestHTTPHandler_TriggerCache_ReportsRemainingTTL verifies a cache hit says how long the stored response has left, and that a miss - which just refreshed it - carries no such claim.
- TestHTTPHandler_TriggerCache_CollapsesConcurrentMisses: TestHTTPHandler_TriggerCache_CollapsesConcurrentMisses verifies requests that miss the same cache key at the same time share one execution instead of each running the workflow, and that every one of them gets that response.
- TestHTTPHandler_TriggerCache_KeepsResponseHeaders: TestHTTPHandler_TriggerCache_KeepsResponseHeaders verifies a header set by a response step survives caching, so a hit reproduces the reply a miss produced.
- TestHTTPHandler_TriggerCache_DoesNotCacheHandlerHeaders: TestHTTPHandler_TriggerCache_DoesNotCacheHandlerHeaders verifies the headers the handler sets per request - the request id, the server version, the cache status - are not stored and replayed to later callers as if they were the workflow's.
- TestFlattenHeaders: FlattenHeaders
- TestFlattenQuery: FlattenQuery
- TestEvaluateCacheKey_ExpandedContext: EvaluateCacheKey ExpandedContext
- TestParseCookies: ParseCookies
- TestTimeoutPolicy_Effective: TestTimeoutPolicy_Effective verifies the request deadline resolution order: the caller's _timeout, then the workflow's timeout_sec, then the server default.
- TestHTTPHandler_TimeoutOverride_Rejected: TestHTTPHandler_TimeoutOverride_Rejected verifies _timeout values that are not a positive number of seconds, or that exceed the server ceiling, fail with 400.
- TestHTTPHandler_TimeoutOverride_Applied: TestHTTPHandler_TimeoutOverride_Applied verifies _timeout bounds a request that would otherwise run under the longer workflow timeout, and that expiry is a 504.
- TestHTTPHandler_DefaultTimeoutApplied: TestHTTPHandler_DefaultTimeoutApplied verifies a workflow declaring no timeout still runs under the server default rather than unbounded.
- TestHTTPHandler_NoCache_Bypass: TestHTTPHandler_NoCache_Bypass verifies _nocache skips the stored response and replaces it with the fresh one.
- TestHTTPHandler_NoCache_Rejected: TestHTTPHandler_NoCache_Rejected verifies a _nocache value that is not a boolean fails with 400 rather than being read as false.
- TestValidate_BasicWorkflow: Validate BasicWorkflow
- TestValidate_MissingName: Validate MissingName
- TestValidate_MissingTriggers: Validate MissingTriggers
- TestValidate_MissingSteps: Validate MissingSteps
- TestValidate_HTTPTrigger: Validate HTTPTrigger
- TestValidate_CronTrigger: Validate CronTrigger
- TestValidateCronExpr: TestValidateCronExpr verifies the accepted schedule dialect: five fields plus descriptors
- TestValidateCronExpr_MatchesScheduler: TestValidateCronExpr_MatchesScheduler verifies validation never accepts a schedule the scheduler cannot run
- TestValidate_LifecycleTrigger: TestValidate_LifecycleTrigger verifies startup and shutdown triggers reject request and schedule fields
- TestValidate_TriggerCache: TestValidate_TriggerCache verifies a cache block is checked the same way whether or not it is disabled: the key is what turns caching on so it is always required, and a bad ttl_sec or evict_cron is refused rather than waiting for the day the cache is switched back on.
- TestValidate_CacheTuningAgreesAcrossTriggers: TestValidate_CacheTuningAgreesAcrossTriggers verifies two triggers of one workflow may cache under different keys but not under different max_size_mb or evict_cron, because the entries share one space named after the workflow. A disabled cache is not part of the comparison.
- TestValidate_EvictCronSchedule: TestValidate_EvictCronSchedule verifies cache evict_cron accepts the same dialect as triggers
- TestValidate_QueryStep: Validate QueryStep
- TestValidate_ReturnsField: TestValidate_ReturnsField verifies returns: is accepted only on query steps and warns when 'affected' is used on a statement that only reads.
- TestValidate_ReturnsMismatchWarnings: TestValidate_ReturnsMismatchWarnings verifies both directions of the returns: override are checked: 'affected' on SQL that only reads, and 'rows' on a write that returns none. A stored-procedure call may do either, so it warns for neither.
- TestValidate_SQLServerBatchAffectedCountWarning: TestValidate_SQLServerBatchAffectedCountWarning verifies the one place the affected count differs by dialect is reported at startup: on SQL Server a batch that ends in a write reports the whole batch's row count, not the final statement's. It must warn only when the difference is observable, and never for another dialect.
- TestValidate_LikeEscapeNeedsEscapeClause: TestValidate_LikeEscapeNeedsEscapeClause verifies a computed param built with likeEscape is rejected unless the SQL declares ESCAPE '!', since without the clause the escape character is matched literally and the search silently returns the wrong rows.
- TestValidate_ReadOnlyWriteDetection: TestValidate_ReadOnlyWriteDetection verifies the read-only check reads writes off the parsed AST in both directions: a write is caught even when its top-level shape reads (a CTE-driven insert, SELECT ... INTO), hides in a multi-statement batch, or sits inside T-SQL control flow; and a write keyword inside a literal, comment, or identifier is not mistaken for a write.
- TestValidate_UnparseableEscapeHatch: TestValidate_UnparseableEscapeHatch verifies the escape hatch for SQL the parser cannot read (a dialect gap, e.g. a T-SQL WHILE ... BEGIN ... END body): the author must declare returns: and writes:, and only then does the read-only guard use the declared writes:. Undeclared SQL is rejected with an actionable message; declaring writes: on SQL that parses is rejected because its behaviour is derived.
- TestValidate_EscapeHatchMySQLSingleStatement: TestValidate_EscapeHatchMySQLSingleStatement verifies a declared escape-hatch step on a MySQL database warns that it must be a single statement, because MySQL's prepared protocol runs one statement per call and an unparseable step runs verbatim. The step is still valid (a warning, not an error) - the author may know it is one statement. SQL Server, which runs a multi-statement batch natively, does not warn.
- TestValidate_HTTPCallStep: Validate HTTPCallStep
- TestValidate_ResponseStep: Validate ResponseStep
- TestValidate_BlockStep: Validate BlockStep
- TestValidate_ConditionAliases: Validate ConditionAliases
- TestExtractTriggerComparisons: TestExtractTriggerComparisons verifies the AST extractor finds trigger.type/cron comparisons in either operand order and ignores everything else.
- TestValidate_TriggerConditionLiterals: TestValidate_TriggerConditionLiterals verifies conditions comparing trigger.type/cron to a literal are checked against the workflow's declared triggers.
- TestValidate_TriggerConditionInAlias: TestValidate_TriggerConditionInAlias verifies a typo'd trigger type inside a conditions alias is caught at the alias definition.
- TestValidate_TriggerConditionInBlock: TestValidate_TriggerConditionInBlock verifies the check reaches conditions on steps nested inside a block.
- TestValidate_Warnings: Validate Warnings
- TestValidate_DuplicateStepNames: Validate DuplicateStepNames
- TestValidate_MultiStepRequiresNames: Validate MultiStepRequiresNames
- TestValidate_PathParameters: Validate PathParameters
- TestExtractPathParams: ExtractPathParams
- TestValidate_Lints: TestValidate_Lints verifies SQL safety lints are on by default, that a database's lints_off denylist silences a named lint while leaving the others, and that a clean query trips none.
- TestValidate_ParamForwardCheck: TestValidate_ParamForwardCheck verifies the forward parameter cross-check: an @param with no source is an error, and every static source (declared parameter, path param, computed param, variable) plus the columns of an iterated query satisfy it.
- TestValidate_ParamReverseCheck: TestValidate_ParamReverseCheck verifies the reverse check: a declared trigger parameter used by no step warns, while one used in SQL or a template, or a path parameter, does not.
- TestValidate_WriteCrossChecks: TestValidate_WriteCrossChecks verifies the write cross-checks, both warnings (never errors - each pattern has a legitimate use): a safe-method HTTP trigger over a writing workflow warns, a caching trigger over a writing workflow warns, and neither fires for a read-only workflow or a non-HTTP trigger. A GET+cache write draws both.
- TestValidate_SQLTemplateInjection: Validate SQLTemplateInjection
- TestContainsTemplateInterpolation: ContainsTemplateInterpolation
- TestValidate_RateLimitPool: TestValidate_RateLimitPool verifies rate limit validation accepts valid pool references
- TestValidate_RateLimitInline: TestValidate_RateLimitInline verifies rate limit validation accepts valid inline config
- TestValidate_RateLimitErrors: TestValidate_RateLimitErrors verifies rate limit validation catches invalid configurations
- TestValidate_HTTPCallRetry: TestValidate_HTTPCallRetry verifies httpcall retry configuration validation
- TestValidate_HTTPCallRetryValid: TestValidate_HTTPCallRetryValid verifies valid httpcall retry configuration passes
- TestValidate_DivisionSafety: TestValidate_DivisionSafety tests that unsafe divisions are caught during validation
- TestValidate_StepReferences: TestValidate_StepReferences tests that step references are validated
- TestValidate_OnOverlap: TestValidate_OnOverlap verifies on_overlap is checked at startup and rejected on triggers where overlapping runs are not a concept.
- TestValidate_UnboundedWorkflowSeverity: TestValidate_UnboundedWorkflowSeverity verifies the timeout rule follows the most demanding trigger, not the order triggers are listed in.
- TestTriggerFieldsCoverEveryField: TestTriggerFieldsCoverEveryField verifies every yaml field of TriggerConfig is claimed by at least one trigger type. Adding a field without deciding where it belongs fails here rather than being rejected on every trigger at runtime.
- TestTriggerFieldsAreRealFields: TestTriggerFieldsAreRealFields verifies the table names only fields that exist, so a renamed field cannot leave a rule guarding nothing.
- TestPopulatedTriggerFields: TestPopulatedTriggerFields verifies field detection reads the yaml names off the struct and reports only the fields carrying a value.
- TestValidateTriggerFields: TestValidateTriggerFields verifies a field that cannot apply to a trigger type is rejected, with the same rule for every type.
- TestValidateTriggerFieldsHint: TestValidateTriggerFieldsHint verifies a misplaced field is explained, not just rejected.
Package: e2e
- TestE2E_ServerStartupAndShutdown: TestE2E_ServerStartupAndShutdown tests the server starts and stops cleanly
- TestE2E_HealthEndpoint: TestE2E_HealthEndpoint tests /health returns database status
- TestE2E_MetricsEndpoint: TestE2E_MetricsEndpoint tests /_/metrics.json returns runtime stats
- TestE2E_PrometheusMetrics: TestE2E_PrometheusMetrics tests that per-request and gauge metrics are recorded
- TestE2E_OpenAPIEndpoint: TestE2E_OpenAPIEndpoint tests /_/openapi.json returns valid spec
- TestE2E_RootEndpoint: TestE2E_RootEndpoint tests / returns endpoint listing
- TestE2E_WorkflowEndpoint: TestE2E_WorkflowEndpoint tests workflow execution returns data
- TestE2E_ErrorHandling_MissingRequiredParameter: TestE2E_ErrorHandling_MissingRequiredParameter tests 400 response for missing required parameters
- TestE2E_ErrorHandling_InvalidParameterType: TestE2E_ErrorHandling_InvalidParameterType tests 400 response for wrong parameter types
- TestE2E_ErrorHandling_DatabaseError: TestE2E_ErrorHandling_DatabaseError tests 500 response for database errors
- TestE2E_ErrorHandling_NotFound: TestE2E_ErrorHandling_NotFound tests 404 response for non-existent endpoints
- TestE2E_ErrorHandling_MethodNotAllowed: TestE2E_ErrorHandling_MethodNotAllowed tests 405 response for wrong HTTP methods
- TestE2E_LogLevelEndpoint: TestE2E_LogLevelEndpoint tests runtime log level changes
- TestE2E_GzipCompression: TestE2E_GzipCompression tests response compression
- TestE2E_RequestID: TestE2E_RequestID tests request ID propagation
- TestE2E_NotFound: TestE2E_NotFound tests 404 for unknown paths
- TestE2E_GracefulShutdown: TestE2E_GracefulShutdown tests server handles SIGTERM gracefully
- TestE2E_ErrorHandling_RateLimited: TestE2E_ErrorHandling_RateLimited tests 429 response when rate limit is exceeded
- TestE2E_ConfigValidation: TestE2E_ConfigValidation tests -validate flag
- TestE2E_InvalidConfig: TestE2E_InvalidConfig tests server rejects invalid config
# Run all tests
make test
# Run by test type
make test-unit # Unit tests (internal packages)
make test-integration # Integration tests (httptest-based)
make test-e2e # End-to-end tests (starts actual binary)
# Run by package
make test-db
make test-handler
make test-tmpl
make test-ratelimit
# etc.
# Run with coverage
make test-cover
make test-cover-html
# Run benchmarks
make test-bench| Type | Location | Description |
|---|---|---|
| Unit tests | internal/*/ |
Test individual functions and methods |
| Integration tests | internal/server/ |
Test component interactions via httptest |
| End-to-end tests | e2e/ |
Start binary, make real HTTP requests |
| Benchmarks | internal/*/benchmark_test.go |
Performance tests |
All unit and integration tests use SQLite in-memory databases to avoid external dependencies.