# class Db(object): pass class Mailer(object): pass # class User(object): db = inject.attr(Db) mailer = inject.attr(Mailer) def __init__(self, name): self.name = name def register(self): self.db.save(self) self.mailer.send_welcome_email(self.name) # inmemory . class TestUser(unittest.TestCase): def setUp(self): inject.clear_and_configure(lambda binder: binder \ .bind(Db, InMemoryDb()) \ .bind(Mailer, Mock())) self.mailer = inject.instance(Mailer) def test_register__should_send_welcome_email(self): # . user = User('John Doe') # . user.register() # . self.mailer.send_welcome_email.assert_called_with('John Doe')
[sudo] pip install inject
# . import inject # def my_config(binder): binder.install(my_config2) # binder.bind(Db, RedisDb('localhost:1234')) binder.bind_to_provider(CurrentUser, get_current_user) # . inject.configure(my_config) # inject.instance inject.attr class User(object): db = inject.attr(Db) @classmethod def load(cls, id): return cls.db.load('user', id) def __init__(self, id): self.id = id def save(self): self.db.save('user', self) def foo(bar): cache = inject.instance(Cache) cache.save('bar', bar) # # . user = User(10) user.save()
redis = RedisCache(address='localhost:1234') def config(binder): binder.bind(Cache, redis)
def config(binder): # Creates a redis cache singleton on first injection. binder.bind_to_constructor(Cache, lambda: RedisCache(address='localhost:1234'))
def get_my_thread_local_cache(): # Custom code here pass def config(binder): # Executes the provider on each injection. binder.bind_to_provider(Cache, get_my_thread_local_cache)
class Config(object): pass class Cache(object): config = inject.attr(Config) class Db(object): config = inject.attr(Config) class User(object): cache = inject.attr(Cache) db = inject.attr(Db) @classmethod def load(cls, user_id): return cls.cache.load('users', user_id) or cls.db.load('users', user_id) inject.configure(lambda binder: binder.bind(Config, load_config_file())) user = User.load(10)
Source: https://habr.com/ru/post/212217/