Skip to content

API Reference#

Warning

decoy.next is a preview and not subject to semver. No major changes are anticipated, but cannot be guaranteed until Decoy v3 is released.

decoy.next #

Decoy mocking library.

Use Decoy to create stubs and spies to isolate your code under test.

Classes:

Name Description
AsyncMock

A mock async callable/class, created by Decoy.mock.

Decoy

Decoy mock factory and state container.

Matcher

Create an argument matcher.

Mock

A mock callable/class, created by Decoy.mock.

Stub

Configure how a mock behaves when called.

Verify

Verify how a mock was called.

When

decoy.next.AsyncMock #

Bases: Mock

A mock async callable/class, created by Decoy.mock.

decoy.next.Decoy #

Decoy mock factory and state container.

Use the create context manager to create a new Decoy instance and reset it after your test. If you use the decoy pytest fixture, this is done automatically.

See the setup guide for more details.

Example

with Decoy.create() as decoy:
    ...

Methods:

Name Description
create

Create a Decoy instance for testing that will reset after usage.

mock

Create a mock. See the mock creation guide for more details.

reset

Reset the decoy instance.

verify

Verify a mock was called. See the verify guide for more details.

verify_order

Verify a sequence of interactions.

when

Configure a mock as a stub. See when guide for more details.

decoy.next.Decoy.create() classmethod #

Create a Decoy instance for testing that will reset after usage.

This method is used by the pytest plugin.

decoy.next.Decoy.mock(*, cls=None, func=None, name=None, is_async=False) #

mock(*, cls: Callable[..., ClassT]) -> ClassT
mock(*, func: FuncT) -> FuncT
mock(*, name: str, is_async: Literal[True]) -> AsyncMock
mock(*, name: str, is_async: bool = False) -> Mock

Create a mock. See the mock creation guide for more details.

Parameters:

Name Type Description Default
cls Callable[..., ClassT] | None

A class definition that the mock should imitate.

None
func FuncT | None

A function definition the mock should imitate.

None
name str | None

A name to use for the mock. If you do not use cls or func, you must add a name.

None
is_async bool

Force the returned mock to be asynchronous. This argument only applies if you don't use cls nor func.

False

Returns:

Type Description
ClassT | FuncT | AsyncMock | Mock

A mock typecast as the object it's imitating, if any.

Example

def test_get_something(decoy: Decoy):
    db = decoy.mock(cls=Database)
    # ...

decoy.next.Decoy.reset() #

Reset the decoy instance.

decoy.next.Decoy.verify(mock, *, times=None, ignore_extra_args=False, is_entered=None) #

Verify a mock was called. See the verify guide for more details.

Parameters:

Name Type Description Default
mock SpecT

The mock to verify.

required
times int | None

Limit the number of times the call is expected.

None
ignore_extra_args bool

Only partially match arguments.

False
is_entered bool | None

Verify call happens when the mock is entered using with.

None

Raises:

Type Description
VerifyError

The verification was not satisfied.

NotAMockError

mock is invalid.

Example

def test_create_something(decoy: Decoy):
    gen_id = decoy.mock(func=generate_unique_id)

    # ...

    decoy.verify(gen_id).called_with("model-prefix_")

decoy.next.Decoy.verify_order() #

Verify a sequence of interactions.

All verifications in the sequence must be individually satisfied before the sequence is checked.

See verification usage guide for more details.

Raises:

Type Description
VerifyOrderError

The sequence was not satisfied.

Example

def test_greet(decoy: Decoy):
    verify_greeting = decoy.mock(name="verify_greeting")
    greet = decoy.mock(name="greet")

    # ...

    with decoy.verify_order():
        decoy.verify(verify_greeting).called_with("hello world")
        decoy.verify(greet).called_with("hello world")

decoy.next.Decoy.when(mock, *, times=None, ignore_extra_args=False, is_entered=None) #

Configure a mock as a stub. See when guide for more details.

Parameters:

Name Type Description Default
mock SpecT

The mock to configure.

required
times int | None

Limit the number of times the behavior is triggered.

None
ignore_extra_args bool

Only partially match arguments.

False
is_entered bool | None

Limit the behavior to when the mock is entered using with.

None

Returns:

Type Description
When[SpecT, SpecT]

A stub interface to configure matching arguments.

Raises:

Type Description
NotAMockError

mock is invalid.

Example

db = decoy.mock(cls=Database)
decoy.when(db.exists).called_with("some-id").then_return(True)

decoy.next.Matcher #

Bases: Generic[ValueT]

Create an argument matcher.

Parameters:

Name Type Description Default
match TypedMatch[ValueT] | UntypedMatch

A comparison function that returns a bool or TypeIs guard.

required
name str | None

Optional name for the matcher; defaults to match.__name__

None
description str | None

Optional extra description for the matcher's repr.

None
Example

Use a function to create a custom matcher.

def is_even(target: object) -> TypeIs[int]:
    return isinstance(target, int) and target % 2 == 0

is_even_matcher = Matcher(is_even)

Matchers can also be constructed from built-in inspection functions, like callable.

callable_matcher = Matcher(callable)

Methods:

Name Description
any

Match an argument, optionally by type and/or attributes.

contains

Match a dict, list, or string with a partial value.

error

Match an exception object.

is_not

Match any value that does not == the given value.

matches

Match a string by a pattern.

Attributes:

Name Type Description
arg ValueT

Type-cast the matcher as the expected value.

value ValueT

The latest matching compared value.

values list[ValueT]

All matching compared values.

decoy.next.Matcher.arg property #

Type-cast the matcher as the expected value.

Example

If the mock expects a str argument, using arg prevents the type-checker from raising an error.

decoy
  .when(mock)
  .called_with(Matcher.matches("^(hello|hi)$").arg)
  .then_return("world")

decoy.next.Matcher.value property #

The latest matching compared value.

Raises:

Type Description
NoMatcherValueCapturedError

the matcher has not been compared with any matching value.

Example

You can use value to trigger a callback passed to your mock.

callback_matcher = Matcher(callable)
decoy.verify(mock).called_with(callback_matcher)
callback_matcher.value("value")

decoy.next.Matcher.values property #

All matching compared values.

decoy.next.Matcher.any(type=None, attrs=None) staticmethod #

any(
    type: type[MatchT],
    attrs: collections.abc.Mapping[str, object]
    | None = None,
) -> Matcher[MatchT]
any(
    type: None = None,
    attrs: collections.abc.Mapping[str, object]
    | None = None,
) -> Matcher[Any]

Match an argument, optionally by type and/or attributes.

If type and attributes are omitted, will match everything, including None.

Parameters:

Name Type Description Default
type type[MatchT] | None

Type to match, if any.

None
attrs Mapping[str, object] | None

Set of attributes to match, if any.

None

decoy.next.Matcher.contains(values, in_order=False) staticmethod #

contains(values: MappingT) -> Matcher[MappingT]
contains(
    values: SequenceT, in_order: bool = False
) -> Matcher[SequenceT]

Match a dict, list, or string with a partial value.

Parameters:

Name Type Description Default
values MappingT | SequenceT

Partial value to match.

required
in_order bool

Match list values in order.

False

decoy.next.Matcher.error(type, message=None) staticmethod #

Match an exception object.

Parameters:

Name Type Description Default
type type[ErrorT]

The type of exception to match.

required
message str | None

An optional regular expression pattern to match.

None

decoy.next.Matcher.is_not(value) staticmethod #

Match any value that does not == the given value.

Parameters:

Name Type Description Default
value object

The value that the matcher rejects.

required

decoy.next.Matcher.matches(pattern) staticmethod #

Match a string by a pattern.

Parameters:

Name Type Description Default
pattern str

Regular expression pattern.

required

decoy.next.Mock #

A mock callable/class, created by Decoy.mock.

Attributes:

Name Type Description
__class__ type[Any]

Imitate isinstance checks.

__signature__ Signature | None

Imitate inspect.signature checks.

decoy.next.Mock.__class__ property #

Imitate isinstance checks.

decoy.next.Mock.__signature__ property #

Imitate inspect.signature checks.

decoy.next.Stub #

Bases: Generic[ParamsT, ReturnT, ContextValueT]

Configure how a mock behaves when called.

Methods:

Name Description
then_do

Trigger a callback function.

then_enter_with

Mock a context manager value for a generator context manager.

then_raise

Mock a raised exception.

then_return

Mock a return value.

decoy.next.Stub.then_do(*actions) #

Trigger a callback function.

decoy.next.Stub.then_enter_with(*values) #

Mock a context manager value for a generator context manager.

decoy.next.Stub.then_raise(*errors) #

Mock a raised exception.

decoy.next.Stub.then_return(*values) #

Mock a return value.

decoy.next.Verify #

Bases: Generic[SpecT]

Verify how a mock was called.

Methods:

Name Description
called_with

Verify that a mock was called.

delete

Verify that an attribute was deleted.

set

Verify that an attribute was set.

decoy.next.Verify.called_with(*args, **kwargs) #

Verify that a mock was called.

decoy.next.Verify.delete() #

Verify that an attribute was deleted.

decoy.next.Verify.set(value) #

Verify that an attribute was set.

decoy.next.When #

Bases: Generic[CallableSpecT, AttributeSpecT]

Configure when a mock is triggered.

Methods:

Name Description
called_with

Configure a stub to react to certain passed-in arguments.

delete

Configure a stub to react to an attribute delete.

get

Configure a stub to react to an attribute get.

set

Configure a stub to react to an attribute set.

decoy.next.When.called_with(*args, **kwargs) #

called_with(
    *args: ParamsT.args, **kwargs: ParamsT.kwargs
) -> Stub[ParamsT, ReturnT, ContextValueT]
called_with(
    *args: ParamsT.args, **kwargs: ParamsT.kwargs
) -> Stub[ParamsT, ReturnT | Awaitable[ReturnT], NoReturn]
called_with(
    *args: ParamsT.args, **kwargs: ParamsT.kwargs
) -> Stub[ParamsT, ReturnT, NoReturn]

Configure a stub to react to certain passed-in arguments.

decoy.next.When.delete() #

Configure a stub to react to an attribute delete.

decoy.next.When.get() #

Configure a stub to react to an attribute get.

decoy.next.When.set(value) #

Configure a stub to react to an attribute set.