def test_repr(self): provider = providers.DelegatedFactory(Example) self.assertEqual( repr(provider), '<dependency_injector.providers.' 'DelegatedFactory({0}) at {1}>'.format(repr(Example), hex(id(provider))))
class Cont(containers.DeclarativeContainer): config = providers.Configuration('config') loggerFactory = providers.DelegatedFactory(logging.getLogger) apiGatewayFactory = providers.DelegatedFactory(APIGateway, loggerFactory) thingRepository = providers.Singleton(ThingRepository, loggerFactory) thingLogic = providers.Singleton(ThingLogic, loggerFactory, thingRepository) thingAuthorizer = providers.Singleton(ThingAuthorizer, loggerFactory, thingLogic) thingLambdaMapper = providers.Singleton(ThingLambdaMapper, loggerFactory, apiGatewayFactory, thingAuthorizer) def shutdown(): pass
def create_basic_log_adapter(providers, name, extra=None): log_message_factory_provider = providers.DelegatedFactory(Message) logger = providers.Singleton(logging.getLogger, name=name) return providers.Singleton( BasicLogAdapter, logger, log_message_factory=log_message_factory_provider, extra=extra)
class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" movie_model = providers.DelegatedFactory(movies.models.Movie) movie_finder = providers.Factory(movies.finders.MovieFinder, movie_model=movie_model) movie_lister = providers.Factory(movies.listers.MovieLister, movie_finder=movie_finder)
class QueryBusContainer(containers.DeclarativeContainer): items_repository = providers.Singleton(AuctionItemsRepository) query_handler_factory = providers.FactoryAggregate( GetItemsQuery=providers.Factory(GetItemsQueryHandler, items_repository=items_repository)) query_bus_factory = providers.Factory( QueryBus, query_handler_factory=providers.DelegatedFactory( query_handler_factory))
class CommandBusContainer(containers.DeclarativeContainer): items_repository = providers.Singleton(AuctionItemsRepository) command_handler_factory = providers.FactoryAggregate( AddItemCommand=providers.Factory(AddItemCommandHandler, items_repository=items_repository)) command_bus_factory = providers.Factory( CommandBus, command_handler_factory=providers.DelegatedFactory( command_handler_factory))
class OverriddenQueryBusContainer(QueryBusContainer): items_repository = providers.Singleton(MockAuctionItemsRepository) query_handler_factory = providers.FactoryAggregate( GetItemsQuery=providers.Factory(GetItemsQueryHandler, items_repository=items_repository)) query_bus_factory = providers.Factory( QueryBus, query_handler_factory=providers.DelegatedFactory( query_handler_factory))
def test_is_delegated_provider(): assert providers.is_delegated(providers.DelegatedFactory(object)) is True
class Container(containers.DeclarativeContainer): obj_factory = providers.DelegatedFactory(dict, foo=providers.Resource(dict, foo="bar"), bar=providers.Resource(dict, foo="bar"))
class MessageBusIocContainer(containers.DeclarativeContainer): MEMORY_CHANNEL_TOPIC_CONFIG_KEY = "memory_channel_topic" MEMORY_CHANNEL_MAX_BUFFER_SIZE = 5 common_ioc = providers.DependenciesContainer() # Configuration config = providers.Configuration('config') logging_provider = IocUtil.create_basic_log_adapter( providers, "bbpyp.message_bus", extra={"CONTEXT_ID": None}) # Internal Providers message_bus_factory_provider = providers.Factory( lambda: MessageBusIocContainer.instance.message_bus_factory.delegate) memory_channel_topic_default_provider = providers.Factory( config.memory_channel_topic_default) memory_channel_max_buffer_size_provider = providers.Factory( config.memory_channel_max_buffer_size) # Delegates for consumer's of this package message_factory_provider = providers.DelegatedFactory( Message, logger=logging_provider, sequence_service=common_ioc.sequence_service_provider) topic_channel_delegated_factory = providers.DelegatedFactory( TopicChannel, logger=logging_provider, channel_topic_config=config.memory_channel_topic, channel_topic_config_default=memory_channel_topic_default_provider, channel_max_buffer_size=memory_channel_max_buffer_size_provider, async_service=common_ioc.async_service_provider, context_service=common_ioc.context_service_provider) message_bus_factory = providers.DelegatedFactory( Bus, logger=logging_provider, bus_factory=message_bus_factory_provider, single_link_node_factory=common_ioc.single_link_node_delegated_factory. provider, topic_channel_factory=topic_channel_delegated_factory, async_service=common_ioc.async_service_provider, context_service=common_ioc.context_service_provider) message_pipe_delegated_factory = providers.DelegatedFactory(MessagePipe) message_pipe_line_builder_provider = providers.Factory( MessagePipeLineBuilder, message_pipe_factory=message_pipe_delegated_factory, linked_list=common_ioc.singly_linked_list_factory) pub_sub_provider = providers.Singleton( PubSub, logger=logging_provider, linked_list=common_ioc.singly_linked_list_factory, bus_factory=message_bus_factory, async_service=common_ioc.async_service_provider, context_service=common_ioc.context_service_provider) build = providers.Callable(bootstrap_container, config=config, common_ioc=common_ioc, logger=logging_provider)
class VertexFactories(containers.DeclarativeContainer): regular = providers.DelegatedFactory(Vertex)
def test_is_provider(self): """Test is_provider.""" self.assertTrue(utils.is_provider(providers.DelegatedFactory(object)))
# Test 4: to check the .args, .kwargs, .attributes attributes provider4 = providers.Factory(Animal) args4: Tuple[Any] = provider4.args kwargs4: Dict[str, Any] = provider4.kwargs attributes4: Dict[str, Any] = provider4.attributes # Test 5: to check the provided instance interface provider5 = providers.Factory(Animal) provided5: providers.ProvidedInstance = provider5.provided attr_getter5: providers.AttributeGetter = provider5.provided.attr item_getter5: providers.ItemGetter = provider5.provided["item"] method_caller5: providers.MethodCaller = provider5.provided.method.call( 123, arg=324) # Test 6: to check the DelegatedFactory provider6 = providers.DelegatedFactory(Cat) animal6: Animal = provider6(1, 2, 3, b="1", c=2, e=0.0) # Test 7: to check the AbstractFactory provider7 = providers.AbstractFactory(Animal) provider7.override(providers.Factory(Cat)) animal7: Animal = provider7(1, 2, 3, b="1", c=2, e=0.0) # Test 8: to check the FactoryDelegate __init__ provider8 = providers.FactoryDelegate(providers.Factory(object)) # Test 9: to check FactoryAggregate provider provider9: providers.FactoryAggregate[str] = providers.FactoryAggregate( a=providers.Factory(str, "str1"), b=providers.Factory(str, "str2"), )
def test_inheritance(self): self.assertIsInstance(providers.DelegatedFactory(object), providers.Factory)
def __init__(self, config, main, common_ioc_factory, message_bus_ioc_factory, combinator_ioc_factory, lexicomb_ioc_factory, state_machine_ioc_factory, lexical_state_machine_ioc_factory, interpreter_state_machine_ioc_factory): self.__instance = containers.DynamicContainer() logging_provider = IocUtil.create_basic_log_adapter(providers, "bbpyp.lexicomb_engine") common_ioc = common_ioc_factory(config=config, source_format_rules={ ":=": {"format": [(r"\s*{}\s*", r"{} ")]}, "+": {"format": [(r"\s*{}\s*", r" {} ")]}, "-": {"format": [(r"\s*{}\s*", r" {} ")]}, "*": {"format": [(r"\s*{}\s*", r" {} ")]}, "/": {"format": [(r"\s*{}\s*", r" {} ")]}, ";": {"format": [(r"\s*{}\s*", r"{}" + linesep)]}, "{": {"format": [(r"\s*{}\s*", r"{}" + linesep)], "indent_delta": IndentDelta.INCREASE}, "}": {"format": [(rf"\s*{linesep}{{{{1}}}}(\s*){{}}\s*", linesep + r"\1{}" + linesep)], "indent_delta": IndentDelta.DECREASE}, "return": {"format": [(rf"\s*{linesep}{{{{1}}}}(\s*){{}}\s*", linesep + r"\1{} ")]} }).build() message_bus_ioc = message_bus_ioc_factory( config=config, common_ioc=common_ioc).build() combinator_ioc = combinator_ioc_factory( common_ioc=common_ioc).build() lexicomb_ioc = lexicomb_ioc_factory( config=config, common_ioc=common_ioc, combinator_ioc=combinator_ioc).build() state_machine_ioc = state_machine_ioc_factory() lexical_state_machine_ioc = lexical_state_machine_ioc_factory( config=config, common_ioc=common_ioc, state_machine_ioc=state_machine_ioc).build() interpreter_state_machine_ioc = interpreter_state_machine_ioc_factory( config=config, common_ioc=common_ioc, state_machine_ioc=state_machine_ioc).build() lexical_actions_provider = providers.Singleton( LexicalActions, logger=logging_provider, lexer=lexicomb_ioc.lexer_provider, queue_service=common_ioc.queue_service_provider, notification_service=common_ioc.notification_service_provider) interpreter_actions_provider = providers.Singleton( InterpreterActions, logger=logging_provider, parser_combinator=lexicomb_ioc.parser_provider, queue_service=common_ioc.queue_service_provider, notification_service=common_ioc.notification_service_provider) lexical_state_machine_ioc.lexical_actions_provider.provided_by( lexical_actions_provider) interpreter_state_machine_ioc.interpreter_actions_provider.provided_by( interpreter_actions_provider) lexicomb_pub_sub_client_provider = providers.DelegatedFactory( LexicombPubSubClient, logger=logging_provider, queue_service=common_ioc.queue_service_provider, notification_service=common_ioc.notification_service_provider, message_factory=message_bus_ioc.message_factory_provider, file_stream_service=common_ioc.file_stream_service_provider, context_service=common_ioc.context_service_provider, async_service=common_ioc.async_service_provider) create_client = providers.DelegatedCallable( self.__create_lexicomb_client, logger=logging_provider, pub_sub=message_bus_ioc.pub_sub_provider, message_pipe_line_builder=message_bus_ioc.message_pipe_line_builder_provider, pub_sub_client_factory=lexicomb_pub_sub_client_provider, lexical_state_machine=lexical_state_machine_ioc.lexical_state_machine_provider, interpreter_state_machine=interpreter_state_machine_ioc.interpreter_state_machine_provider) self.__instance.lexicomb_ioc = lexicomb_ioc self.__instance.main = providers.Callable( main, create_client=create_client, pub_sub=message_bus_ioc.pub_sub_provider, async_service=common_ioc.async_service_provider, metric_service=common_ioc.metric_service_provider)
def test_is_delegated_provider(self): """Test is_delegated_provider.""" provider = providers.DelegatedFactory(object) self.assertIs(provider.provide_injection(), provider)
class LexicombIocContainer(containers.DeclarativeContainer): """Inversion of control container for the Lexicomb parser""" def bootstrap_container(config, logger, common_ioc, combinator_ioc, *args, **kwargs): LexicombIocContainer.instance = LexicombIocContainer( config=config, common_ioc=common_ioc, combinator_ioc=combinator_ioc) IocUtil.identify_singletons_to_be_skipped_during_deepcopy(LexicombIocContainer.instance) return LexicombIocContainer.instance common_ioc = providers.DependenciesContainer() combinator_ioc = providers.DependenciesContainer() # Configuration config = providers.Configuration('config') config_provider = providers.Object(config) logging_provider = IocUtil.create_basic_log_adapter(providers, "bbpyp.lexicomb") # internal providers parser_factory_provider = providers.Singleton( lambda: LexicombIocContainer.instance.parser_provider()) lexicon_provider = providers.Singleton( lambda: LexicombIocContainer.instance.config.lexicomb.lexicon()) # lexer tag_exprssions_factory = providers.DelegatedFactory(TagExpressions) tag_expressions_builder_factory = providers.Factory( TagExpressionsBuilder, tag_expressions_factory=tag_exprssions_factory) # parser result_factory_provider = providers.DelegatedFactory(Result) variable_provider = providers.DelegatedFactory(Variable, result_factory=result_factory_provider) real_number_factory_provider = providers.DelegatedFactory( RealNumber, result_factory=result_factory_provider) string_factory_provider = providers.DelegatedFactory( String, result_factory=result_factory_provider) hash_provider = providers.DelegatedFactory(Hash, result_factory=result_factory_provider) access_provider = providers.DelegatedFactory(Access, result_factory=result_factory_provider) assignment_provider = providers.DelegatedFactory( Assignment, result_factory=result_factory_provider) block_factory_provider = providers.DelegatedFactory( Block, result_factory=result_factory_provider) return_statement_factory_provider = providers.DelegatedFactory( ReturnStatement, result_factory=result_factory_provider) exist_provider = providers.DelegatedFactory(Exist, result_factory=result_factory_provider) conditional_provider = providers.DelegatedFactory( Conditional, result_factory=result_factory_provider) conditional_repeat_provider = providers.DelegatedFactory( ConditionalRepeat, result_factory=result_factory_provider) logical_unary_operator_provider = providers.DelegatedFactory( LogicalUnaryOperator, result_factory=result_factory_provider) arithmetic_unary_operator_provider = providers.DelegatedFactory( ArithmeticUnaryOperator, result_factory=result_factory_provider) unary_operator_factory = providers.Factory( UnaryOperatorFactory, logical_unary_operator_factory=logical_unary_operator_provider, arithmetic_unary_operator_factory=arithmetic_unary_operator_provider) arithmetic_binary_operator_provider = providers.DelegatedFactory( ArithmeticBinaryOperator, real_number_factory=real_number_factory_provider, string_factory=string_factory_provider, result_factory=result_factory_provider) relational_binary_operator_provider = providers.DelegatedFactory( RelationalBinaryOperator, result_factory=result_factory_provider) logical_binary_operator_provider = providers.DelegatedFactory( LogicalBinaryOperator, result_factory=result_factory_provider) binary_operator_factory = providers.Factory(BinaryOperatorFactory, arithmetic_binary_operator_factory=arithmetic_binary_operator_provider, relational_binary_operator_factory=relational_binary_operator_provider, logical_binary_operator_factory=logical_binary_operator_provider) select_operator_factory = providers.Factory( SelectOperatorFactory, unary_operator_factory=unary_operator_factory, binary_operator_factory=binary_operator_factory) # Delegates for consumer's of this package lexer_provider = providers.Singleton( Lexer, logger=logging_provider, tag_expressions_builder=tag_expressions_builder_factory) tag_statement_provider = providers.DelegatedFactory( TagStatement, parser_service=parser_factory_provider, lexer_service=lexer_provider, lexicon_path=lexicon_provider, file_stream_service=common_ioc.file_stream_service_provider, result_factory=result_factory_provider) no_op_statement_factory_provider = providers.DelegatedFactory( NoOpStatement, result_factory=result_factory_provider) parser_provider = providers.Singleton( Parser, logger=logging_provider, tag_factory=combinator_ioc.tag_combinator_factory.delegate(), reserved_factory=combinator_ioc.reserved_combinator_factory.delegate(), repeat_match_factory=combinator_ioc.repeat_match_combinator_factory.delegate(), variable_factory=variable_provider, real_number_factory=real_number_factory_provider, hash_factory=hash_provider, access_factory=access_provider, unary_operator_factory=unary_operator_factory, binary_operator_factory=binary_operator_factory, select_operator_factory=select_operator_factory, assignment_factory=assignment_provider, block_factory=block_factory_provider, return_statement_factory=return_statement_factory_provider, no_op_statement_factory=no_op_statement_factory_provider, exist_factory=exist_provider, conditional_factory=conditional_provider, conditional_repeat_factory=conditional_repeat_provider, tag_statement_factory=tag_statement_provider, source_format_service=common_ioc.source_format_service_provider, context_service=common_ioc.context_service_provider, ) build = providers.Callable(bootstrap_container, config=config, logger=logging_provider, common_ioc=common_ioc, combinator_ioc=combinator_ioc)
class CommonIocContainer(containers.DeclarativeContainer): def bootstrap_container(config, source_format_rules, logger): if 'logger' in config: logging.config.dictConfig(config['logger']) logging.getLogger('bbpyp').addHandler(logging.NullHandler()) CommonIocContainer.instance = CommonIocContainer( config=config, source_format_rules=source_format_rules) container = CommonIocContainer.instance IocUtil.identify_singletons_to_be_skipped_during_deepcopy(container) logger.info("container configuration complete") return container # Configuration config = providers.Configuration('config') source_format_rules = providers.Configuration('source_format_rules') logging_provider = IocUtil.create_basic_log_adapter( providers, "bbpyp.common") source_format_service_provider = providers.Singleton( SourceFormatService, format_rules=source_format_rules) context_service_provider = providers.Singleton(ContextService) context_filter_provider = providers.Singleton( BasicContextFilter, context_service=context_service_provider) action_context_factory_provider = providers.DelegatedFactory( ActionContextManager, context_service=context_service_provider) async_service_provider = providers.Singleton( AsyncService, logger=logging_provider, context_service=context_service_provider, action_context_factory=action_context_factory_provider) named_item_service_provider = providers.Factory(NamedItemService) notification_service_provider = providers.Singleton( NotificationService, logger=logging_provider, named_item_service=named_item_service_provider, async_service=async_service_provider) path_service_provider = providers.DelegatedFactory(Path) open_file_service_provider = providers.DelegatedFactory( synchronous_open_file) file_stream_service_provider = providers.Singleton( FileStreamService, logger=logging_provider, async_service=async_service_provider, open_file_service=open_file_service_provider, path_service=path_service_provider, context_service=context_service_provider, ) metric_service_provider = providers.Singleton( MetricService, named_item_service=named_item_service_provider) fifo_queue_provider = providers.DelegatedFactory(FifoQueue) sequence_service_provider = providers.Singleton( SequenceService, fifo_queue_factory=fifo_queue_provider, named_item_service=named_item_service_provider) sequence_queue_provider = providers.DelegatedFactory( SequenceQueue, sequence_service=sequence_service_provider) queue_factory_provider = providers.Factory( QueueFactory, fifo_queue_factory=fifo_queue_provider, sequence_queue_factory=sequence_queue_provider) queue_service_provider = providers.Singleton( QueueService, named_item_service=named_item_service_provider, queue_factory=queue_factory_provider, metric_service=metric_service_provider) sequential_transfer_object_provider = providers.DelegatedFactory( SequentialTransferObject, sequence_service=sequence_service_provider) link_node_iter_delegated_factory = providers.DelegatedFactory(LinkNodeIter) single_link_node_delegated_factory = providers.DelegatedFactory( SingleLinkNode, link_node_iter_factory=link_node_iter_delegated_factory) singly_linked_list_factory = providers.Factory( SinglyLinkedList, single_link_node_factory=single_link_node_delegated_factory) build = providers.Callable(bootstrap_container, config=config, source_format_rules=source_format_rules, logger=logging_provider)
def test_is_delegated_provider(self): self.assertTrue( providers.is_delegated(providers.DelegatedFactory(object)))
def test_repr(): provider = providers.DelegatedFactory(Example) assert repr(provider) == ( "<dependency_injector.providers." "DelegatedFactory({0}) at {1}>".format(repr(Example), hex(id(provider))) )
def test_call_overridden_by_delegated_factory(): provider = providers.AbstractFactory(object) provider.override(providers.DelegatedFactory(Example)) assert isinstance(provider(), Example)
def test_inheritance(): assert isinstance(providers.DelegatedFactory(object), providers.Factory)
"""Example user model.""" def __init__(self, photos_factory): """Initialize instance.""" self.photos_factory = photos_factory self._main_photo = None @property def main_photo(self): """Return user's main photo.""" if not self._main_photo: self._main_photo = self.photos_factory() return self._main_photo # Defining User and Photo factories using DelegatedFactory provider: photos_factory = providers.DelegatedFactory(Photo) users_factory = providers.DelegatedFactory( User, photos_factory=photos_factory, ) # or using Delegate(Factory(...)) photos_factory = providers.Factory(Photo) users_factory = providers.Factory( User, photos_factory=providers.Delegate(photos_factory), ) # or using Factory(...).delegate()
class StateMachineIocContainer(containers.DeclarativeContainer): trigger_transition_factory = providers.DelegatedFactory(TriggerTransition) # Delegates for consumer's of this package state_transition_builder_factory = providers.Factory( StateTransitionBuilder, trigger_transition_factory=trigger_transition_factory)