2015-04-23 13:15:10 +03:00
|
|
|
"""External dependency providers example."""
|
2015-03-10 01:43:23 +03:00
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
import sqlite3
|
2015-03-10 01:43:23 +03:00
|
|
|
|
2015-02-23 11:47:38 +03:00
|
|
|
from objects.providers import Singleton
|
2015-05-14 11:38:56 +03:00
|
|
|
from objects.providers import Factory
|
2015-02-23 11:47:38 +03:00
|
|
|
from objects.providers import ExternalDependency
|
2015-03-10 01:43:23 +03:00
|
|
|
|
2015-03-23 02:04:18 +03:00
|
|
|
from objects.injections import KwArg
|
2015-02-23 11:47:38 +03:00
|
|
|
from objects.injections import Attribute
|
2015-01-28 01:26:38 +03:00
|
|
|
|
2015-01-23 02:42:59 +03:00
|
|
|
|
|
|
|
class ObjectA(object):
|
2015-03-10 01:43:23 +03:00
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
"""ObjectA has dependency on database."""
|
2015-01-23 02:42:59 +03:00
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
def __init__(self, database):
|
|
|
|
"""Initializer.
|
2015-03-10 01:43:23 +03:00
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
Database dependency need to be injected via init arg."""
|
|
|
|
self.database = database
|
2015-01-23 02:42:59 +03:00
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
def get_one(self):
|
|
|
|
"""Select one from database and return it."""
|
|
|
|
return self.database.execute('SELECT 1').fetchone()[0]
|
2015-01-23 02:42:59 +03:00
|
|
|
|
|
|
|
|
2015-04-24 11:59:10 +03:00
|
|
|
# Database and `ObjectA` providers.
|
|
|
|
database = ExternalDependency(instance_of=sqlite3.Connection)
|
2015-01-23 02:42:59 +03:00
|
|
|
|
2015-05-14 11:38:56 +03:00
|
|
|
object_a_factory = Factory(ObjectA,
|
|
|
|
KwArg('database', database))
|
2015-01-23 02:42:59 +03:00
|
|
|
|
|
|
|
# Satisfaction of external dependency.
|
2015-04-24 11:59:10 +03:00
|
|
|
database.override(Singleton(sqlite3.Connection,
|
|
|
|
KwArg('database', ':memory:'),
|
|
|
|
KwArg('timeout', 30),
|
|
|
|
KwArg('detect_types', True),
|
|
|
|
KwArg('isolation_level', 'EXCLUSIVE'),
|
|
|
|
Attribute('row_factory', sqlite3.Row)))
|
|
|
|
|
|
|
|
# Creating several `ObjectA` instances.
|
2015-05-14 11:38:56 +03:00
|
|
|
object_a_1 = object_a_factory()
|
|
|
|
object_a_2 = object_a_factory()
|
2015-04-24 11:59:10 +03:00
|
|
|
|
|
|
|
# Making some asserts.
|
|
|
|
assert object_a_1 is not object_a_2
|
|
|
|
assert object_a_1.database is object_a_2.database is database()
|