コード例 #1
0
def _create_elements(*factories) -> Sequence[Element]:
    return [
        Element(
            injector=FactoryInjector(c),
            strategy=_default_strategy,
        ) for c in factories
    ]
コード例 #2
0
def test_module_consistency_check_internals():
    check = ModuleElementConsistencyCheck()
    elements = [Element(injector=..., strategy=...) for _ in range(4)]

    check.check([Module(elements={*elements}, exports={*elements[:2]})])
    with pytest.raises(ModuleElementConsistencyError):
        check.check(
            [Module(elements={*elements[:2]}, exports={*elements[1:]})])

    a = Module(elements={*elements[:2]}, exports={*elements[:2]})
    b = Module(elements={*elements[2:]}, exports={*elements}, imports={a})
    check.check([a, b])
    a = Module(elements={*elements[:2]}, exports={*elements[:1]})
    b = Module(elements={*elements[2:]}, exports={*elements}, imports={a})
    with pytest.raises(ModuleElementConsistencyError):
        check.check([a, b])

    a = Module(elements={*elements}, bootstrap={*elements})
    check.check([a])
    a = Module(elements={*elements[:2]}, bootstrap={*elements})
    with pytest.raises(ModuleElementConsistencyError):
        check.check([a])
    a = Module(elements={*elements[:2]}, exports={*elements[:1]})
    b = Module(elements={*elements[2:]}, bootstrap={*elements})
    with pytest.raises(ModuleElementConsistencyError):
        check.check([a, b])
コード例 #3
0
def test_singleton_strategy():
    strategy = SingletonProvideStrategy()
    context = SampleContext()
    element = Element(injector=SampleInjector(), strategy=strategy)

    value1 = strategy.provide(context, element)
    assert isinstance(value1, list)
    assert element in context.global_state
    assert context.global_state[element] is value1

    value2 = strategy.provide(context, element)
    assert value1 is value2
コード例 #4
0
def test_module_consistency_check_duplicates():
    check = ModuleElementConsistencyCheck()
    elements = [Element(injector=..., strategy=...) for _ in range(8)]

    check.check([
        Module(elements={*elements[:4]}, exports={*elements[:2]}),
        Module(elements={*elements[4:]}, exports={*elements[6:]}),
    ])
    with pytest.raises(ModuleElementConsistencyError):
        check.check([
            Module(elements={*elements}, exports={*elements[:2]}),
            Module(elements={*elements[4:]}, exports={*elements[6:]}),
        ])
コード例 #5
0
def test_local_strategy():
    strategy = LocalProvideStrategy()
    context = SampleContext()
    element = Element(injector=SampleInjector(), strategy=strategy)

    value1 = strategy.provide(context, element)
    assert isinstance(value1, list)
    assert element not in context.global_state

    value2 = strategy.provide(context, element)
    assert isinstance(value2, list)
    assert element not in context.global_state
    assert value1 is not value2
コード例 #6
0
def test_aggregation_assignment_factory():
    class X:
        pass

    class Y(X):
        pass

    class Z(X):
        pass

    class T:
        pass

    x, x_agg, y, z, t, t_inv = (
        Element(injector=MockupInjector([FrozenSet[X]]), strategy=...),
        Element(injector=MockupInjector([], Iterable[X]), strategy=...),
        Element(injector=MockupInjector([], Y), strategy=...),
        Element(injector=MockupInjector([], Z), strategy=...),
        Element(injector=MockupInjector([], T), strategy=...),
        Element(injector=MockupInjector([T]), strategy=...),
    )

    factory = AggregationAssignmentFactory()

    dependencies, values = _dependencies_values([x, t])
    assignments = [
        factory.assign(dependency, values) for dependency in dependencies
    ]
    assert len(assignments) == 1
    assert len(assignments[0].values) == 0

    dependencies, values = _dependencies_values([t_inv, t])
    with pytest.raises(AssignmentError):
        for dependency in dependencies:
            factory.assign(dependency, values)

    dependencies, values = _dependencies_values([x, y, z, t], imports=[x_agg])
    assignments = [
        factory.assign(dependency, values) for dependency in dependencies
    ]
    assert len(assignments) == 1
    assignment = assignments[0]
    assert len(assignment.values) == 3
    assert {value.type
            for value in assignment.values
            } == {e.value().type
                  for e in [x_agg, y, z]}

    mapper = assignment.mapper
    assert isinstance(mapper, MixedIterableValuesMapper)
    assert mapper.container_factory is frozenset
    for value, flag in zip(assignment.values, mapper.iterate_args):
        if hasattr(value.type, "__origin__"):
            assert flag
        else:
            assert not flag
コード例 #7
0
ファイル: base.py プロジェクト: dlski/python-di
 def create(
     cls,
     injector: Injector,
     singleton: bool = True,
     label: Optional[str] = None,
     export: bool = True,
     bootstrap: bool = False,
     agg_checks: Collection[IsAggregationType] = (),
 ) -> "ModuleElement":
     if singleton:
         strategy = SingletonProvideStrategy()
     else:
         strategy = LocalProvideStrategy()
     return cls(
         element=Element(
             injector=injector,
             strategy=strategy,
             label=label,
         ),
         export=export,
         bootstrap=bootstrap,
         agg_checks=agg_checks,
     )
コード例 #8
0
def _e() -> Element:
    return Element(
        injector=...,
        strategy=...,
    )
コード例 #9
0
 def eval(self, element: Element) -> Any:
     return element.injector()
コード例 #10
0
ファイル: navigator.py プロジェクト: dlski/python-di
 def _iterate_subtypes(cls, element: Element):
     type_ = element.value().type
     if type_:
         yield from (
             sub_type for sub_type in type_.mro() if not is_base_type(sub_type)
         )
コード例 #11
0
ファイル: navigator.py プロジェクト: dlski/python-di
 def _iterate_type(cls, element: Element):
     type_ = element.value().type
     if type_:
         yield type_
コード例 #12
0
ファイル: solvers.py プロジェクト: dlski/python-di
 def value(self, element: Element) -> Value:
     if element not in self._cache:
         self._cache[element] = element.value()
     return self._cache[element]
コード例 #13
0
ファイル: recursive.py プロジェクト: dlski/python-di
 def eval(self, element: Element):
     if not self.has(element):
         raise ApplicationInstanceStateError(f"Missing element {element}")
     kwargs = self._args_values(element)
     return element.injector(**kwargs)