make_mock_class

classmethod Mocker.make_mock_class(name='Mocker', instance=True, simple=False, attributes: dict = None, modules: dict = None, **kwargs) → Union[Any, privex.helpers.collections.Mocker, Type[privex.helpers.collections.Mocker]][source]

Return a customized mock class or create an instance which appears to be named name

Allows code which might check x.__class__.__name__ to believe it’s the correct object.

Using the kwarg module you can change the module that the class / instance appears to have been imported from, allowing for quite deceiving fake classes and instances.

Example usage:

>>> redis = Mocker.make_mock_class('Redis', module='redis')
>>> # As seen below, the class appears to be called Redis, and even claims to be from the module `redis`
>>> redis
<redis.Redis object at 0x7fd7402ea4a8>
>>> print(f'Module: {redis.__module__} - Class Name: {redis.__class__.__name__}')
Module: redis - Class Name: Redis

Creating methods/attributes dynamically

You can set arbitrary attributes to point at a function, or just set them to a lambda:

>>> redis.exists = lambda key: 1
>>> redis.exists('hello')
1
>>> redis.hello()  # Non-existent attributes just act as a function that eats any args and returns None
None
Parameters
  • name – The name to write onto the mock class’s __name__ (and __qualname__ if not specified)

  • instance (bool) – If True then the disguised mock class will be returned as an instance. Otherwise the raw class itself will be returned for you to instantiate yourself.

  • simple (bool) – When True, generates a very basic, new class - not based on Mocker, which contains the attributes/methods defined in the param attributes.

  • kwargs – All kwargs (other than qualname) are forwarded to __init__ of the disguised class if instance is True.

  • attributes (dict) – If simple is True, then this dictionary of attributes is used to generate the class’s attributes, methods, and/or constructor. If simple is False, and instance is True, these attributes are passed to the constructor of the Mocker clone that was generated.

  • modules (dict) – If simple is False, and instance is True, this dict of modules are passed to the constructor of the Mocker clone that was generated.

Key str qualname

Optionally specify the “qualified name” to insert into __qualname__. If this isn’t specified, then name is used for qualname, which is fine for most cases anyway.

Key str module

Optionally override the module namespace that the class is supposedly from. If not specified, then the class will just inherit this module (privex.helpers.common)

Returns