Add implementation, typing stubs, and tests

This commit is contained in:
Roman Mogylatov 2021-02-15 08:49:59 -05:00
parent 93fa37728b
commit 3a4d84787e
4 changed files with 5080 additions and 4847 deletions

File diff suppressed because it is too large Load Diff

View File

@ -176,6 +176,8 @@ class CoroutineDelegate(Delegate):
class ConfigurationOption(Provider[Any]):
UNDEFINED: object
def __init__(self, name: Tuple[str], root: Configuration) -> None: ...
def __enter__(self) -> ConfigurationOption: ...
def __exit__(self, *exc_info: Any) -> None: ...
def __getattr__(self, item: str) -> ConfigurationOption: ...
def __getitem__(self, item: Union[str, Provider]) -> ConfigurationOption: ...
@property
@ -203,6 +205,8 @@ class TypedConfigurationOption(Callable[T]):
class Configuration(Object[Any]):
DEFAULT_NAME: str = 'config'
def __init__(self, name: str = DEFAULT_NAME, default: Optional[Any] = None, *, strict: bool = False) -> None: ...
def __enter__(self) -> Configuration : ...
def __exit__(self, *exc_info: Any) -> None: ...
def __getattr__(self, item: str) -> ConfigurationOption: ...
def __getitem__(self, item: Union[str, Provider]) -> ConfigurationOption: ...
def get_name(self) -> str: ...

View File

@ -1415,6 +1415,12 @@ cdef class ConfigurationOption(Provider):
return copied
def __enter__(self):
return self
def __exit__(self, *exc_info):
pass
def __str__(self):
return represent_provider(provider=self, provides=self.get_name())
@ -1740,6 +1746,12 @@ cdef class Configuration(Object):
return copied
def __enter__(self):
return self
def __exit__(self, *exc_info):
pass
def __str__(self):
return represent_provider(provider=self, provides=self.__name)

View File

@ -243,6 +243,33 @@ class ConfigTests(unittest.TestCase):
with self.assertRaises(AttributeError):
a.__name__
def test_context_manager_alias(self):
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
container = Container()
with container.config as cfg:
cfg.override({'foo': 'foo', 'bar': 'bar'})
self.assertEqual(container.config(), {'foo': 'foo', 'bar': 'bar'})
self.assertEqual(cfg(), {'foo': 'foo', 'bar': 'bar'})
self.assertIs(container.config, cfg)
def test_option_context_manager_alias(self):
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
container = Container()
with container.config.option as opt:
opt.override({'foo': 'foo', 'bar': 'bar'})
self.assertEqual(container.config(), {'option': {'foo': 'foo', 'bar': 'bar'}})
self.assertEqual(container.config.option(), {'foo': 'foo', 'bar': 'bar'})
self.assertEqual(opt(), {'foo': 'foo', 'bar': 'bar'})
self.assertIs(container.config.option, opt)
def test_missing_key(self):
# See: https://github.com/ets-labs/python-dependency-injector/issues/358
self.config.override(None)