Skip to content

API reference

flexmock(spec=None, **kwargs)

Main entry point into the flexmock API.

This function is used to either generate a new fake object or take an existing object (or class or module) and use it as a basis for a partial mock. In case of a partial mock, the passed in object is modified to support basic Mock class functionality making it unnecessary to make successive flexmock() calls on the same objects to generate new expectations.

It is safe to call flexmock() on the same object again, flexmock will detect when an object has already been partially mocked and return it each time.

Parameters:

Name Type Description Default
spec Optional[Any]

Object, class, or module to mock.

None
**kwargs Any

Method or return value pairs to attach to the object.

{}

Returns:

Type Description
Mock

Mock object if no spec is provided. Otherwise return the spec object.

Examples:

>>> mock = flexmock(Plane)
>>> mock.should_receive("fly")
<flexmock._api.Expectation object at ...>

Mock

Fake object class returned by the flexmock() function.

new_instances(self, *args)

Overrides __new__ method on a class to return custom objects.

Alias for should_receive('__new__').and_return(args).one_by_one().

Parameters:

Name Type Description Default
*args Any

Objects to return on each successive call to __new__.

()

Returns:

Type Description
Expectation

Expectation object.

Examples:

>>> fake_plane = flexmock(model="fake")
>>> flexmock(Plane).new_instances(fake_plane)
<flexmock._api.Expectation object at ...>
>>> Plane().model
'fake'

It is also possible to return different fake objects in a sequence:

>>> fake_plane1 = flexmock(model="fake1")
>>> fake_plane2 = flexmock(model="fake2")
>>> flexmock(Plane).new_instances(fake_plane1, fake_plane2)
<flexmock._api.Expectation object at ...>
>>> Plane().model
'fake1'
>>> Plane().model
'fake2'

should_call(self, name)

Creates a spy.

This means that the original method will be called rather than the fake version. However, we can still keep track of how many times it is called and with what arguments, and apply expectations accordingly.

should_call is meaningless/not allowed for non-callable attributes.

Parameters:

Name Type Description Default
name str

Name of the method to spy.

required

Returns:

Type Description
Expectation

Expectation object.

Examples:

>>> flexmock(plane).should_call("repair").once()
<flexmock._api.Expectation object at ...>
>>> plane.repair("wing")

should_receive(self, name)

Replaces the specified attribute with a fake.

Parameters:

Name Type Description Default
name str

Name of the attribute to replace.

required

Returns:

Type Description
Expectation

Expectation object which can be used to modify the expectations on the fake attribute.

Examples:

>>> flexmock(plane).should_receive("fly").and_return("vooosh!").once()
<flexmock._api.Expectation object at ...>
>>> plane.fly()
'vooosh!'

Expectation

Holds expectations about methods.

The information contained in the Expectation object includes method name, its argument list, return values, and any exceptions that the method might raise.

and_raise(self, exception, *args, **kwargs)

Specifies the exception to be raised when this expectation is met.

Parameters:

Name Type Description Default
exception Type[BaseException]

Exception class.

required
*args Any

Positional arguments to pass to the exception.

()
**kwargs Any

Keyword arguments to pass to the exception.

{}

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

Make a mocked method raise an exception instead of returning a value:

>>> flexmock(plane).should_receive("fly").and_raise(BadWeatherException)
<flexmock._api.Expectation object at ...>
>>> plane.fly()
Traceback (most recent call last):
  ...
BadWeatherException

Make a spy to verify that a specific exception is raised:

>>> flexmock(plane).should_call("repair").and_raise(RuntimeError, "err msg")
<flexmock._api.Expectation object at ...>

and_return(self, *values)

Override the return value of this expectation's method.

When and_return is given multiple times, each value provided is returned on successive invocations of the method. It is also possible to mix and_return with and_raise in the same manner to alternate between returning a value and raising and exception on different method invocations.

When combined with the one_by_one modifier, value is treated as a list of values to be returned in the order specified by successive calls to this method rather than a single list to be returned each time.

Parameters:

Name Type Description Default
*values Any

Optional list of return values, defaults to None if not given.

()

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

Provide return values for mocks:

>>> flexmock(plane).should_receive("land").and_return("landed!").once()
<flexmock._api.Expectation object at ...>
>>> plane.land()
'landed!'

Match specific return values with spies:

>>> flexmock(plane).should_call("passenger_count").and_return(3)
<flexmock._api.Expectation object at ...>
>>> plane.passenger_count()
3

and_yield(self, *args)

Specifies the list of items to be yielded on successive method calls.

In effect, the mocked object becomes a generator.

Parameters:

Name Type Description Default
*args Any

Items to be yielded on successive method calls.

()

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("flight_log").and_yield("fly", "land")
<flexmock._api.Expectation object at ...>
>>> log = plane.flight_log()
>>> next(log)
'fly'
>>> next(log)
'land'

at_least(self)

Modifies the associated times() expectation.

When given, an exception will only be raised if the method is called less than times() specified. Does nothing if times() is not given.

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("fly").at_least().once()
<flexmock._api.Expectation object at ...>
>>> plane.fly("east")

at_most(self)

Modifies the associated times() expectation.

When given, an exception will only be raised if the method is called more than times() specified. Does nothing if times() is not given.

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("land").at_most().once()
<flexmock._api.Expectation object at ...>
>>> plane.land()
>>> plane.land()
Traceback (most recent call last):
  ...
flexmock.exceptions.MethodCallError: land() expected to be called at most...

mock(self)

Return the mock associated with this expectation.

Returns:

Type Description
Mock

Mock associated with this expectation.

Examples:

>>> plane = flexmock(plane).should_receive("fly").mock()

never(self)

Expect expectation's method to never be called.

Alias for times(0).

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("crash").never()
<flexmock._api.Expectation object at ...>
>>> plane.crash()
Traceback (most recent call last):
  ...
flexmock.exceptions.MethodCallError: crash() expected to be called...

once(self)

Expect expectation's method to be called once.

Alias for times(1).

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("land").once()
<flexmock._api.Expectation object at ...>
>>> plane.land()

one_by_one(self)

Modifies the return value to be treated as a list of return values.

Each value in the list is returned on successive invocations of the method.

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("pilot").and_return("pilot1", "pilot2").one_by_one()
<flexmock._api.Expectation object at ...>
>>> plane.pilot()
'pilot1'
>>> plane.pilot()
'pilot2'

ordered(self)

Makes the expectation respect the order of should_receive statements.

An exception will be raised if methods are called out of order, determined by order of should_receive calls in the test.

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("fly").with_args("east").ordered()
<flexmock._api.Expectation object at ...>
>>> flexmock(plane).should_receive("fly").with_args("west").ordered()
<flexmock._api.Expectation object at ...>
>>> plane.fly("west")
Traceback (most recent call last):
  ...
flexmock.exceptions.CallOrderError: fly("west") called before...

replace_with(self, function)

Gives a function to run instead of the mocked out one.

Parameters:

Name Type Description Default
function Callable[..., Any]

A callable that is used to replace the original function.

required

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("set_speed").replace_with(lambda x: x == 5)
<flexmock._api.Expectation object at ...>
>>> plane.set_speed(5)
True
>>> plane.set_speed(4)
False

times(self, number)

Number of times this expectation's method is expected to be called.

There are also 3 aliases for the times() method:

  • once() -> times(1)
  • twice() -> times(2)
  • never() -> times(0)

Parameters:

Name Type Description Default
number int

Expected call count.

required

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("fly").times(1)
<flexmock._api.Expectation object at ...>
>>> plane.fly()
>>> flexmock(plane).should_call("land").times(2)
<flexmock._api.Expectation object at ...>
>>> plane.land()
>>> plane.land()

twice(self)

Expect expectation's method to be called twice.

Alias for times(2).

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("fly").twice()
<flexmock._api.Expectation object at ...>
>>> plane.fly()
>>> plane.fly()

when(self, func)

Sets an outside resource to be checked when asserting if a method should be called.

Parameters:

Name Type Description Default
func Callable[..., Any]

Function that indicates if the mocked or spied method should have been called.

required

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

>>> flexmock(plane).should_receive("land").when(lambda: plane.is_flying)
<flexmock._api.Expectation object at ...>
>>> plane.is_flying
True
>>> plane.land()
>>> plane.is_flying = False
>>> plane.land()
Traceback (most recent call last):
  ...
flexmock.exceptions.StateError: land expected to be called when...

with_args(self, *args, **kwargs)

Override the arguments used to match this expectation's method.

Parameters:

Name Type Description Default
*args Any

Positional arguments.

()
**kwargs Any

Keyword arguments.

{}

Returns:

Type Description
Expectation

Self, i.e. can be chained with other Expectation methods.

Examples:

Match calls with no arguments:

>>> flexmock(plane).should_receive("fly").with_args()
<flexmock._api.Expectation object at ...>

Match a single argument:

>>> flexmock(plane).should_receive("fly").with_args("east")
<flexmock._api.Expectation object at ...>

Match keyword arguments:

>>> flexmock(plane).should_receive("fly").with_args("up", destination="Oslo")
<flexmock._api.Expectation object at ...>

Match argument type:

>>> flexmock(plane).should_receive("fly").with_args(str)
<flexmock._api.Expectation object at ...>

Match a string using a compiled regular expression:

>>> regex = re.compile("^(up|down)$")
>>> flexmock(plane).should_receive("fly").with_args(regex)
<flexmock._api.Expectation object at ...>