mock_alchemy.utils

A module for utils for the mock-alchemy library.

mock_alchemy.utils.build_identity_map(items)[source]

Builds identity map.

Utility for building identity map from given SQLAlchemy models.

Parameters

items (Sequence[Any]) – A sequence of SQLAlchemy objects.

Return type

Dict

Returns

An identity map of the given SQLAlchemy objects.

For example:

>>> from sqlalchemy import Column, Integer, String
>>> from sqlalchemy.ext.declarative import declarative_base

>>> Base = declarative_base()

>>> class SomeClass(Base):
...     __tablename__ = 'some_table'
...     pk1 = Column(Integer, primary_key=True)
...     pk2 = Column(Integer, primary_key=True)
...     name =  Column(String(50))
...     def __repr__(self):
...         return str(self.pk1)

>>> build_identity_map([SomeClass(pk1=1, pk2=2)])
{(1, 2): 1}
mock_alchemy.utils.copy_and_update(target, updater)[source]

Copy and update dictionary.

Copy dictionary and update it all in one operation.

Parameters
  • target (Dict) – The dictionary to copy and update.

  • updater (Dict) – The updating dictionary.

Returns

A new dictionary of the target copied and updated by updater.

Return type

Dict

For example:

>>> a = {'foo': 'bar'}
>>> b = copy_and_update(a, {1: 2})
>>> a is b
False
>>> b == {'foo': 'bar', 1: 2}
True
mock_alchemy.utils.get_item_attr(idmap, access)[source]

Access dictionary in different methods.

Utility for accessing dict by different key types (for get).

Parameters
  • idmap (Dict) – A dictionary of identity map of SQLAlchemy objects.

  • access (Union[Dict, Tuple, Any]) – The access pattern which should either be basic data type, dictionary, or a tuple. If it is dictionary it should map to the names of the primary keys of the SQLAlchemy objects. If it is a tuple, it should be a set of keys to search for. If it is not a dict or a tuple, then the objects in question must have only one primary key of the type passed (such as a string, integer, etc.).

Return type

Any

Returns

An SQlAlchemy object that was requested.

For example::
>>> idmap = {(1,): 2}
>>> get_item_attr(idmap, 1)
2
>>> idmap = {(1,): 2}
>>> get_item_attr(idmap, {"pk": 1})
2
>>> get_item_attr(idmap, (1,))
2
mock_alchemy.utils.indexof(needle, haystack)[source]

Gets the index of some item in a sequence.

Find an index of needle in haystack by looking for exact same item by pointer ids vs usual list.index() which finds by object comparison.

Parameters
  • needle (Any) – The object or item to find in the sequence.

  • haystack (Sequence[Any]) – The sequence of items to search for the needle.

Return type

int

Returns

The index of the needle in the haystack.

Raises

ValueError – If the needle is not found inside the haystack.

For example:

>>> a = {}
>>> b = {}
>>> haystack = [1, a, 2, b]
>>> indexof(b, haystack)
3
>>> indexof(None, haystack)
Traceback (most recent call last):
...
ValueError: None is not in [1, {}, 2, {}]
mock_alchemy.utils.match_type(s, t)[source]

Match the string type.

Matches the string type with the provided type and returns the string of the desired type.

Parameters
  • s (Union[bytes, str]) – The string to match the type with.

  • t (Union[Type[bytes], Type[str]]) – The type to make the string with.

Return type

Union[bytes, str]

Returns

An object of the desired type of type t.

For example:

>>> assert type(match_type(b'hello', bytes)) is bytes
>>> assert type(match_type(u'hello', str)) is str
>>> assert type(match_type(b'hello', str)) is str
>>> assert type(match_type(u'hello', bytes)) is bytes
mock_alchemy.utils.raiser(exp, *args, **kwargs)[source]

Raises an exception with the given args.

Utility for raising exceptions Useful in one-liners.

Parameters
  • exp (Type[Exception]) – The exception to raise.

  • args (Any) – The args to use for the exception.

  • kwargs (Any) – The kwargs to use for the exception.

Raises

exp – The parameterized exception of the specified kind.

For example:

>>> a = lambda x: not x and raiser(ValueError, 'error message')
>>> _ = a(True)
>>> _ = a(False)
Traceback (most recent call last):
...
ValueError: error message
Return type

Type[Exception]

mock_alchemy.utils.setattr_tmp(obj, name, value)[source]

Set the atrributes of object temporarily.

Utility for temporarily setting value in an object.

Parameters
  • obj (object) – An object to set the attribute of.

  • name (str) – The name of the attribute.

  • value (Any) – The value to set the attribute to.

Return type

Any

Returns

A context manager that can be used.

Yields

Used for the context manager so that this function can be used as with setattr_tmp.

For example:

>>> class Foo(object):
...     foo = 'foo'
>>> print(Foo.foo)
foo
>>> with setattr_tmp(Foo, 'foo', 'bar'):
...     print(Foo.foo)
bar
>>> print(Foo.foo)
foo

>>> Foo.foo = None
>>> with setattr_tmp(Foo, 'foo', 'bar'):
...     print(Foo.foo)
None