|
1 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 |
|
2 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt |
|
3 |
|
4 """ |
|
5 Imports that we need at runtime, but might not be present. |
|
6 |
|
7 When importing one of these modules, always do it in the function where you |
|
8 need the module. Some tests will need to remove the module. If you import |
|
9 it at the top level of your module, then the test won't be able to simulate |
|
10 the module being unimportable. |
|
11 |
|
12 The import will always succeed, but the value will be None if the module is |
|
13 unavailable. |
|
14 |
|
15 Bad:: |
|
16 |
|
17 # MyModule.py |
|
18 from coverage.optional import unsure |
|
19 |
|
20 def use_unsure(): |
|
21 unsure.something() |
|
22 |
|
23 Good:: |
|
24 |
|
25 # MyModule.py |
|
26 |
|
27 def use_unsure(): |
|
28 from coverage.optional import unsure |
|
29 if unsure is None: |
|
30 raise Exception("Module unsure isn't available!") |
|
31 |
|
32 unsure.something() |
|
33 |
|
34 """ |
|
35 |
|
36 import contextlib |
|
37 |
|
38 # This file's purpose is to provide modules to be imported from here. |
|
39 # pylint: disable=unused-import |
|
40 |
|
41 # TOML support is an install-time extra option. |
|
42 try: |
|
43 import toml |
|
44 except ImportError: # pragma: not covered |
|
45 toml = None |
|
46 |
|
47 |
|
48 @contextlib.contextmanager |
|
49 def without(modname): |
|
50 """Hide a module for testing. |
|
51 |
|
52 Use this in a test function to make an optional module unavailable during |
|
53 the test:: |
|
54 |
|
55 with coverage.optional.without('toml'): |
|
56 use_toml_somehow() |
|
57 |
|
58 Arguments: |
|
59 modname (str): the name of a module importable from |
|
60 `coverage.optional`. |
|
61 |
|
62 """ |
|
63 real_module = globals()[modname] |
|
64 try: |
|
65 globals()[modname] = None |
|
66 yield |
|
67 finally: |
|
68 globals()[modname] = real_module |