Exemplo n.º 1
0
def test_wrong_registration(monkeypatch, container):
    # Wrong class in registry

    monkeypatch.setattr(container, 'get', DummyWrongRegistrations.d_get)
    inj = Injector(DummyWrongRegistrations)
    with pytest.raises(LookupError) as exc:
        inj(container)
    msg = 'Injector failed for target on DummyWrongRegistrations'
    assert msg == str(exc.value)
Exemplo n.º 2
0
def test_nothing_needed(container):
    # Our dataclass doesn't want anything

    @dataclass
    class Dummy:
        pass

    inj = Injector(Dummy)
    result: Dummy = inj(container)
    assert Dummy == result.__class__
Exemplo n.º 3
0
def test_primitive_value_with_default(container):
    # Type is str but you don't put primitive values in registry

    @dataclass
    class Dummy:
        target: str = 'Dummy Target'

    inj = Injector(Dummy)
    result: Dummy = inj(container)
    assert 'Dummy Target' == result.target
Exemplo n.º 4
0
def test_injected_customer_from_injector(container, dummy_customer):
    # The best spelling for getting the context as the correct type

    @dataclass
    class Dummy:
        context: DummyCustomer = injected(Context)

    container.context = dummy_customer
    inj = Injector(Dummy)
    result: Dummy = inj(container)
    assert 'dummy_customer' == getattr(result.context, 'name')
Exemplo n.º 5
0
def test_injected_customer_from_container_attr(container, dummy_customer):
    # Slightly-better spelling for getting context, but as correct type

    @dataclass
    class Dummy:
        context: DummyCustomer = injected(ServiceContainer, attr='context')

    container.context = dummy_customer
    inj = Injector(Dummy)
    result: Dummy = inj(container)
    assert 'dummy_customer' == getattr(result.context, 'name')
Exemplo n.º 6
0
def test_container_post_init(monkeypatch, container, dummy_customer):
    # Use dataclass post init to get something out of the
    # container

    @dataclass
    class Dummy:
        container: ServiceContainer
        url: Optional[str] = None

        def __post_init__(self):
            self.url = self.container.get(Url)

    def d_get(key):
        if key is Url:
            return Url()
        raise TypeError()

    monkeypatch.setattr(container, 'get', d_get)
    container.context = dummy_customer
    inj = Injector(Dummy)
    result: Dummy = inj(container)
    assert container == result.container
Exemplo n.º 7
0
def test_init_false(container):
    # Use __post_init__ to initialize a field

    inj = Injector(DummyInit)
    result: DummyInit = inj(container)
    assert 'initialized' == result.name
Exemplo n.º 8
0
def test_container(container):
    # Target wants to grab the container itself

    inj = Injector(DummyContainer)
    result: DummyContainer = inj(container)
    assert container == result.container