Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_registering_a_callable_as_concrete_is_exception():
"""
Likewise, if we register an arbitrary callable, there's
no key by which we can later resolve, so we reject the
registration
"""
container = Container()
with pytest.raises(InvalidRegistrationException):
container.register(lambda: "oops")
def test_can_register_an_instance():
container = Container()
writer = TmpFileMessageWriter("my-file")
container.register(MessageWriter, instance=writer)
expect(container.resolve(MessageWriter)).to(equal(writer))
def test_forward_references_can_be_registered_as_strings():
"""
For cases where you want to declare a ref like 'module.Dep' we allow you to
resolve a forward reference with an arbitrary string.
"""
container = punq.Container()
container.register("Dependency", DataAccessLayer)
container.register(Client)
instance = container.resolve(Client)
assert instance.dep.val == 2
def test_defaults_are_superseded_by_context():
container = Container()
container.register(Dep)
container.register(Client)
client = container.resolve(Client, b=5)
expect(client.b).to(equal(5))
def test_resolve_all_returns_all_registrations_in_order():
container = Container()
container.register(MessageWriter, StdoutMessageWriter)
container.register(MessageWriter, TmpFileMessageWriter, path="my-file")
[first, second] = container.resolve_all(MessageWriter)
expect(first).to(be_a(StdoutMessageWriter))
expect(second).to(be_a(TmpFileMessageWriter))
def test_can_resolve_objects_with_forward_references():
"""
If we've already registered a type with the name 'Dependency' then we
should be able to resolve the forward reference.
"""
container = punq.Container()
container.register(Dependency)
container.register(Client)
instance = container.resolve(Client)
assert instance.dep.val == 1
def test_can_provide_arguments_to_resolve():
container = Container()
container.register(MessageWriter, TmpFileMessageWriter)
instance = container.resolve(MessageWriter, path="foo")
expect(instance.path).to(equal("foo"))
def test_resolves_instances_with_prototype_scope():
container = Container()
container.register(MessageWriter, StdoutMessageWriter, scope=Scope.transient)
mw1 = container.resolve(MessageWriter)
mw2 = container.resolve(MessageWriter)
expect(mw1).not_to(equal(mw2))
def test_can_register_with_a_custom_factory():
container = Container()
container.register(MessageWriter, lambda: "win")
container.register(MessageSpeaker, HelloWorldSpeaker)
speaker = container.resolve(MessageSpeaker)
expect(speaker).to(be_a(HelloWorldSpeaker))
expect(speaker.writer).to(equal("win"))
def test_can_register_a_concrete_type():
container = Container()
container.register(StdoutMessageWriter)
expect(container.resolve(StdoutMessageWriter)).to(be_a(StdoutMessageWriter))