2015-04-14 23:17:53 +03:00
|
|
|
Providers
|
|
|
|
=========
|
|
|
|
|
|
|
|
|
|
|
|
Providers delegation
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
Overriding of providers
|
|
|
|
-----------------------
|
|
|
|
|
|
|
|
Any provider can be overridden by another provider.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
2015-04-23 13:15:10 +03:00
|
|
|
"""Providers overriding example."""
|
2015-04-14 23:17:53 +03:00
|
|
|
|
|
|
|
import sqlite3
|
|
|
|
|
2015-05-14 11:59:47 +03:00
|
|
|
from objects.providers import Factory
|
2015-04-14 23:17:53 +03:00
|
|
|
from objects.providers import Singleton
|
|
|
|
|
|
|
|
from objects.injections import KwArg
|
|
|
|
from objects.injections import Attribute
|
|
|
|
|
|
|
|
|
|
|
|
class ObjectA(object):
|
|
|
|
|
|
|
|
"""ObjectA has dependency on database."""
|
|
|
|
|
|
|
|
def __init__(self, database):
|
|
|
|
"""Initializer.
|
|
|
|
|
|
|
|
Database dependency need to be injected via init arg."""
|
|
|
|
self.database = database
|
|
|
|
|
|
|
|
def get_one(self):
|
|
|
|
"""Select one from database and return it."""
|
|
|
|
return self.database.execute('SELECT 1')
|
|
|
|
|
|
|
|
|
|
|
|
class ObjectAMock(ObjectA):
|
|
|
|
|
|
|
|
"""Mock of ObjectA.
|
|
|
|
|
|
|
|
Has no dependency on database.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
"""Initializer."""
|
|
|
|
|
|
|
|
def get_one(self):
|
|
|
|
"""Select one from database and return it.
|
|
|
|
|
|
|
|
Mock makes no database queries and always returns two instead of one.
|
|
|
|
"""
|
|
|
|
return 2
|
|
|
|
|
|
|
|
|
|
|
|
# Database and `ObjectA` providers.
|
|
|
|
database = Singleton(sqlite3.Connection,
|
|
|
|
KwArg('database', ':memory:'),
|
|
|
|
KwArg('timeout', 30),
|
|
|
|
KwArg('detect_types', True),
|
|
|
|
KwArg('isolation_level', 'EXCLUSIVE'),
|
|
|
|
Attribute('row_factory', sqlite3.Row))
|
|
|
|
|
2015-05-14 11:59:47 +03:00
|
|
|
object_a_factory = Factory(ObjectA,
|
|
|
|
KwArg('database', database))
|
2015-04-14 23:17:53 +03:00
|
|
|
|
|
|
|
|
|
|
|
# Overriding `ObjectA` provider with `ObjectAMock` provider.
|
2015-05-14 11:59:47 +03:00
|
|
|
object_a_factory.override(Factory(ObjectAMock))
|
2015-04-14 23:17:53 +03:00
|
|
|
|
|
|
|
# Creating several `ObjectA` instances.
|
2015-05-14 11:59:47 +03:00
|
|
|
object_a_1 = object_a_factory()
|
|
|
|
object_a_2 = object_a_factory()
|
2015-04-14 23:17:53 +03:00
|
|
|
|
|
|
|
# Making some asserts.
|
|
|
|
assert object_a_1 is not object_a_2
|
|
|
|
assert object_a_1.get_one() == object_a_2.get_one() == 2
|
2015-05-14 11:59:47 +03:00
|
|
|
|