testh

package
v0.47.4 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2024 License: MIT Imports: 61 Imported by: 0

Documentation

Overview

Package testh (test helper) contains functionality for testing.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DriverDefsFrom

func DriverDefsFrom(tb testing.TB, cfgFiles ...string) []*userdriver.DriverDef

DriverDefsFrom builds DriverDef values from cfg files.

func DriverDetectors added in v0.34.0

func DriverDetectors() []files.TypeDetectFunc

DriverDetectors returns the common set of TypeDetectorFuncs.

func ExtractHandlesFromQuery added in v0.47.0

func ExtractHandlesFromQuery(tb testing.TB, query string, failOnErr bool) []string

ExtractHandlesFromQuery returns all handles mentioned in the query. If failOnErr is true, the test will fail on any parse error; otherwise, the test will log the error and return an empty slice.

func GenerateLargeCSV added in v0.47.0

func GenerateLargeCSV(t *testing.T, fp string)

GenerateLargeCSV generates a large CSV file. At count = 5000000, the generated file is ~500MB.

func KindScanType

func KindScanType(knd kind.Kind) reflect.Type

KindScanType returns the default scan type for kind. The returned type is typically a sql.NullType.

func NewActorSource added in v0.47.3

func NewActorSource(tb testing.TB, handle string, clean bool) *source.Source

NewActorSource returns a new *source.Source for a copy of the Sakila actor.csv datafile, using the given handle. If clean is true, the copy is deleted by t.Cleanup.

func NewRecordMeta

func NewRecordMeta(colNames []string, colKinds []kind.Kind) record.Meta

NewRecordMeta builds a new record.Meta instance for testing.

func RecordsFromTbl

func RecordsFromTbl(tb testing.TB, handle, tbl string) (recMeta record.Meta, recs []record.Record)

RecordsFromTbl returns a cached copy of all records from handle.tbl. The function performs a "SELECT * FROM tbl" and caches (in a package variable) the returned recs and recMeta for subsequent calls. Thus if the underlying data source records are modified, the returned records may be inconsistent.

This function effectively exists to speed up testing times.

func SetBuildVersion added in v0.34.0

func SetBuildVersion(tb testing.TB, vers string)

SetBuildVersion sets the build version for the lifecycle of test t.

func TempLockFunc added in v0.47.0

func TempLockFunc(tb testing.TB) lockfile.LockFunc

TempLockFunc returns a lockfile.LockFunc that uses a temp file.

func TempLockfile added in v0.47.0

func TempLockfile(tb testing.TB) lockfile.Lockfile

TempLockfile returns a lockfile.Lockfile that uses a temp file.

Types

type Helper

type Helper struct {
	T testing.TB

	Context context.Context

	Cleanup *cleanup.Cleanup
	// contains filtered or unexported fields
}

Helper encapsulates a test helper session.

func New

func New(tb testing.TB, opts ...Option) *Helper

New returns a new Helper. The helper's Close func will be automatically invoked via t.Cleanup.

func NewWith

func NewWith(tb testing.TB, handle string) (*Helper, *source.Source,
	driver.SQLDriver, driver.Grip, *sql.DB,
)

NewWith is a convenience wrapper for New, that also returns the source.Source for handle, the driver.SQLDriver, driver.Grip, and the *sql.DB.

func (*Helper) Add added in v0.41.0

func (h *Helper) Add(src *source.Source) *source.Source

Add adds src to the helper's collection.

func (*Helper) Close

func (h *Helper) Close()

Close runs any cleanup tasks, failing h's testing.T if any cleanup error occurs. Close is automatically invoked via t.Cleanup, it does not need to be explicitly invoked unless desired.

func (*Helper) CopyTable

func (h *Helper) CopyTable(
	dropAfter bool,
	src *source.Source,
	fromTable, toTable tablefq.T,
	copyData bool,
) string

CopyTable copies fromTable into a new table toTable. If toTable is empty, a unique table name is generated based on fromTable. The table name used is returned. If dropAfter is true, the table is dropped when t.Cleanup is run. If copyData is true, fromTable's data is also copied. Constraints (keys, defaults etc.) may not be copied.

TODO: CopyTable should return tablefq.T instead of string.

func (*Helper) CreateTable

func (h *Helper) CreateTable(dropAfter bool, src *source.Source, tblDef *schema.Table,
	data ...[]any,
) (affected int64)

CreateTable creates a new table in src, and inserts data, returning the number of data rows inserted. If dropAfter is true, the created table is dropped when t.Cleanup is run.

func (*Helper) DiffDB

func (h *Helper) DiffDB(src *source.Source)

DiffDB fails the test if src's metadata is substantially different when t.Cleanup runs vs when DiffDB is invoked. Effectively DiffDB takes before and after snapshots of src's metadata, and compares various elements such as the number of tables, table row counts, etc. DiffDB is useful for verifying that tests are leaving the database as they found it.

Note that DiffDB adds considerable overhead to test runtime.

If envar SQ_TEST_DIFFDB is true, DiffDB is run on every SQL source returned by Helper.Source.

func (*Helper) DriverFor

func (h *Helper) DriverFor(src *source.Source) driver.Driver

DriverFor is a convenience method to get src's driver.Driver.

func (*Helper) DropTable

func (h *Helper) DropTable(src *source.Source, tbl tablefq.T)

DropTable drops tbl from src.

func (*Helper) ExecSQL

func (h *Helper) ExecSQL(src *source.Source, query string, args ...any) (affected int64)

ExecSQL is a convenience wrapper for sql.DB.Exec that returns the rows affected, failing on any error. Note that ExecSQL uses the same Grip instance as returned by h.Open.

func (*Helper) Files

func (h *Helper) Files() *files.Files

Files returns the helper's source.Files instance.

func (*Helper) Grips added in v0.47.0

func (h *Helper) Grips() *driver.Grips

Grips returns the helper's driver.Grips instance.

func (*Helper) Insert

func (h *Helper) Insert(src *source.Source, tbl string, cols []string, records ...[]any) (affected int64)

Insert inserts records for cols into src.tbl, returning the number of records inserted. Note that the records arg may be mutated by src's driver InsertMungeFunc.

func (*Helper) InsertDefaultRow

func (h *Helper) InsertDefaultRow(src *source.Source, tbl string)

InsertDefaultRow executes the equivalent of INSERT INTO tbl DEFAULT VALUES. It fails if a row was not inserted.

Note that for some driver types, the driver does not support DEFAULT values for some col types. For example this method may fail for a MySQL column "col_text TEXT NOT NULL", as TEXT and BLOB cannot have a DEFAULT value.

func (*Helper) IsMonotable

func (h *Helper) IsMonotable(src *source.Source) bool

IsMonotable returns true if src's driver is monotable.

func (*Helper) Log

func (h *Helper) Log() *slog.Logger

func (*Helper) NewCollection added in v0.34.0

func (h *Helper) NewCollection(handles ...string) *source.Collection

NewCollection is a convenience function for building a new *source.Collection incorporating the supplied handles. See Helper.Source for more on the behavior.

func (*Helper) Open

func (h *Helper) Open(src *source.Source) driver.Grip

Open opens a driver.Grip for src via h's internal Grips instance: thus subsequent calls to Open may return the same driver.Grip instance. The opened driver.Grip will be closed during h.Close.

func (*Helper) OpenDB added in v0.41.0

func (h *Helper) OpenDB(src *source.Source) *sql.DB

OpenDB is a convenience method for getting the sql.DB for src. The returned sql.DB is closed during h.Close, via the closing of its parent driver.Grip.

func (*Helper) QuerySLQ added in v0.29.0

func (h *Helper) QuerySLQ(query string, args map[string]string) (*RecordSink, error)

QuerySLQ executes the SLQ query. Args are predefined variables for substitution.

func (*Helper) QuerySQL

func (h *Helper) QuerySQL(src *source.Source, db sqlz.DB, query string, args ...any) (*RecordSink, error)

QuerySQL uses libsq.QuerySQL to execute SQL query against src, returning a sink to which all records have been written. Typically the db arg is nil, and QuerySQL uses the same driver.Grip instance as returned by Helper.Open. If db is non-nil, it is passed to libsq.QuerySQL (e.g. the query needs to execute against a sql.Tx), and the caller is responsible for closing db.

func (*Helper) Registry

func (h *Helper) Registry() *driver.Registry

Registry returns the helper's registry instance, configured with standard providers.

func (*Helper) RowCount

func (h *Helper) RowCount(src *source.Source, tbl string) int64

RowCount returns the result of "SELECT COUNT(*) FROM tbl", failing h's test on any error.

func (*Helper) Run added in v0.37.0

func (h *Helper) Run() *run.Run

Run returns the helper's run instance.

func (*Helper) SQLDriverFor

func (h *Helper) SQLDriverFor(src *source.Source) driver.SQLDriver

SQLDriverFor is a convenience method to get src's driver.SQLDriver.

func (*Helper) Source

func (h *Helper) Source(handle string) *source.Source

Source returns a test Source with the given handle. The standard test source collection is loaded from the sq config file at TestSourcesConfigPath, (but additional sources can be added via Helper.Add). Variables such as ${SQ_ROOT} in the config file are expanded. The same instance of *source.Source will be returned for multiple invocations of this method on the same Helper instance.

For certain file-based driver types, the returned src's Location may point to a copy of the file. This helps avoid tests dirtying a version-controlled data file.

Any external database source (that is, any SQL source other than SQLite3) will have its location determined from an envar. Given a source @sakila_pg12, its location is derived from an envar SQ_TEST_SRC__SAKILA_PG12. If that envar is not set, the test calling this method will be skipped.

If envar SQ_TEST_DIFFDB is true, DiffDB is run on every SQL source returned by Source.

func (*Helper) SourceConfigured added in v0.47.0

func (h *Helper) SourceConfigured(handle string) bool

SourceConfigured returns true if the source is configured. Note that Helper.Source skips the test if the source is not configured: that is to say, if the source location requires population via an envar, and the envar is not set. For example, for the PostgreSQL source @sakila_pg12, the envar SQ_TEST_SRC__SAKILA_PG12 is required. SourceConfigured tests if that envar is set.

func (*Helper) SourceMetadata added in v0.41.0

func (h *Helper) SourceMetadata(src *source.Source) (*metadata.Source, error)

SourceMetadata returns metadata for src.

func (*Helper) TableMetadata added in v0.41.0

func (h *Helper) TableMetadata(src *source.Source, tbl string) (*metadata.Table, error)

TableMetadata returns metadata for src's table.

func (*Helper) TruncateTable

func (h *Helper) TruncateTable(src *source.Source, tbl string) (affected int64)

TruncateTable truncates tbl in src.

type Option added in v0.34.0

type Option func(h *Helper)

Option is a functional option type used with New to configure the helper.

func OptCaching added in v0.47.0

func OptCaching(enable bool) Option

OptCaching enables or disables ingest caching.

func OptNoLog added in v0.47.0

func OptNoLog() Option

OptNoLog disables the test logger.

type RecordSink

type RecordSink struct {
	// RecMeta holds the recMeta received via Open.
	RecMeta record.Meta

	// Recs holds the records received via WriteRecords.
	Recs []record.Record

	// Closed tracks the times Close was invoked.
	Closed []time.Time

	// Flushed tracks the times Flush was invoked.
	Flushed []time.Time
	// contains filtered or unexported fields
}

RecordSink is an impl of output.RecordWriter that captures invocations of that interface.

func (*RecordSink) Close

func (r *RecordSink) Close(context.Context) error

Close implements libsq.RecordWriter.

func (*RecordSink) Flush

func (r *RecordSink) Flush(context.Context) error

Flush implements libsq.RecordWriter.

func (*RecordSink) Open

func (r *RecordSink) Open(_ context.Context, recMeta record.Meta) error

Open implements libsq.RecordWriter.

func (*RecordSink) Result added in v0.32.0

func (r *RecordSink) Result() any

Result returns the first (and only) value returned from a query like "SELECT COUNT(*) FROM actor". It is effectively the same as RecordSink.Recs[0][0]. The function will panic if there is no appropriate result.

func (*RecordSink) WriteRecords

func (r *RecordSink) WriteRecords(_ context.Context, recs []record.Record) error

WriteRecords implements libsq.RecordWriter.

Directories

Path Synopsis
Package fixt contains common test fixture values.
Package fixt contains common test fixture values.
Package proj contains test utilities for dealing with project paths and the like.
Package proj contains test utilities for dealing with project paths and the like.
Package sakila holds test constants and such for the sakila test sources.
Package sakila holds test constants and such for the sakila test sources.
Package testsrc holds testing constants (in addition to pkg sakila).
Package testsrc holds testing constants (in addition to pkg sakila).
Package tu contains basic generic test utilities.
Package tu contains basic generic test utilities.

Jump to

Keyboard shortcuts

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