python-dependency-injector/examples/providers/factory_init_injections_and_contexts.py

74 lines
2.0 KiB
Python
Raw Normal View History

2015-09-03 00:24:20 +03:00
"""`di.Factory` providers with init injections priority example."""
2015-06-05 12:28:12 +03:00
2015-09-03 00:24:20 +03:00
import dependency_injector as di
2015-06-05 12:28:12 +03:00
class User(object):
"""Example class User.
Class User has to be provided with user id.
Also Class User has dependencies on class Photo and class CreditCard
objects.
All of the dependencies have to be provided like __init__ arguments.
"""
def __init__(self, id, main_photo, credit_card):
2015-07-25 00:14:45 +03:00
"""Initializer."""
2015-06-05 12:28:12 +03:00
self.id = id
self.main_photo = main_photo
self.credit_card = credit_card
super(User, self).__init__()
class Photo(object):
"""Example class Photo."""
class CreditCard(object):
"""Example class CreditCard."""
# User, Photo and CreditCard factories:
2015-09-03 00:24:20 +03:00
credit_cards_factory = di.Factory(CreditCard)
photos_factory = di.Factory(Photo)
users_factory = di.Factory(User,
main_photo=photos_factory,
credit_card=credit_cards_factory)
2015-06-05 12:28:12 +03:00
# Creating several User objects:
2015-07-20 18:46:45 +03:00
user1 = users_factory(1)
# Same as: user1 = User(1,
# main_photo=Photo(),
# credit_card=CreditCard())
user2 = users_factory(2)
# Same as: user2 = User(2,
# main_photo=Photo(),
# credit_card=CreditCard())
2015-06-05 12:28:12 +03:00
# Making some asserts:
assert user1.id == 1
assert isinstance(user1.main_photo, Photo)
assert isinstance(user1.credit_card, CreditCard)
assert user2.id == 2
assert isinstance(user2.main_photo, Photo)
assert isinstance(user2.credit_card, CreditCard)
assert user1.main_photo is not user2.main_photo
assert user1.credit_card is not user2.credit_card
2015-09-03 00:24:20 +03:00
# Context keyword arguments have priority on keyword argument injections:
2015-06-05 12:28:12 +03:00
main_photo_mock = Photo()
credit_card_mock = CreditCard()
user3 = users_factory(3, main_photo=main_photo_mock,
credit_card=credit_card_mock)
assert user3.id == 3
assert user3.main_photo is main_photo_mock
assert user3.credit_card is credit_card_mock