test

package
v0.0.0-...-66e4c3a Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2023 License: MIT Imports: 43 Imported by: 0

README

/test

General global test utilities.

Regarding test/test_*.go and its test.With* functions

Test helpers like test.WithTestDatabase and test.WithTestServer require usage of a closure, as these functions automatically manage the setup and teardown (e.g. server shutdown, db connection drop) for your testcase.

Other pkgs don't have this requirement (e.g. the initialization code for test.NewTestMailer which covers the setup for the mailer mock), thus, please use this With* convention incl. closure only when it makes sense.

Regarding test/fixtures.go

This are your global db test fixtures, that are only available while testing. However, feel free to setup specialized fixtures per package if required (e.g. just initialize an additional IntegreSQL template).

Regarding test/helper_*.go

Please use this convention to specify test only utility functions.

Regarding snapshot testing

Golden files can be created by using the Snapshoter.Save(t TestingT, data ...interface{}) method. The snapshot can be configured to force an update, use a different replacer function or to set a different file location and suffix for the snaphot.

A snapshot can be updated by either calling the Update(true) method, or by using the global override by setting the environment variable TEST_UPDATE_GOLDEN to true. To update all snapshots the call might look like this: TEST_UPDATE_GOLDEN=true make test.

testdata and . or _ prefixed files

Note that Go will ignore directories or files that begin with "." or "_", so you have more flexibility in terms of how you name your test data directory.

Go build ignores directory named testdata. The Go tool will ignore any directory in your $GOPATH that starts with a period, an underscore, or matches the word testdata When go test runs, it sets current directory as package directory

Examples:

https://github.com/golang-standards/project-layout/tree/master/test

Documentation

Index

Constants

View Source
const (
	PlainTestUserPassword  = "password"
	HashedTestUserPassword = "$argon2id$v=19$m=65536,t=1,p=4$RFO8ulg2c2zloG0029pAUQ$2Po6NUIhVCMm9vivVDuzo7k5KVWfZzJJfeXzC+n+row" //nolint:gosec
)
View Source
const (
	TestMailerDefaultSender = "test@example.com"
)

Variables

View Source
var (
	DefaultSnapshotDirPathAbs = filepath.Join(util.GetProjectRootDir(), "/test/testdata/snapshots")
	UpdateGoldenGlobal        = util.GetEnvAsBool("TEST_UPDATE_GOLDEN", false)
)
View Source
var Snapshoter = snapshoter{
	// contains filtered or unexported fields
}

Functions

func ApplyDump

func ApplyDump(ctx context.Context, t *testing.T, db *sql.DB, dumpFile string) error

ApplyDump applies dumpFile (absolute path to .sql file) to db

func ApplyMigrations

func ApplyMigrations(t *testing.T, db *sql.DB) (countMigrations int, err error)

ApplyMigrations applies all current database migrations to db

func ApplyTestFixtures

func ApplyTestFixtures(ctx context.Context, t *testing.T, db *sql.DB) (countFixtures int, err error)

ApplyTestFixtures applies all current test fixtures (insert) to db

func CompareAll

func CompareAll(t *testing.T, base map[string]string, toCheck map[string]string, skipKeys map[string]bool)

func CompareAllPayload

func CompareAllPayload(t *testing.T, base map[string]interface{}, toCheck map[string]string, skipKeys map[string]bool, keyConvertFunc ...func(string) string)

func CompareFileHashes

func CompareFileHashes(t *testing.T, expectedFile string, actualFile string)

func DotEnvLoadFileOrSkipTest

func DotEnvLoadFileOrSkipTest(t *testing.T, absolutePathToEnvFile string)

DotEnvLoadFileOrSkipTest tries to load the overgiven path to the dotenv file overwriting ENV vars. If the file is not found, the test will be automatically skipped.

func DotEnvLoadLocalOrSkipTest

func DotEnvLoadLocalOrSkipTest(t *testing.T)

DotEnvLoadLocalOrSkipTest tries to load the `.env.local` file in the projectroot overwriting ENV vars. If the file is not found, the test will be automatically skipped.

func GetMapFromStruct

func GetMapFromStruct(s interface{}) map[string]string

func GetMapFromStructByTag

func GetMapFromStructByTag(tag string, s interface{}) map[string]string

GetMapFromStructByTag returns a map of a given struct using a tag name as key and the string of the property value as value. inspired by: https://stackoverflow.com/questions/55879028/golang-get-structs-field-name-by-json-tag

func GetTestMailerMockTransport

func GetTestMailerMockTransport(t *testing.T, m *mailer.Mailer) *transport.MockMailTransport

func HeadersWithAuth

func HeadersWithAuth(t *testing.T, token string) http.Header

func HeadersWithConfigurableAuth

func HeadersWithConfigurableAuth(t *testing.T, scheme string, token string) http.Header

func NewSMTPMailerFromDefaultEnv

func NewSMTPMailerFromDefaultEnv(t *testing.T) *mailer.Mailer

func NewTestMailer

func NewTestMailer(t *testing.T) *mailer.Mailer

func NewTestPusher

func NewTestPusher(t *testing.T, db *sql.DB) *push.Service

func ParseResponseAndValidate

func ParseResponseAndValidate(t *testing.T, res *httptest.ResponseRecorder, v runtime.Validatable)

func ParseResponseBody

func ParseResponseBody(t *testing.T, res *httptest.ResponseRecorder, v interface{})

func PerformRequest

func PerformRequest(t *testing.T, s *api.Server, method string, path string, body GenericPayload, headers http.Header) *httptest.ResponseRecorder

func PerformRequestWithArray

func PerformRequestWithArray(t *testing.T, s *api.Server, method string, path string, body GenericArrayPayload, headers http.Header) *httptest.ResponseRecorder

func PerformRequestWithArrayAndParams

func PerformRequestWithArrayAndParams(t *testing.T, s *api.Server, method string, path string, body GenericArrayPayload, headers http.Header, queryParams map[string]string) *httptest.ResponseRecorder

func PerformRequestWithParams

func PerformRequestWithParams(t *testing.T, s *api.Server, method string, path string, body GenericPayload, headers http.Header, queryParams map[string]string) *httptest.ResponseRecorder

func PerformRequestWithRawBody

func PerformRequestWithRawBody(t *testing.T, s *api.Server, method string, path string, body io.Reader, headers http.Header, queryParams map[string]string) *httptest.ResponseRecorder

func WithTestDatabase

func WithTestDatabase(t *testing.T, closure func(db *sql.DB))

WithTestDatabase returns an isolated test database based on the current migrations and fixtures.

func WithTestDatabaseContext

func WithTestDatabaseContext(ctx context.Context, t *testing.T, closure func(db *sql.DB))

WithTestDatabaseContext returns an isolated test database based on the current migrations and fixtures. The provided context will be used during setup (instead of the default background context).

func WithTestDatabaseEmpty

func WithTestDatabaseEmpty(t *testing.T, closure func(db *sql.DB))

WithTestDatabaseEmpty returns an isolated test database with no migrations applied or fixtures inserted.

func WithTestDatabaseEmptyContext

func WithTestDatabaseEmptyContext(ctx context.Context, t *testing.T, closure func(db *sql.DB))

WithTestDatabaseEmptyContext returns an isolated test database with no migrations applied or fixtures inserted. The provided context will be used during setup (instead of the default background context).

func WithTestDatabaseFromDump

func WithTestDatabaseFromDump(t *testing.T, config DatabaseDumpConfig, closure func(db *sql.DB))

WithTestDatabaseFromDump returns an isolated test database based on a dump file.

func WithTestDatabaseFromDumpContext

func WithTestDatabaseFromDumpContext(ctx context.Context, t *testing.T, config DatabaseDumpConfig, closure func(db *sql.DB))

WithTestDatabaseFromDumpContext returns an isolated test database based on a dump file. The provided context will be used during setup (instead of the default background context).

func WithTestPusher

func WithTestPusher(t *testing.T, closure func(p *push.Service, db *sql.DB))

func WithTestServer

func WithTestServer(t *testing.T, closure func(s *api.Server))

WithTestServer returns a fully configured server (using the default server config).

func WithTestServerConfigurable

func WithTestServerConfigurable(t *testing.T, config config.Server, closure func(s *api.Server))

WithTestServerConfigurable returns a fully configured server, allowing for configuration using the provided server config.

func WithTestServerConfigurableContext

func WithTestServerConfigurableContext(ctx context.Context, t *testing.T, config config.Server, closure func(s *api.Server))

WithTestServerConfigurableContext returns a fully configured server, allowing for configuration using the provided server config. The provided context will be used during setup (instead of the default background context).

func WithTestServerConfigurableFromDump

func WithTestServerConfigurableFromDump(t *testing.T, config config.Server, dumpConfig DatabaseDumpConfig, closure func(s *api.Server))

WithTestServerConfigurableFromDump returns a fully configured server, allowing for configuration using the provided server config and a database dump to be injected.

func WithTestServerConfigurableFromDumpContext

func WithTestServerConfigurableFromDumpContext(ctx context.Context, t *testing.T, config config.Server, dumpConfig DatabaseDumpConfig, closure func(s *api.Server))

WithTestServerConfigurableFromDumpContext returns a fully configured server, allowing for configuration using the provided server config and a database dump to be injected. The provided context will be used during setup (instead of the default background context).

func WithTestServerFromDump

func WithTestServerFromDump(t *testing.T, dumpConfig DatabaseDumpConfig, closure func(s *api.Server))

WithTestServerFromDump returns a fully configured server (using the default server config) and allows for a database dump to be injected.

Types

type DatabaseDumpConfig

type DatabaseDumpConfig struct {
	DumpFile          string // required, absolute path to dump file
	ApplyMigrations   bool   // optional, default false
	ApplyTestFixtures bool   // optional, default false
}

type FixtureMap

type FixtureMap struct {
	User1                         *models.User
	User1AppUserProfile           *models.AppUserProfile
	User1AccessToken1             *models.AccessToken
	User1RefreshToken1            *models.RefreshToken
	User2                         *models.User
	User2AppUserProfile           *models.AppUserProfile
	User2AccessToken1             *models.AccessToken
	User2RefreshToken1            *models.RefreshToken
	UserDeactivated               *models.User
	UserDeactivatedAppUserProfile *models.AppUserProfile
	UserDeactivatedAccessToken1   *models.AccessToken
	UserDeactivatedRefreshToken1  *models.RefreshToken
	User1PushToken                *models.PushToken
	User1PushTokenAPN             *models.PushToken
}

The main definition which fixtures are available through Fixtures(). Mind the declaration order! The fields get inserted exactly in the order they are declared.

func Fixtures

func Fixtures() FixtureMap

Fixtures returns a function wrapping our fixtures, which tests are allowed to manipulate. Each test (which may run concurrently) receives a fresh copy, preventing side effects between test runs.

type GenericArrayPayload

type GenericArrayPayload []interface{}

func (GenericArrayPayload) Reader

func (g GenericArrayPayload) Reader(t *testing.T) *bytes.Reader

type GenericPayload

type GenericPayload map[string]interface{}

func (GenericPayload) Reader

func (g GenericPayload) Reader(t *testing.T) *bytes.Reader

type Insertable

type Insertable interface {
	Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error
}

Insertable represents a common interface for all model instances so they may be inserted via the Inserts() func

func Inserts

func Inserts() []Insertable

Inserts defines the order in which the fixtures will be inserted into the test database

type TestingT

type TestingT interface {
	Cleanup(func())
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fail()
	FailNow()
	Failed() bool
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Helper()
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	Name() string
	Skip(args ...interface{})
	SkipNow()
	Skipf(format string, args ...interface{})
	Skipped() bool
	TempDir() string
}

TestingT is used to generate a mock of testing.T to enable testing of helper methods which are using assert/require Inspired by: https://github.com/uber-go/zap/blob/master/zaptest/testingt_test.go, commit 5b0fd114dcc089875ee61dfad3617c3a43c2e93e

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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