|
| 1 | +from dataclasses import dataclass |
| 2 | +from uuid import uuid4 |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from injection import find_instance, injectable, mod |
| 7 | +from injection.loaders import ProfileLoader |
| 8 | + |
| 9 | + |
| 10 | +class TestProfileLoader: |
| 11 | + def test_load_with_success(self): |
| 12 | + profile_name = "test" |
| 13 | + global_profile_name = uuid4().hex |
| 14 | + |
| 15 | + @mod(global_profile_name).constant |
| 16 | + class GlobalConfig: ... |
| 17 | + |
| 18 | + @injectable |
| 19 | + @dataclass |
| 20 | + class A: |
| 21 | + config: GlobalConfig |
| 22 | + |
| 23 | + @mod(profile_name).injectable(on=A) |
| 24 | + class B(A): ... |
| 25 | + |
| 26 | + loader = ProfileLoader( |
| 27 | + { |
| 28 | + mod().name: [global_profile_name], |
| 29 | + profile_name: [global_profile_name], |
| 30 | + } |
| 31 | + ) |
| 32 | + |
| 33 | + with pytest.raises(TypeError): |
| 34 | + find_instance(A) |
| 35 | + |
| 36 | + loader.init() |
| 37 | + |
| 38 | + assert type(find_instance(A)) is A |
| 39 | + loaded_profile = loader.load(profile_name) |
| 40 | + assert type(find_instance(A)) is B |
| 41 | + |
| 42 | + # Cleaning |
| 43 | + loaded_profile.unload() |
| 44 | + |
| 45 | + def test_load_with_context_manager(self): |
| 46 | + profile_name = "test" |
| 47 | + global_profile_name = uuid4().hex |
| 48 | + |
| 49 | + @mod(global_profile_name).constant |
| 50 | + class GlobalConfig: ... |
| 51 | + |
| 52 | + @injectable |
| 53 | + @dataclass |
| 54 | + class A: |
| 55 | + config: GlobalConfig |
| 56 | + |
| 57 | + @mod(profile_name).injectable(on=A) |
| 58 | + class B(A): ... |
| 59 | + |
| 60 | + loader = ProfileLoader( |
| 61 | + { |
| 62 | + mod().name: [global_profile_name], |
| 63 | + profile_name: [global_profile_name], |
| 64 | + } |
| 65 | + ) |
| 66 | + loader.init() |
| 67 | + |
| 68 | + assert type(find_instance(A)) is A |
| 69 | + |
| 70 | + with loader.load(profile_name): |
| 71 | + assert type(find_instance(A)) is B |
| 72 | + |
| 73 | + assert type(find_instance(A)) is A |
0 commit comments