Skip to content

Commit 9f04005

Browse files
authored
fix: 🐛 Unable to call unlock in a module in use
1 parent bb3e8dc commit 9f04005

2 files changed

Lines changed: 32 additions & 7 deletions

File tree

injection/_core/module.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,12 @@ def __str__(self) -> str:
156156
)
157157

158158

159+
@dataclass(frozen=True, slots=True)
160+
class UnlockCalled(Event):
161+
def __str__(self) -> str:
162+
return "An `unlock` method has been called."
163+
164+
159165
"""
160166
Broker
161167
"""
@@ -802,8 +808,11 @@ def change_priority(self, module: Module, priority: Priority | PriorityStr) -> S
802808
return self
803809

804810
def unlock(self) -> Self:
805-
for broker in self.__brokers:
806-
broker.unlock()
811+
event = UnlockCalled()
812+
813+
with self.dispatch(event, lock_bypass=True):
814+
for broker in self.__brokers:
815+
broker.unlock()
807816

808817
return self
809818

@@ -838,20 +847,20 @@ def remove_listener(self, listener: EventListener) -> Self:
838847
self.__channel.remove_listener(listener)
839848
return self
840849

841-
def on_event(self, event: Event, /) -> ContextManager[None] | None:
850+
def on_event(self, event: Event, /) -> ContextManager[None]:
842851
self_event = ModuleEventProxy(self, event)
843852
return self.dispatch(self_event)
844853

845854
@contextmanager
846-
def dispatch(self, event: Event) -> Iterator[None]:
847-
self.__check_locking()
855+
def dispatch(self, event: Event, *, lock_bypass: bool = False) -> Iterator[None]:
856+
if not lock_bypass:
857+
self.__check_locking()
848858

849859
with self.__channel.dispatch(event):
850860
try:
851861
yield
852862
finally:
853-
message = str(event)
854-
self.__debug(message)
863+
self.__debug(event)
855864

856865
def __debug(self, message: object) -> None:
857866
for logger in self.__loggers:

tests/core/test_module.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,22 @@ class C(A): ...
405405
assert isinstance(b1.a, A)
406406
assert isinstance(b2.a, C)
407407

408+
def test_unlock_with_module_in_use_raise_module_lock_error(self, module):
409+
second_module = Module()
410+
module.use(second_module)
411+
412+
@module.singleton
413+
class A: ...
414+
415+
@second_module.singleton
416+
class B: ...
417+
418+
module.get_instance(A)
419+
second_module.get_instance(B)
420+
421+
with pytest.raises(ModuleLockError):
422+
second_module.unlock()
423+
408424
def test_unlock_with_scoped_dependency(self, module):
409425
@module.scoped("test")
410426
class Dependency: ...

0 commit comments

Comments
 (0)