mocker_builder package

Submodules

mocker_builder module

class mocker_builder.mocker_builder.MockerBuilder[source]

Bases: ABC

Our interface to connect mock metadata builder to the user’s building tests

add_fixture(content: TFixtureContentType) TFixtureContentType[source]

Method to simulate a pytest fixture to be called in every test but in another way.

Args:
content (TFixtureContentType):

Method to be called and returned or yielded

Returns:
TFixtureContentType:

The return/yield data from content.

initializer()[source]
abstract mocker_builder_setup()[source]

Method to setup your tests initializing mocker builder features.

patch(target: TargetType, method: Optional[AttrType] = None, attribute: Optional[AttrType] = None, new: TypeNew = sentinel.DEFAULT, spec: Optional[bool] = None, create: bool = False, spec_set: Optional[bool] = None, autospec: Optional[Union[bool, Callable]] = None, new_callable: Optional[NewCallableType] = None, return_value: Optional[ReturnValueType] = None, side_effect: Optional[SideEffectType] = None, mock_configure: Optional[MockMetadataKwargsType] = None, **kwargs) _TPatch[_TMockType][source]

From here we create new mock.patch parsing the target parameter. You can just set your target as normal imported class, module or method. You don’t need to pass it as string like normal mock.patch does. Here we make it easier by just allowing to set the target parameter for classes, modules and methods or functions without the need of setting the method parameter. Just if you wanna mock an attribute you must set it from the attribute parameter as string. The target can be am imported class or module but the attribute need to be passed as string.

Test Cases
    from testing_heroes.my_heroes
    import JusticeLeague

    class TestMyHeroes(MockerBuilder):

        @MockerBuilder.initializer
        def mocker_builder_setup(self):
                self.mock_justice_league__init__ = self.patch(
                    target=JusticeLeague.__init__
                )

        @pytest.mark.asyncio
        async def test_heroes_sleeping(self):
            justce_league = JusticeLeague()
            assert self.mock_justice_league__init__().called

            async def hero_names():
                yield Batman().nickname
                yield Robin().nickname

            _hero_names = hero_names()

            async for result in justce_league.are_heroes_sleeping():
                assert result == "=== Heroes are awakened ==="

            self.mock_justice_league__init__.stop()

            justce_league = JusticeLeague()

            async for result in justce_league.are_heroes_sleeping():
                _hero_name = await _hero_names.__anext__()
                assert result == f"MagicMock=>({_hero_name}): ZZzzzz"
Types
     TargetType = TypeVar('TargetType', Callable, ModuleType, str)

     AttrType = TypeVar('AttrType', bound=Union[Callable, str])

     TypeNew = TypeVar('TypeNew', bound=Any)

     NewCallableType = TypeVar('NewCallableType', bound=Optional[Callable])

     ReturnValueType = TypeVar('ReturnValueType', bound=Optional[Any])

     SideEffectType = TypeVar('SideEffectType', bound=Optional[Union[Callable, List]])

Note

This doc is defined in unittest.patch doc. For a complete documentation please see: https://docs.python.org/3/library/unittest.mock.html#the-patchers

Args:
target (TargetType):

The target to be mocked.

method (AttrType[str], optional):

Method to be mocked, useful when need to create an method or dynamically invoking.

attribute (AttrType[str], optional):

Attribute to be mocked. Defaults to None.

new (TypeNew, optional):

The new type that target attribute will get after mocking. Defaults to DEFAULT.

spec (bool, optional):

This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

If spec is an object (rather than a list of strings) then mock.__class__ returns the class of the spec object. This allows mocks to pass isinstance tests.

create (bool, optional):

By default patch() will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!.

spec_set (bool, optional):

A stricter variant of spec. If used, attempting to set or get an attribute on the mock that isn’t on the object passed as spec_set will raise an AttributeError.

autospec (Union[bool, Callable], optional):

A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the create_autospec() function and Autospeccing.

Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.

new_callable (NewCallableType, optional):

Allows you to specify a different class, or callable object, that will be called to create the new object. By default AsyncMock is used for async functions and MagicMock for the rest.

return_value (ReturnValueType, optional):

The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

side_effect (SideEffectType, optional):

A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT, the return value of this function is used as the return value.

If side_effect is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned.

mock_configure (MockMetadataKwargsType, optional):

Set attributes on the mock through keyword arguments. It exists to make it easier to do configuration after the mock has been created.

Attributes plus return values and side effects can be set on child mocks using standard dot notation:

mock_who_is_my_hero = self.patch(
    target=Batman,
    mock_configure={
        'return_value.nickname': 'Bat Mock',
        'return_value.eating_banana.return_value': "doesn't like banana",
        'return_value.wearing_pyjama.return_value': "doesn't wear pyjama",
        'return_value.just_call_for.return_value': "Just calls for Mocker",
        'return_value.just_says.return_value': "I'm gonna mock you babe!",
    }
)
Returns:
TMocker.PatchType:

Alias to _TPatch Generics which handle with MagicMock or AsyncMock (not yet really but working on) according patching async methods or not.

exception mocker_builder.mocker_builder.MockerBuilderException(*args: object)[source]

Bases: Exception

Raised Exception in MockerBuilder usage or invocation

class mocker_builder.mocker_builder.MockerBuilderWarning[source]

Bases: object

Base class for all warnings emitted by mocker-builder

static warn(message: str)[source]
class mocker_builder.mocker_builder.Patcher[source]

Bases: object

Patch wrapper for the mocker.patch feature.

Args:
_mocker (MockFixture):

mocker fixture keeper.

_mocked_metadata (List[TMockMetadata]):

Instances of patched mocks.

static dispatch(mock_metadata: TMockMetadata) _TPatch[_TMockType][source]

Our mock patch to properly identify and setting mock properties. We start the mock so we can manage state when stopping or restarting mocks and setting results (changing return_value or side_effect patch properties).

Args:
mock_metadata (TMockMetadata):

Mock metadata instance with mock’s data.

Returns:
TMocker.PatchType:

Our Mock Patch Type wrapper.

static mock_configure(mock_metadata: TMockMetadata) _TPatch[_TMockType][source]
class mocker_builder.mocker_builder.TMockMetadata(target_path: ~typing.Optional[str] = None, is_async: bool = False, patch_kwargs: ~mocker_builder.mocker_builder.MockMetadataKwargsType = <factory>, _patch: ~typing.Optional[~mocker_builder.mocker_builder._Patch] = None, _mock: ~typing.Optional[~mocker_builder.mocker_builder._TMockType] = None, is_active: bool = False)[source]

Bases: object

Mock metadata structure to keep state of created mock and patcher for easily reset mock return value and so on.

Args:
target_path (str):

Keep converted mock patch target and attribute users enter as class method or attribute or even module methods or attributes so we can just patch them.

is_async: (bool):

Identify if method to be mocked is async or not.

patch_kwargs: (MockMetadataKwargsType):

Here we just dispatch kwargs mock parameters such as return_value, side_effect, spec, new_callable, mock_configure and so on.

_patch: (_Patch):

Mocker _patch wrapper to the mock.patch features.

_mock: (_TMockType):

Mock instance keeper.

is_active: (bool):

Flag to sinalize that mock is active. When set to False mock will be cleaned up after tested function finished.

property autospec: TypeAutoSpec
property create: bool
is_active: bool = False
is_async: bool = False
property mock_configure: MockMetadataKwargsType
property new: TypeNew
property new_callable: NewCallableType
patch_kwargs: MockMetadataKwargsType
property return_value: ReturnValueType
property side_effect: SideEffectType
property spec: TypeSpec
target_path: str = None
class mocker_builder.mocker_builder.TMockMetadataBuilder(_mock_metadata: ~typing.Optional[~mocker_builder.mocker_builder.TMockMetadata] = None, _mock_keys_validate: ~typing.List[str] = <factory>, _bypass_methods: ~typing.List[str] = <factory>)[source]

Bases: object

Here we build our mock metada to parse mock parameters and propagate state.

Args:
_mock_metadata (TMockMetadata):

Mock metadata instance to propagate mock state.

_mock_keys_validate (List[str]):

Mock parameters we need to check if were setted to dispatch to mock.patch creation.

_bypass_methods (List[str]):

Methods we need keeping properly behavior for return value.

Raises:
MockerBuilderException:

Notify users when we found in trouble.

class mocker_builder.mocker_builder.TMocker[source]

Bases: object

Our API to handle patch and mock features

PatchType

alias of _TPatch[_TMockType]

Module contents

class mocker_builder.MockerBuilder[source]

Bases: ABC

Our interface to connect mock metadata builder to the user’s building tests

add_fixture(content: TFixtureContentType) TFixtureContentType[source]

Method to simulate a pytest fixture to be called in every test but in another way.

Args:
content (TFixtureContentType):

Method to be called and returned or yielded

Returns:
TFixtureContentType:

The return/yield data from content.

initializer()[source]
abstract mocker_builder_setup()[source]

Method to setup your tests initializing mocker builder features.

patch(target: TargetType, method: Optional[AttrType] = None, attribute: Optional[AttrType] = None, new: TypeNew = sentinel.DEFAULT, spec: Optional[bool] = None, create: bool = False, spec_set: Optional[bool] = None, autospec: Optional[Union[bool, Callable]] = None, new_callable: Optional[NewCallableType] = None, return_value: Optional[ReturnValueType] = None, side_effect: Optional[SideEffectType] = None, mock_configure: Optional[MockMetadataKwargsType] = None, **kwargs) _TPatch[_TMockType][source]

From here we create new mock.patch parsing the target parameter. You can just set your target as normal imported class, module or method. You don’t need to pass it as string like normal mock.patch does. Here we make it easier by just allowing to set the target parameter for classes, modules and methods or functions without the need of setting the method parameter. Just if you wanna mock an attribute you must set it from the attribute parameter as string. The target can be am imported class or module but the attribute need to be passed as string.

Test Cases
    from testing_heroes.my_heroes
    import JusticeLeague

    class TestMyHeroes(MockerBuilder):

        @MockerBuilder.initializer
        def mocker_builder_setup(self):
                self.mock_justice_league__init__ = self.patch(
                    target=JusticeLeague.__init__
                )

        @pytest.mark.asyncio
        async def test_heroes_sleeping(self):
            justce_league = JusticeLeague()
            assert self.mock_justice_league__init__().called

            async def hero_names():
                yield Batman().nickname
                yield Robin().nickname

            _hero_names = hero_names()

            async for result in justce_league.are_heroes_sleeping():
                assert result == "=== Heroes are awakened ==="

            self.mock_justice_league__init__.stop()

            justce_league = JusticeLeague()

            async for result in justce_league.are_heroes_sleeping():
                _hero_name = await _hero_names.__anext__()
                assert result == f"MagicMock=>({_hero_name}): ZZzzzz"
Types
     TargetType = TypeVar('TargetType', Callable, ModuleType, str)

     AttrType = TypeVar('AttrType', bound=Union[Callable, str])

     TypeNew = TypeVar('TypeNew', bound=Any)

     NewCallableType = TypeVar('NewCallableType', bound=Optional[Callable])

     ReturnValueType = TypeVar('ReturnValueType', bound=Optional[Any])

     SideEffectType = TypeVar('SideEffectType', bound=Optional[Union[Callable, List]])

Note

This doc is defined in unittest.patch doc. For a complete documentation please see: https://docs.python.org/3/library/unittest.mock.html#the-patchers

Args:
target (TargetType):

The target to be mocked.

method (AttrType[str], optional):

Method to be mocked, useful when need to create an method or dynamically invoking.

attribute (AttrType[str], optional):

Attribute to be mocked. Defaults to None.

new (TypeNew, optional):

The new type that target attribute will get after mocking. Defaults to DEFAULT.

spec (bool, optional):

This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

If spec is an object (rather than a list of strings) then mock.__class__ returns the class of the spec object. This allows mocks to pass isinstance tests.

create (bool, optional):

By default patch() will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!.

spec_set (bool, optional):

A stricter variant of spec. If used, attempting to set or get an attribute on the mock that isn’t on the object passed as spec_set will raise an AttributeError.

autospec (Union[bool, Callable], optional):

A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the create_autospec() function and Autospeccing.

Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.

new_callable (NewCallableType, optional):

Allows you to specify a different class, or callable object, that will be called to create the new object. By default AsyncMock is used for async functions and MagicMock for the rest.

return_value (ReturnValueType, optional):

The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

side_effect (SideEffectType, optional):

A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT, the return value of this function is used as the return value.

If side_effect is an iterable then each call to the mock will return the next value from the iterable. If any of the members of the iterable are exceptions they will be raised instead of returned.

mock_configure (MockMetadataKwargsType, optional):

Set attributes on the mock through keyword arguments. It exists to make it easier to do configuration after the mock has been created.

Attributes plus return values and side effects can be set on child mocks using standard dot notation:

mock_who_is_my_hero = self.patch(
    target=Batman,
    mock_configure={
        'return_value.nickname': 'Bat Mock',
        'return_value.eating_banana.return_value': "doesn't like banana",
        'return_value.wearing_pyjama.return_value': "doesn't wear pyjama",
        'return_value.just_call_for.return_value': "Just calls for Mocker",
        'return_value.just_says.return_value': "I'm gonna mock you babe!",
    }
)
Returns:
TMocker.PatchType:

Alias to _TPatch Generics which handle with MagicMock or AsyncMock (not yet really but working on) according patching async methods or not.