eric7/DebugClients/Python/coverage/optional.py

branch
eric7
changeset 8527
2bd1325d727e
parent 8526
587202572b10
child 8528
2175f268ad9b
equal deleted inserted replaced
8526:587202572b10 8527:2bd1325d727e
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 import unsure
19
20 def use_unsure():
21 unsure.something()
22
23 Also bad::
24
25 # MyModule.py
26 from coverage.optional import unsure
27
28 def use_unsure():
29 unsure.something()
30
31 Good::
32
33 # MyModule.py
34
35 def use_unsure():
36 from coverage.optional import unsure
37 if unsure is None:
38 raise Exception("Module unsure isn't available!")
39
40 unsure.something()
41
42 """
43
44 import contextlib
45
46 # This file's purpose is to provide modules to be imported from here.
47 # pylint: disable=unused-import
48
49 # TOML support is an install-time extra option.
50 try:
51 import toml
52 except ImportError: # pragma: not covered
53 toml = None
54
55
56 @contextlib.contextmanager
57 def without(modname):
58 """Hide a module for testing.
59
60 Use this in a test function to make an optional module unavailable during
61 the test::
62
63 with coverage.optional.without('toml'):
64 use_toml_somehow()
65
66 Arguments:
67 modname (str): the name of a module importable from
68 `coverage.optional`.
69
70 """
71 real_module = globals()[modname]
72 try:
73 globals()[modname] = None
74 yield
75 finally:
76 globals()[modname] = real_module

eric ide

mercurial