| Total Complexity | 7 |
| Total Lines | 48 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | from typing import Optional |
||
| 2 | |||
| 3 | from lagom import Container |
||
| 4 | |||
| 5 | |||
| 6 | class MySimpleDep: |
||
| 7 | extra_stuff = "yes" |
||
| 8 | |||
| 9 | |||
| 10 | class MyComplexDep: |
||
| 11 | extra_stuff = "yes" |
||
| 12 | |||
| 13 | def __init__(self, something): |
||
| 14 | pass |
||
| 15 | |||
| 16 | |||
| 17 | class MyDepWithAnOptional: |
||
| 18 | success = "yes" |
||
| 19 | |||
| 20 | def __init__(self, dep: Optional[MySimpleDep] = None): |
||
| 21 | self.dep = dep |
||
| 22 | |||
| 23 | |||
| 24 | class MyDepWithAnOptionalThatCantBeBuilt: |
||
| 25 | success = "yes" |
||
| 26 | |||
| 27 | def __init__(self, dep: Optional[MyComplexDep] = "weird default"): # type: ignore |
||
| 28 | self.dep = dep |
||
| 29 | |||
| 30 | |||
| 31 | def test_missing_optional_dependencies_cause_no_errors(container: Container): |
||
| 32 | resolved = container.resolve(MyDepWithAnOptionalThatCantBeBuilt) |
||
| 33 | assert resolved.success == "yes" |
||
| 34 | |||
| 35 | |||
| 36 | def test_defaults_for_optional_types_are_honoured(container: Container): |
||
| 37 | resolved = container.resolve(MyDepWithAnOptionalThatCantBeBuilt) |
||
| 38 | assert resolved.dep == "weird default" |
||
| 39 | |||
| 40 | |||
| 41 | def test_optional_dependencies_are_understood_and_injected(container: Container): |
||
| 42 | resolved = container.resolve(MyDepWithAnOptional) |
||
| 43 | assert resolved.dep.extra_stuff == "yes" # type: ignore |
||
| 44 | |||
| 45 | |||
| 46 | def test_we_can_ask_for_optional_things_that_cant_be_constructed(container: Container): |
||
| 47 | assert container.resolve(Optional[MyComplexDep]) is None # type: ignore |
||
| 48 |