|
| 1 | +# Copyright 2019 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import mock |
| 16 | +import six |
| 17 | + |
| 18 | + |
| 19 | +def maybe_fail_import(predicate): |
| 20 | + """Create and return a patcher that conditionally makes an import fail. |
| 21 | +
|
| 22 | + Args: |
| 23 | + predicate (Callable[[...], bool]): A callable that, if it returns `True`, |
| 24 | + triggers an `ImportError`. It must accept the same arguments as the |
| 25 | + built-in `__import__` function. |
| 26 | + https://docs.python.org/3/library/functions.html#__import__ |
| 27 | +
|
| 28 | + Returns: |
| 29 | + A mock patcher object that can be used to enable patched import behavior. |
| 30 | + """ |
| 31 | + orig_import = six.moves.builtins.__import__ |
| 32 | + |
| 33 | + def custom_import(name, globals=None, locals=None, fromlist=(), level=0): |
| 34 | + if predicate(name, globals, locals, fromlist, level): |
| 35 | + raise ImportError |
| 36 | + return orig_import(name, globals, locals, fromlist, level) |
| 37 | + |
| 38 | + return mock.patch.object(six.moves.builtins, "__import__", new=custom_import) |
0 commit comments