Skip to content

Advanced usage

Non-existent attributes

You can also mock attributes that don't exist. By default, Chainmock will raise an AttributeError if you try to mock a non-existent attribute:

mocker(Teapot).mock("new_method")
|
Traceback (most recent call last):
  ...
AttributeError: type object 'Teapot' has no attribute 'new_method'

Allow creation of the new method explicitly with the create=True parameter:

mocker(Teapot).mock("new_method", create=True).return_value("mocked")
assert Teapot().new_method() == "mocked"

Mocking builtins

Chainmock allows you to mock built-in functions and classes, such as open. You can mock built-in functions and classes directly, just like any other attribute:

import builtins
mock_file = mocker()
mock_file.mock("read").return_value("mocked1").called_once()
mocker(builtins).mock("open").return_value(mock_file)
assert open("foo", encoding="utf8").read() == "mocked1"

Chained method calls

You can mock chained method access by using dot notation:

from pathlib import Path
# Mock a chain of path operations
mocker(Path).mock("home.joinpath.resolve").return_value("/mocked/home/path")
assert Path.home().joinpath("test").resolve() == "/mocked/home/path"

Note

For more information, please see also API reference. It contains more examples and extensive documentation about every method and function available in Chainmock.