| Total Complexity | 7 |
| Total Lines | 51 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | import pytest |
||
| 2 | |||
| 3 | from lagom import Singleton, Construction, Container |
||
| 4 | |||
| 5 | |||
| 6 | class MyBasicDep: |
||
| 7 | pass |
||
| 8 | |||
| 9 | |||
| 10 | class MyMoreComplicatedDep: |
||
| 11 | def __init__(self, some_number): |
||
| 12 | self.sum_number = some_number |
||
| 13 | |||
| 14 | |||
| 15 | class MyCompositeDep: |
||
| 16 | def __init__(self, a: MyBasicDep, b: MyMoreComplicatedDep): |
||
| 17 | self.a = a |
||
| 18 | self.b = b |
||
| 19 | |||
| 20 | |||
| 21 | @pytest.fixture |
||
| 22 | def container_with_deps(container: Container): |
||
| 23 | container.define(MyBasicDep, Singleton(MyBasicDep)) |
||
| 24 | container.define( |
||
| 25 | MyMoreComplicatedDep, Singleton(Construction(lambda: MyMoreComplicatedDep(5))) |
||
| 26 | ) |
||
| 27 | container.define(MyCompositeDep, Singleton(MyCompositeDep)) |
||
| 28 | return container |
||
| 29 | |||
| 30 | |||
| 31 | def test_singleton_is_only_resolved_once(container_with_deps: Container): |
||
| 32 | first = container_with_deps.resolve(MyBasicDep) |
||
| 33 | second = container_with_deps.resolve(MyBasicDep) |
||
| 34 | assert first is not None |
||
| 35 | assert first is second |
||
| 36 | |||
| 37 | |||
| 38 | def test_singleton_can_have_construction_logic(container_with_deps: Container): |
||
| 39 | first = container_with_deps.resolve(MyMoreComplicatedDep) |
||
| 40 | second = container_with_deps.resolve(MyMoreComplicatedDep) |
||
| 41 | assert first.sum_number == 5 |
||
| 42 | assert first is second |
||
| 43 | |||
| 44 | |||
| 45 | def test_singleton_can_compose_other_dependencies(container_with_deps: Container): |
||
| 46 | first = container_with_deps.resolve(MyCompositeDep) |
||
| 47 | second = container_with_deps.resolve(MyCompositeDep) |
||
| 48 | assert type(first.a) == MyBasicDep |
||
| 49 | assert type(first.b) == MyMoreComplicatedDep |
||
| 50 | assert first is second |
||
| 51 |