Patch pkgutil.get_loader to give loader without get_filename or archive. This provides for tests where a system has custom loaders, e.g. Google App Engine's HardenedModulesHook, which have neither the `get_filename` method nor the `archive` attribute. This fixture will run the test
(request, monkeypatch)
| 98 | |
| 99 | @pytest.fixture(params=(True, False)) |
| 100 | def limit_loader(request, monkeypatch): |
| 101 | """Patch pkgutil.get_loader to give loader without get_filename or archive. |
| 102 | |
| 103 | This provides for tests where a system has custom loaders, e.g. Google App |
| 104 | Engine's HardenedModulesHook, which have neither the `get_filename` method |
| 105 | nor the `archive` attribute. |
| 106 | |
| 107 | This fixture will run the testcase twice, once with and once without the |
| 108 | limitation/mock. |
| 109 | """ |
| 110 | if not request.param: |
| 111 | return |
| 112 | |
| 113 | class LimitedLoader: |
| 114 | def __init__(self, loader): |
| 115 | self.loader = loader |
| 116 | |
| 117 | def __getattr__(self, name): |
| 118 | if name in {"archive", "get_filename"}: |
| 119 | raise AttributeError(f"Mocking a loader which does not have {name!r}.") |
| 120 | return getattr(self.loader, name) |
| 121 | |
| 122 | old_get_loader = pkgutil.get_loader |
| 123 | |
| 124 | def get_loader(*args, **kwargs): |
| 125 | return LimitedLoader(old_get_loader(*args, **kwargs)) |
| 126 | |
| 127 | monkeypatch.setattr(pkgutil, "get_loader", get_loader) |
| 128 | |
| 129 | |
| 130 | @pytest.fixture |
nothing calls this directly
no outgoing calls
no test coverage detected