From 0ab6104428df576a892c1dcec025043ec76485c3 Mon Sep 17 00:00:00 2001 From: Alec Thomas Date: Thu, 27 Jun 2013 10:40:21 -0400 Subject: [PATCH] Fix tests! --- README.md | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/README.md b/README.md index e681c4b..62d533b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Injector work with the following Python interpreters: A Quick Example --------------- + ```pycon >>> from injector import Injector, inject >>> class Inner(object): @@ -38,6 +39,7 @@ A Quick Example >>> outer = injector.get(Outer) >>> outer.inner.forty_two 42 + ``` A Full Example @@ -45,18 +47,23 @@ A Full Example Here's a full example to give you a taste of how Injector works: + ```pycon >>> from injector import Module, Key, provides, Injector, inject, singleton + ``` We'll use an in-memory SQLite database for our example: + ```pycon >>> import sqlite3 + ``` And make up an imaginary RequestHandler class that uses the SQLite connection: + ```pycon >>> class RequestHandler(object): ... @inject(db=sqlite3.Connection) @@ -67,24 +74,30 @@ And make up an imaginary RequestHandler class that uses the SQLite connection: ... cursor = self._db.cursor() ... cursor.execute('SELECT key, value FROM data ORDER by key') ... return cursor.fetchall() + ``` Next, for the sake of the example, we'll create a "configuration" annotated type: + ```pycon >>> Configuration = Key('configuration') + ``` Key is used to uniquely identifies the configuration dictionary. Next, we bind the configuration to the injector, using a module: + ```pycon >>> def configure_for_testing(binder): ... configuration = {'db_connection_string': ':memory:'} ... binder.bind(Configuration, to=configuration, scope=singleton) + ``` Next we create a module that initialises the DB. It depends on the configuration provided by the above module to create a new DB connection, then populates it with some dummy data, and provides a Connection object: + ```pycon >>> class DatabaseModule(Module): ... @singleton @@ -96,26 +109,31 @@ Next we create a module that initialises the DB. It depends on the configuration ... cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)') ... cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")') ... return conn + ``` (Note how we have decoupled configuration from our database initialisation code.) Finally, we initialise an Injector and use it to instantiate a RequestHandler instance. This first transitively constructs a sqlite3.Connection object, and the Configuration dictionary that it in turn requires, then instantiates our \`RequestHandler\`: + ```pycon >>> injector = Injector([configure_for_testing, DatabaseModule()]) >>> handler = injector.get(RequestHandler) >>> tuple(map(str, handler.get()[0])) # py3/py2 compatibility hack ('hello', 'world') + ``` We can also veryify that our Configuration and SQLite connections are indeed singletons within the Injector: + ```pycon >>> injector.get(Configuration) is injector.get(Configuration) True >>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection) True + ``` You're probably thinking something like: "this is a large amount of work just to give me a database connection", and you are correct; dependency injection is typically not that useful for smaller projects. It comes into its own on large projects where the up-front effort pays for itself in two ways: @@ -157,10 +175,12 @@ For a generic type such as `str`, annotations are very useful for unique identif As an *alternative* convenience to using annotations, `Key` may be used to create unique types as necessary: + ```pycon >>> from injector import Key >>> Name = Key('name') >>> Description = Key('description') + ``` Which may then be used as binding keys, without annotations, as they already uniquely identify a particular provider: @@ -178,12 +198,14 @@ An annotation is additional unique information about a type to avoid binding key A binding is the mapping of a unique binding key to a corresponding provider. For example: + ```pycon >>> from injector import InstanceProvider >>> bindings = { ... (Name, None): InstanceProvider('Sherlock'), ... (Description, None): InstanceProvider('A man of astounding insight'), ... } + ``` ### Binder @@ -194,16 +216,19 @@ The `Binder` is simply a convenient wrapper around the dictionary that maps type A `Module` configures bindings. It provides methods that simplify the process of binding a key to a provider. For example the above bindings would be created with: + ```pycon >>> from injector import Module >>> class MyModule(Module): ... def configure(self, binder): ... binder.bind(Name, to='Sherlock') ... binder.bind(Description, to='A man of astounding insight') + ``` For more complex instance construction, methods decorated with `@provides` will be called to resolve binding keys: + ```pycon >>> from injector import provides >>> class MyModule(Module): @@ -213,6 +238,7 @@ For more complex instance construction, methods decorated with `@provides` will ... @provides(Description) ... def describe(self): ... return 'A man of astounding insight (at %s)' % time.time() + ``` ### Injection @@ -221,6 +247,7 @@ Injection is the process of providing an instance of a type, to a method that us Here is an example of injection on a module provider method, and on the constructor of a normal class: + ```pycon >>> from injector import inject >>> class User(object): @@ -228,14 +255,18 @@ Here is an example of injection on a module provider method, and on the construc ... def __init__(self, name, description): ... self.name = name ... self.description = description + ``` + ```pycon >>> class UserModule(Module): ... def configure(self, binder): ... binder.bind(User) + ``` + ```pycon >>> class UserAttributeModule(Module): ... def configure(self, binder): @@ -245,33 +276,41 @@ Here is an example of injection on a module provider method, and on the construc ... @inject(name=Name) ... def describe(self, name): ... return '%s is a man of astounding insight' % name + ``` You can also `inject`-decorate class itself. This code: + ```pycon >>> @inject(name=Name) ... class Item(object): ... pass + ``` is equivalent to: + ```pycon >>> class Item(object): ... @inject(name=Name) ... def __init__(self, name): ... self.name = name + ``` **Note**: You can also begin the name of injected member with an underscore(s) (to indicate the member being private for example). In such case the member will be injected using the name you specified, but corresponding parameter in a constructor (let's say you instantiate the class manually) will have the underscore prefix stripped (it makes it consistent with most of the usual parameter names): + ```pycon >>> @inject(_y=int) ... class X(object): ... pass + ``` + ```pycon >>> x1 = injector.get(X) >>> x1.y @@ -279,8 +318,10 @@ Traceback (most recent call last): AttributeError: 'X' object has no attribute 'y' >>> x1._y 0 + ``` + ```pycon >>> x2 = X(y=2) >>> x2.y @@ -288,34 +329,42 @@ Traceback (most recent call last): AttributeError: 'X' object has no attribute 'y' >>> x2._y 2 + ``` ### Injector The `Injector` brings everything together. It takes a list of `Module` s, and configures them with a binder, effectively creating a dependency graph: + ```pycon >>> from injector import Injector >>> injector = Injector([UserModule(), UserAttributeModule()]) + ``` You can also pass classes instead of instances to `Injector`, it will instantiate them for you: + ```pycon >>> injector = Injector([UserModule, UserAttributeModule]) + ``` The injector can then be used to acquire instances of a type, either directly: + ```pycon >>> injector.get(Name) 'Sherlock' >>> injector.get(Description) 'Sherlock is a man of astounding insight' + ``` Or transitively: + ```pycon >>> user = injector.get(User) >>> isinstance(user, User) @@ -324,50 +373,61 @@ True 'Sherlock' >>> user.description 'Sherlock is a man of astounding insight' + ``` ### Assisted injection Sometimes there are classes that have injectable and non-injectable parameters in their constructors. Let's have for example: + ```pycon >>> class Database(object): pass + ``` + ```pycon >>> class User(object): ... def __init__(self, name): ... self.name = name + ``` + ```pycon >>> @inject(db=Database) ... class UserUpdater(object): ... def __init__(self, user): ... pass + ``` You may want to have database connection `db` injected into `UserUpdater` constructor, but in the same time provide `user` object by yourself, and assuming that `user` object is a value object and there's many users in your application it doesn't make much sense to inject objects of class `User`. In this situation there's technique called Assisted injection: + ```pycon >>> from injector import AssistedBuilder >>> injector = Injector() >>> builder = injector.get(AssistedBuilder(UserUpdater)) >>> user = User('John') >>> user_updater = builder.build(user=user) + ``` This way we don't get `UserUpdater` directly but rather a builder object. Such builder has `build(**kwargs)` method which takes non-injectable parameters, combines them with injectable dependencies of `UserUpdater` and calls `UserUpdater` initializer using all of them. `AssistedBuilder(X)` is injectable just as anything else, if you need instance of it you just ask for it like that: + ```pycon >>> @inject(updater_builder=AssistedBuilder(UserUpdater)) ... class NeedsUserUpdater(object): ... def method(self): ... updater = self.updater_builder.build(user=None) + ``` More information on this topic: @@ -378,6 +438,7 @@ More information on this topic: Concept similar to Guice's child injectors is supported by `Injector`. This way you can have one injector that inherits bindings from other injector (parent) but these bindings can be overriden in it and it doesn't affect parent injector bindings: + ```pycon >>> def configure_parent(binder): ... binder.bind(str, to='asd') @@ -392,10 +453,12 @@ Concept similar to Guice's child injectors is supported by `Injector`. This way ('asd', 42) >>> child.get(str), child.get(int) ('qwe', 42) + ``` **Note**: Default scopes are bound only to root injector. Binding them manually to child injectors will result in unexpected behaviour. **Note 2**: Once a binding key is present in parent injector scope (like `singleton` scope), provider saved there takes predecence when binding is overridden in child injector in the same scope. This behaviour is subject to change: + ```pycon >>> def configure_parent(binder): ... binder.bind(str, to='asd', scope=singleton) @@ -409,6 +472,7 @@ Concept similar to Guice's child injectors is supported by `Injector`. This way 'qwe' >>> parent.get(str) # wat 'qwe' + ``` Scopes @@ -424,6 +488,7 @@ Singletons are declared by binding them in the SingletonScope. This can be done A (redunant) example showing all three methods: + ```pycon >>> @singleton ... class Thing(object): pass @@ -434,6 +499,7 @@ A (redunant) example showing all three methods: ... @provides(Thing) ... def provide_thing(self): ... return Thing() + ``` ### Implementing new Scopes @@ -442,18 +508,22 @@ In the above description of scopes, we glossed over a lot of detail. In particul Basically, there are two steps. First, subclass `Scope` and implement `Scope.get`: + ```pycon >>> from injector import Scope >>> class CustomScope(Scope): ... def get(self, key, provider): ... return provider + ``` Then create a global instance of `ScopeDecorator` to allow classes to be easily annotated with your scope: + ```pycon >>> from injector import ScopeDecorator >>> customscope = ScopeDecorator(CustomScope) + ``` This can be used like so: @@ -462,18 +532,22 @@ This can be used like so: Scopes are bound in modules with the `Binder.bind_scope` method: + ```pycon >>> class MyModule(Module): ... def configure(self, binder): ... binder.bind_scope(CustomScope) + ``` Scopes can be retrieved from the injector, as with any other instance. They are singletons across the life of the injector: + ```pycon >>> injector = Injector([MyModule()]) >>> injector.get(CustomScope) is injector.get(CustomScope) True + ``` For scopes with a transient lifetime, such as those tied to HTTP requests, the usual solution is to use a thread or greenlet-local cache inside the scope. The scope is "entered" in some low-level code by calling a method on the scope instance that creates this cache. Once the request is complete, the scope is "left" and the cache cleared. @@ -483,6 +557,7 @@ Tests When you use unit test framework such as `unittest2` or `nose` you can also profit from `injector`. However, manually creating injectors and test classes can be quite annoying. There is, however, `with_injector` method decorator which has parameters just as `Injector` construtor and installes configured injector into class instance on the time of method call: + ```pycon >>> from injector import Module, with_injector >>> class UsernameModule(Module): @@ -497,6 +572,7 @@ When you use unit test framework such as `unittest2` or `nose` you can also prof ... @inject(username=str) ... def test_username(self, username): ... assert (username == 'Maria') + ``` *Each* method call re-initializes `Injector` - if you want to you can also put `with_injector` decorator on class constructor.