Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

mck

v0.0.0-20261107141710-3b2f04da4aca
git.sr.ht/~slukits/testing/mck

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

93 matches

Top ↑

Constants

ConnectionString

const ConnectionString = "mck:pgx"

NoExit

const NoExit = math.MinInt

Variables

PncMissingExec (2 declarations)

var (
	PncMissingExec       = "testing/mck.Pgx.Exec: no matching mock"
	PncMultipleExecMocks = "testing/mck.Pgx.Exec: multiple matching mocks"
)

PncMissingQuery (2 declarations)

var (
	PncMissingQuery       = "testing/mck.Pgx.Query: no matching mock"
	PncMultipleQueryMocks = "testing/mck.Pgx.Query: multiple matching mocks"
)

PncScanCounts (3 declarations)

var (
	PncScanCounts          = "testing/mck.rowsMock.Scan: destinations count doesn't match row fields"
	PncMissingRegistration = "testing/mck.rowsMock.Scan: unregistered destination type"
	PncScanDest            = "testing/mck.rowsMock.Scan: scan mock value to destination"
)

ErrScanType

var ErrScanType = errors.New(
	"rowsMock.Scan: row field type doesn't match destination")

Zero

var Zero zero

Zero given to Calls.Has stands for the zero value of the recorded argument at its position.

Functions

Exit

func Exit(funcVar *func(int), assert *int) (deferExitPanic func())

MainStdout

func MainStdout(app string) (outputs func() (out, err string))

OsArgs

func OsArgs(t *std.T, aa ...string)

OsArgs replaces os.Args by given strings and resets them once associated test has ended. NOTE: it is NOT save to execute a test with OsArgs-mocking concurrently with other tests.

Stderr

func Stderr(t *std.T) func() string

Stderr replaces os.Stderr with an temporary *os.File which is cleaned up and reset after the test was executed and whose content can be retrieved calling returned function. NOTE: when parallel running tests mock os.Stderr then Stderr will panic.

Stdout

func Stdout(t *std.T) func() string

Stdout replaces os.Stdout with an temporary *os.File which is cleaned up and reset after the test was executed and whose content can be retrieved calling returned function. NOTE: when parallel running tests mock os.Stdout then Stdout will panic.

Type

func Type[T any]() reflect.Type

Type returns the type T for an ArgsDef call, e.g. Type[io.Reader](). It is needed for interface types since an interface value passed as any only reveals the type of its implementation (or none if passed value is nil).

Types

CallRecorder

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

CallRecorder records the calls of a mocked function to assert if, how often and with which arguments it was called. The zero value is ready to use and safe for concurrent use. The arguments of the first recorded call define the argument types which all further calls must have unless ArgsDef defined them beforehand.

CallRecorder.ArgsDef

func (cr *CallRecorder) ArgsDef(defs ...any)

ArgsDef defines the argument types of recorded calls by given example values respectively by types obtained from Type. It is needed if an argument is of an interface type, i.e. if its dynamic type may vary between calls or it may be nil. ArgsDef panics if the argument types are already defined.

CallRecorder.Calls

func (cr *CallRecorder) Calls(t testing.T) Calls

CallRecorder.Must

func (cr *CallRecorder) Must(
	t testing.T, timeout time.Duration,
) Calls

Must returns the so far recorded calls. It waits for the first call and fatales given test t if there is none before timeout.

CallRecorder.Record

func (cr *CallRecorder) Record(args ...any)

Record records a call with given arguments. It panics if args don't match the defined argument types. NOTE a slice argument which the caller modifies later on must be cloned before it is recorded.

Calls

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

Calls is a snapshot of the calls of a CallRecorder.

Calls.Arg

func (cc Calls) Arg(i int) iter.Seq[any]

Arg iterates over the i-th argument of all recorded calls. It errors the test and yields nothing if there is no i-th argument.

Calls.Has

func (cc Calls) Has(args ...any) bool

Has reports if there is a call with given arguments. An argument is identified by its position and type: the first given argument stands for the first recorded argument accepting its type, the second for the next one after that accepting its type and so on. I.e. for calls of f(old, new string, fm os.FileMode) the arguments (old), (old, new), (fm), (old, fm) or (old, new, fm) may be given while new can't be asked for without old. Has errors the test if the types of given arguments can't be identified that way.

Calls.HasArg

func (cc Calls) HasArg(i int, fn func(arg any) bool) bool

HasArg reports if the i-th argument of a recorded call satisfies given predicate fn. It errors the test if there is no i-th argument.

Calls.Len

func (cc Calls) Len() int

Len returns the number of recorded calls.

Calls.Match

func (cc Calls) Match(ss ...string) bool

CmdCond

type CmdCond func() bool

CmdCond represents a fixture condition which if it is true triggers its associated mocked return values.

CmdValues

type CmdValues = func(args ...string) (string, error)

CmdValues is a function that provides return values for an os/exec command mock while provided with the arguments of the command.

Doer

type Doer func(*http.Request) (*http.Response, error)

Exec

type Exec struct {
	ProductionCmd func(string, ...string) (string, error)
	// contains filtered or unexported fields
}

Exec allows to systematically mock system command executions:

var (
	exec x.Exec
	execMocker mck.Exec
)

execMocker.Production = exec.Dep.Set(x.Cmd(execMocker.Cmd)).(
	func(string, ...string) (string, error))
execMocker.Mock("stdout", nil, "command", "arg1", "arg2")

out, err := exec.Dep.Cmd("command", "arg1", "arg2")

fmt.Println(out) // will print "stdout"
fmt.Println(err) // will print nil

Note: Exec.Mock* methods provide the created mck.OsExecMock which will be used to match against executed production commands to identify mocked values. These mck.OsExecMock instances may be modified.

Note a mocked command execution will panic if more then one mock matches the command. See Exec.MockOn for an extended option to discriminate two mocks which would otherwise both match an executed command.

Exec.Called

func (exc *Exec) Called(cmd string, args ...string) bool

Exec.ClearOn

func (exc *Exec) ClearOn()

ClearOn removes all conditioned mocks.

Exec.Cmd

func (exc *Exec) Cmd(cmd string, args ...string) (string, error)

Cmd implements the x.Exec.Dep.Cmd dependency and matches registered mocks against given command with its arguments. If a matching mock is found its values are returned; otherwise the production command execution is called.

Exec.Count

func (exc *Exec) Count(cmd string, args ...string) int

Exec.Mock

func (exc *Exec) Mock(
	stdout string, err error, match ...string,
) *OsExecMock

Mock registers given return values stdout and err for commands that match given strings.

Exec.MockFn

func (exc *Exec) MockFn(fn CmdValues, match ...string) *OsExecMock

MockFn register given return values function for command executions that match given strings.

Exec.MockOn

func (exc *Exec) MockOn(
	c CmdCond, stdout string, err error, match ...string,
) *OsExecMock

MockOn returns mocked stdout and err if given condition c evaluates to true and given strings match the executed command string. Note this feature allows to circumvent the restriction that only one mock can match an executed command. But OsExec will still panic if two mocks match the same command and have their respective conditions true at the same time.

ExecQry

type ExecQry struct {
	// Err returned for conn.Exec
	Err error
	// Assert hook is called with the Exec-SQL and its arguments before
	// the mocked values are returned
	Assert func(string, ...any)
	// Executed is set to true once an Exec-mock has been successfully
	// matched to a production Exec-call.
	Executed bool
	// contains filtered or unexported fields
}

ExecQry instances are tried to be matched against production ExecQry-calls. In case of a match it's set mock-values are injected as return values for the production ExecQry-call.

Execs

type Execs []*ExecQry

Execs are a sequence of mck.Exec-mock-definitions.

HttpIO

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

HttpIO.Do

func (hio *HttpIO) Do(default_ Doer) Doer

HttpIO.MckDo

func (hio *HttpIO) MckDo(
	rsp *http.Response, err error, matches ...string,
) *Response

HttpIO.MckRequest

func (hio *HttpIO) MckRequest(
	r *http.Request, err error, matches ...string,
) *Request

HttpIO.NewRequest

func (hio *HttpIO) NewRequest(method, url string, body io.Reader) (
	*http.Request, error,
)

Logger

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

Logger provides an concurrency save in memory log/slog-logger. A logger may not be copied after its first use.

Logger.Debug

func (lg *Logger) Debug(msg string, attrs ...any)

Logger.Error

func (lg *Logger) Error(msg string, attrs ...any)

Logger.Info

func (lg *Logger) Info(msg string, attrs ...any)

Logger.String

func (lg *Logger) String() string

Logger.Warn

func (lg *Logger) Warn(msg string, attrs ...any)

Match

type Match = []string

Match is a more meaningful alias for []string holding strings which are matched against an other string.

OsExecMock

type OsExecMock struct {
	Stdout string
	Err    error
	Fn     CmdValues
	Match  []string
	Cond   CmdCond
	// contains filtered or unexported fields
}

Pgx

type Pgx struct {
	Scanners scanners
	CloseErr error
	Closed   bool
	PingErr  error
	// contains filtered or unexported fields
}

Pgx allows to mock a database connection by using Pgx.MQuery and Pgx.MExec to mock return values of Pgx.Query and Pgx.Exec calls.

Pgx.AnyExec

func (px *Pgx) AnyExec(commandTag string) *ExecQry

AnyExec is an easy way to make all production Exec calls successful (or fail).

Pgx.AnyQuery

func (px *Pgx) AnyQuery() *Query

AnyQuery is an easy way to make all production Query calls successful (or fail). Note: since a successful Query call depends on a matching number of row fields and scanning destinations the only way to make all queries pass is to not provide any rows. I.e. the passing "AnyQuery" is not able to provide data.

Pgx.Close

func (px *Pgx) Close(_ context.Context) error

Pgx.Exec

func (px *Pgx) Exec(
	_ context.Context, sql string, args ...any,
) (pgconn.CommandTag, error)

Exec mocks pgx.Conn.Exec. It fails if a particular production Exec-call matches more then one mck.Exec instance or if it matches none. But in the later case it tries first to fall back to an Pgx.AnyExec mock.

Pgx.MExec

func (px *Pgx) MExec(commandTag string, match ...string) *ExecQry

MExec mock an Pgx.Exec-SQL whose string representation is matched by sequence of match-strings to return given command tag. Returned mck.Exec-instance may be used

Pgx.MNotify

func (px *Pgx) MNotify(channel, payload string)

MNotify adds a mock notification to the queue.

Pgx.MNotifyErr

func (px *Pgx) MNotifyErr(err error)

MNotifyErr sets a mock notification error that will be returned on the next wait.

Pgx.MQuery

func (px *Pgx) MQuery(mm Match, rr ...Row) *Query

MQuery mockup the return value of Query-call. Note two mocks matching the same query will panic.

Pgx.Ping

func (px *Pgx) Ping(_ context.Context) error

Pgx.Query

func (px *Pgx) Query(
	_ context.Context, sql string, args ...any,
) (pgx.Rows, error)

Query mocks pgx.Conn.Query. It fails if a particular production Query-call matches more then one mck.Query instance or if it matches none. But in the later case it tries first to fall back to an Pgx.AnyQuery mock.

Pgx.String

func (px *Pgx) String() string

Pgx.WaitForNotification

func (px *Pgx) WaitForNotification(ctx context.Context) (*pgconn.Notification, error)

WaitForNotification waits for a mock notification or error, or until the context is canceled.

Queries

type Queries []*Query

Query

type Query struct {
	// Err returned for conn.Query
	Err error
	// Rows provide the mocked data
	Rows Rows
	// contains filtered or unexported fields
}

Request

type Request struct {
	Mck       *http.Request
	Err       error
	Matches   []string
	MatchesFn func(_, _ string) bool
}

Requests

type Requests []*Request

Response

type Response struct {
	Mck       *http.Response
	Err       error
	Matches   []string
	MatchesFn func(_, _ string) bool
}

Responses

type Responses []*Response

Row

type Row []any

Rows

type Rows struct {
	// RR is the data provided by Rows.Next/Rows.Scan
	RR []Row
	// Closed is set to true once RowsMock.Close was called.
	Closed bool
	// RowsErr returned from pgx.Rows.Err
	RowsErr error
	// ScanErr returned from pgx.Rows.Scan
	ScanErr error
	// contains filtered or unexported fields
}

Rows implements the pgx.Rows interface.

Rows.Close

func (rr *Rows) Close()

Close mocks pgx.Rows.Close and sets the rowsMock.Closed flag.

Rows.CommandTag

func (rr *Rows) CommandTag() pgconn.CommandTag

CommandTag mocks pgx.Rows.CommandTag (unimplemented).

Rows.Conn

func (rr *Rows) Conn() *pgx.Conn

Conn mocks pgx.Rows.Conn (unimplemented).

Rows.Err

func (rr *Rows) Err() error

Err mocks pgx.Rows.Err returning given rows-mock error.

Rows.FieldDescriptions

func (rr *Rows) FieldDescriptions() []pgconn.FieldDescription

FieldDescriptions mocks pgx.Rows.FieldDescriptions (unimplemented).

Rows.Next

func (rr *Rows) Next() bool

Next mocks pgx.Rows.Next go es to the next mocked record or returns false.

Rows.RawValues

func (rr *Rows) RawValues() [][]byte

RawValues mocks pgx.Rows.RawValues (unimplemented).

Rows.Scan

func (rr *Rows) Scan(dest ...any) error

Scan mocks pgx.Rows.Scan trying to read mocked record into given destinations. Scan fails if the destinations count doesn't match the mocked row's fields count or if the row filed type can't be matched with the destination type.

Rows.Values

func (rr *Rows) Values() ([]any, error)

Values mocks pgx.Rows.Values (unimplemented).

Scanner

type Scanner func(any) (any, error)

Values

type Values[T any] struct {
	// contains filtered or unexported fields
}

Values[T].Add

func (vv *Values[T]) Add(values ...T) *Values[T]

Values[T].Clear

func (vv *Values[T]) Clear() *Values[T]

Values[T].Next

func (vv *Values[T]) Next() T

Dependency graph