testutil

package
v1.20220411.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 23 Imported by: 1

Documentation

Index

Constants

View Source
const (
	// DefaultFixtureDirectory is the default directory where test fixture
	// files will be retrieved. Since `go test` sets the present working directory
	// to the current directory under test, this is a relative path.
	DefaultFixtureDirectory = "./testdata"
	// DefaultGoldenFilePrefix is the prefix that will be prepended to suffixes
	// for golden filenames.
	DefaultGoldenFilePrefix = "golden."
	// DefaultUpdateGoldenFlag is the flag that this package will use to check
	// if golden files should be updated.
	DefaultUpdateGoldenFlag = "update-golden"
)
View Source
const (
	SuiteFailureTests  = 1
	SuiteFailureBefore = 2
	SuiteFailureAfter  = 3
)

FailureCodes

Variables

This section is empty.

Functions

func AssertGoldenFile added in v1.20210917.5

func AssertGoldenFile(it *assert.Assertions, expected []byte, filenameSuffix string, opts ...FixtureOption)

AssertGoldenFile checks that a "golden file" matches the expected contents. The golden file will use the test fixtures directory and will use the filename suffix **after** a prefix of `golden.`, e.g. `./testdata/golden.config.yml`.

Managing golden files can be tedious, so test suites can optionally specify a boolean flag (e.g. `go test --update-golden`) that can be propagated to this function; in which case the golden file will just be overwritten instead of compared against `expected`.

func BeginAll

func BeginAll() ([]*sql.Tx, error)

BeginAll begins a transaction in each of the underlying connections. If an error is raised by *any* of the connections, t

func CreateTestDatabase

func CreateTestDatabase(ctx context.Context, opts ...db.Option) (*db.Connection, error)

CreateTestDatabase creates a randomized test database.

func DefaultDB

func DefaultDB() *db.Connection

DefaultDB returns a default database connection for tests.

func DefaultDBs

func DefaultDBs() []*db.Connection

DefaultDBs returns a default set database connections for tests.

func DropTestDatabase

func DropTestDatabase(ctx context.Context, conn *db.Connection, opts ...db.Option) (err error)

DropTestDatabase drops a database.

func GetTestFixture added in v1.20210917.5

func GetTestFixture(it *assert.Assertions, filename string, opts ...FixtureOption) []byte

GetTestFixture opens a file in the test fixtures directory. This relies on the present working directory being set to the current directory under test and will default to `./testdata` when reading files.

func MarkUpdateGoldenFlag added in v1.20210917.5

func MarkUpdateGoldenFlag(opts ...FixtureOption)

MarkUpdateGoldenFlag is intended to be used in a `TestMain()` to declare a flag **before** `go test` parses flags (if not, unknown flags will fail a test).

This is expected to be used in two modes: > MarkUpdateGoldenFlag() which will mark `--update-golden` (via `DefaultUpdateGoldenFlag`) as a valid flag for tests and with a custom flag override: > MarkUpdateGoldenFlag(OptUpdateGoldenFlag(customFlag))

func NowRounded added in v1.20210826.18

func NowRounded(it assertions, locationName string, precision time.Duration) time.Time

NowRounded returns the current time, but rounded to a given precision and then placed into a timezone given by a location name from the IANA Time Zone database (or "Local").

This is useful in situations where timestamps are written to and then read back from a foreign system, like a database. For example, a `TIMESTAMP WITH TIME ZONE` column in `postgres` will truncate to microsecond precision and will return a "bare" timezone even if the timezone written was UTC.

func ResolveDBConfig added in v1.20210826.18

func ResolveDBConfig(ctx context.Context, c *db.Config) error

ResolveDBConfig is intended to be used to help debug issues resolving a `db.Config` from the environment.

In the case of failure, this wraps the `Resolve()` error with a helpful message and a list of all relevant environment variables.

func RollbackAll

func RollbackAll(txs ...*sql.Tx) error

RollbackAll calls `Rollback` on a set of transactions.

func ValidatePool added in v1.20210826.18

func ValidatePool(ctx context.Context, pool *db.Connection, hints string) error

ValidatePool validates that - the connection string is valid - the selected `sql` driver can be used - a simple ping can be sent over the connection (is the DB reachable?)

In the case of failure, this tries to diagnose the connection error and produce helpful tips on how to resolve.

Types

type AlwaysFailDB added in v1.20210826.18

type AlwaysFailDB struct {
	Errors ErrorProducer
}

AlwaysFailDB implements the `db.DB` interface, but each method always fails.

func (*AlwaysFailDB) ExecContext added in v1.20210826.18

func (afd *AlwaysFailDB) ExecContext(context.Context, string, ...interface{}) (sql.Result, error)

ExecContext implements the `db.DB` interface and returns and error.

func (*AlwaysFailDB) QueryContext added in v1.20210826.18

func (afd *AlwaysFailDB) QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)

QueryContext implements the `db.DB` interface and returns and error.

func (*AlwaysFailDB) QueryRowContext added in v1.20210826.18

func (afd *AlwaysFailDB) QueryRowContext(context.Context, string, ...interface{}) *sql.Row

QueryRowContext implements the `db.DB` interface; the error value is embedded in the `sql.Row` value returned.

type ErrorProducer added in v1.20210826.18

type ErrorProducer interface {
	NextError() error
}

ErrorProducer is an interface that defines an error factory.

type FixtureConfig added in v1.20210917.5

type FixtureConfig struct {
	Directory        string
	GoldenFilePrefix string
	UpdateGoldenFlag string
}

FixtureConfig represents defaults used for working with test fixtures.

func NewFixtureConfig added in v1.20210917.5

func NewFixtureConfig(opts ...FixtureOption) FixtureConfig

NewFixtureConfig returns a new `FixtureConfig` and applies options.

type FixtureOption added in v1.20210917.5

type FixtureOption func(*FixtureConfig)

FixtureOption is a mutator for a `FixtureConfig`.

func OptTestFixtureDirectory added in v1.20210917.5

func OptTestFixtureDirectory(name string) FixtureOption

OptTestFixtureDirectory sets the directory used to look up test fixture files. Both relative and absolute paths are supported.

func OptUpdateGoldenFlag added in v1.20210917.5

func OptUpdateGoldenFlag(name string) FixtureOption

OptUpdateGoldenFlag sets the default flag used to determine if golden files should be updated (e.g. to use `--update-golden`, pass `"update-golden"` here).

type Option

type Option func(*Suite)

Option is a mutator for a test suite.

func OptAfter

func OptAfter(steps ...SuiteAction) Option

OptAfter appends after run actions.

func OptBefore

func OptBefore(steps ...SuiteAction) Option

OptBefore appends before run actions.

func OptLog

func OptLog(log logger.Log) Option

OptLog sets the suite logger.

func OptWithDefaultDB

func OptWithDefaultDB() Option

OptWithDefaultDB runs a test suite with a dedicated database connection.

func OptWithDefaultDBs

func OptWithDefaultDBs(count int) Option

OptWithDefaultDBs runs a test suite with a count of database connections. Note: this type of connection pool is used in rare circumstances for performance reasons; you probably want to use `OptWithDefaultDB` for your tests.

func OptWithStatementLabelRequired added in v1.20210603.3

func OptWithStatementLabelRequired() Option

OptWithStatementLabelRequired adds a defaultdb interceptor that enforces that statement labels must be present on all statements.

type PseudoQueryDB added in v1.20210826.18

type PseudoQueryDB struct {
	DB    *sql.DB
	Query string
	Args  []interface{}
}

PseudoQueryDB implements the `db.DB` interface, it intercepts calls to `QueryContext` and replaces the `query` / `args` arguments with custom values.

func (*PseudoQueryDB) ExecContext added in v1.20210826.18

func (pqd *PseudoQueryDB) ExecContext(_ context.Context, _ string, _ ...interface{}) (sql.Result, error)

ExecContext implements the `db.DB` interface; this is not supported in `PseudoQueryDB`. It will **always** return a "not implemented" error.

func (*PseudoQueryDB) QueryContext added in v1.20210826.18

func (pqd *PseudoQueryDB) QueryContext(ctx context.Context, _ string, _ ...interface{}) (*sql.Rows, error)

QueryContext implements the `db.DB` interface. It intercepts the **actual** query and arguments and replaces them with the query and arguments stored on the current `PseudoQueryDB`.

func (*PseudoQueryDB) QueryRowContext added in v1.20210826.18

func (pqd *PseudoQueryDB) QueryRowContext(_ context.Context, _ string, _ ...interface{}) *sql.Row

QueryRowContext implements the `db.DB` interface; this is not supported in `PseudoQueryDB`. It will **always** return a `sql.Row` with a "not implemented" error set on the row.

type SingleError added in v1.20210826.18

type SingleError struct {
	Error error
}

SingleError satisfies ErrorProducer for a single error.

func (*SingleError) NextError added in v1.20210826.18

func (se *SingleError) NextError() error

NextError produces the "next" error.

type SliceErrors added in v1.20210826.18

type SliceErrors struct {
	Errors []error
	Index  int
}

SliceErrors satisfies ErrorProducer for a slice of errors.

func (*SliceErrors) NextError added in v1.20210826.18

func (se *SliceErrors) NextError() error

NextError produces the "next" error. (This is not concurrency safe.)

type Suite

type Suite struct {
	M      *testing.M
	Log    logger.Log
	Before []SuiteAction
	After  []SuiteAction
}

Suite is a set of before and after actions for a given package tests.

func New

func New(m *testing.M, opts ...Option) *Suite

New returns a new test suite.

func (Suite) Run

func (s Suite) Run()

Run runs tests and calls os.Exit(...) with the exit code.

func (Suite) RunCode added in v1.20211016.2

func (s Suite) RunCode() (code int)

RunCode runs the suite and returns an exit code.

It is used by `.Run()`, which will os.Exit(...) this code.

type SuiteAction

type SuiteAction func(context.Context) error

SuiteAction is a step that can be run either before or after package tests.

Jump to

Keyboard shortcuts

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