• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pywbem / pywbemtools / test-2757

11 Jan 2026 09:04AM UTC coverage: 29.475% (-58.6%) from 88.026%
test-2757

Pull #1501

github

web-flow
Merge 4229b955d into f9b5e1682
Pull Request #1501: Fixed start program timeouts and other issues in listener tests; Enabled tests again

59 of 116 new or added lines in 3 files covered. (50.86%)

3924 existing lines in 32 files now uncovered.

1953 of 6626 relevant lines covered (29.47%)

0.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

39.68
/pywbemtools/pywbemcli/mockscripts/__init__.py
1
# (C) Copyright 2020 IBM Corp.
2
# (C) Copyright 2020 Inova Development Inc.
3
# All Rights Reserved
4
#
5
# Licensed under the Apache License, Version 2.0 (the "License");
6
# you may not use this file except in compliance with the License.
7
# You may obtain a copy of the License at
8
#
9
#    http://www.apache.org/licenses/LICENSE-2.0
10
#
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS,
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
# See the License for the specific language governing permissions and
15
# limitations under the License.
16
"""
2✔
17
Module for holding mock scripts.
18

19
This module provides its namespace as the parent namespace for any mock scripts.
20
The main objects in mock scripts are provider classes, and they need to exist
21
in a module namespace for pickle to be able to load the corresponding objects.
22
"""
23

24
import sys
2✔
25
import os
2✔
26
import importlib
2✔
27
import traceback
2✔
28
import pywbem
2✔
29

30
from ..._utils import pywbemtools_warn_explicit
2✔
31

32

33
class MockError(Exception):
2✔
34
    """
35
    Base class for all exceptions related to issues with the mock environment.
36
    """
37
    pass
2✔
38

39

40
class NotCacheable(MockError):
2✔
41
    """
42
    Indicates that the mock environment is not cacheable.
43
    """
44
    pass
2✔
45

46

47
class MockFileError(MockError):
2✔
48
    """
49
    Indicates an issue with a mock file.
50
    """
51
    pass
2✔
52

53

54
class MockScriptError(MockFileError):
2✔
55
    """
56
    Indicates that the mock script raised an exception. The exception message
57
    contains the traceback from the script.
58
    """
59
    pass
2✔
60

61

62
class MockMOFCompileError(MockFileError):
2✔
63
    """
64
    Indicates that a mock MOF file could not be compiled.
65
    """
66
    pass
2✔
67

68

69
class SetupNotSupportedError(MockError):
2✔
70
    """
71
    Indicates that a mock script with the setup() function was used on Python
72
    <3.5.
73

74
    On Python <3.5, only the old setup approach with global variables is
75
    supported.
76
    """
77
    pass
2✔
78

79

80
class DeprecatedSetupWarning(Warning):
2✔
81
    """
82
    Indicates the use of deprecated mock script setup.
83
    """
84
    pass
2✔
85

86

87
def setup_script(file_path, conn, server, verbose):
2✔
88
    """
89
    Import a mock script and perform its setup.
90

91
    Both types of mock script setup are supported:
92
    * The setup via calling setup(conn, server, verbose)
93
    * The deprecated setup via global variables CONN, SERVER, VERBOSE
94

95
    Raises:
96
      MockScriptError:
97
      SetupNotSupportedError (py<3.5): New-style setup in mock script not
98
        supported.
99
      NotCacheable (py<3.5): Mock environment is not cacheable.
100
      DeprecatedSetupWarning: Old-style setup mock script. This is a
101
        warning that this style is deprecated and will be removed in a
102
        future version of pywbemtools
103
    """
UNCOV
104
    modpath = get_modpath(file_path)
×
UNCOV
105
    spec = importlib.util.spec_from_file_location(modpath, file_path)
×
UNCOV
106
    module = importlib.util.module_from_spec(spec)
×
107

108
    # We cannot find out whether the script has a setup() function before
109
    # executing it, so we have to set the global variables for the old
110
    # setup approach in any case.
111
    # Deprecated: These global variables have been deprecated will be removed
112
    # in a future version of pywbemtools, They are retained because users may
113
    # have defined scripts that use this old-style interface.
UNCOV
114
    module.CONN = conn
×
UNCOV
115
    module.SERVER = server
×
UNCOV
116
    module.VERBOSE = verbose
×
117

UNCOV
118
    sys.modules[modpath] = module
×
UNCOV
119
    try:
×
UNCOV
120
        spec.loader.exec_module(module)
×
UNCOV
121
    except Exception as exc:
×
UNCOV
122
        raise script_error(file_path, exc)
×
123

UNCOV
124
    if hasattr(module, 'setup'):
×
UNCOV
125
        try:
×
UNCOV
126
            module.setup(conn=conn, server=server, verbose=verbose)
×
127
        except Exception as exc:
×
128
            raise script_error(file_path, exc)
×
129
    else:
UNCOV
130
        pywbemtools_warn_explicit(
×
131
            "The support of mock scripts without setup() function is "
132
            "deprecated and will be removed in a future version.",
133
            DeprecatedSetupWarning, file_path, 0)
134

135

136
def import_script(file_path):
2✔
137
    """
138
    Import a mock script causing it to define the provider class(es), without
139
    performing setup activities such as registering its provider(s) or adding
140
    objects to the CIM repository of the mock connection.
141

142
    There are multiple reasons this function can raise NotCacheable. If
143
    that happens, the logic of the caller is to perform a complete build
144
    of the mock environment. During that build, script errors or the
145
    deprecation of the old setup approach will surface.
146

147
    Raises:
148
      NotCacheable
149
    """
UNCOV
150
    modpath = get_modpath(file_path)
×
UNCOV
151
    spec = importlib.util.spec_from_file_location(modpath, file_path)
×
UNCOV
152
    module = importlib.util.module_from_spec(spec)
×
UNCOV
153
    sys.modules[modpath] = module
×
UNCOV
154
    try:
×
UNCOV
155
        spec.loader.exec_module(module)
×
UNCOV
156
    except Exception:
×
157
        # Possible reasons:
158
        # - Error in mock script
159
        # - Mock script implements old setup approach with global variables,
160
        #   (but we intentionally did not set them in order not to perform
161
        #   the setup)
162
        # We report the reason was the old setup approach. If it was en error,
163
        # this will surface during rebuild.
UNCOV
164
        raise NotCacheable(
×
165
            f"Mock script {file_path} implements old setup approach with "
166
            "global variables")
167

168
    # This is just checked for additional safety - normally the execution
169
    # of mock script has failed due to missing global variables.
170
    # Note that variables from the mock script are set only after exec_module()
UNCOV
171
    if not hasattr(module, 'setup'):
×
172
        raise NotCacheable(
×
173
            f"Mock script {file_path} does not have a setup() function")
174

175

176
def script_error(file_path, exc):
2✔
177
    """
178
    Return a MockScriptError exception object with the current traceback in its
179
    exception message, ready to be displayed.
180
    """
UNCOV
181
    if isinstance(exc, pywbem.Error):
×
182
        new_exc = MockScriptError(f"Mock script {file_path} failed: {exc}")
×
183
    else:
UNCOV
184
        tb = traceback.format_exception(*sys.exc_info())
×
UNCOV
185
        fail_list = "\n".join(tb)
×
UNCOV
186
        new_exc = MockScriptError(
×
187
            f"Mock script {file_path} failed:\n{fail_list}")
UNCOV
188
    new_exc.__cause__ = None
×
UNCOV
189
    return new_exc
×
190

191

192
def get_modpath(file_path):
2✔
193
    """
194
    Return the dotted module path to be used for a mock script.
195
    """
UNCOV
196
    this_modpath = __name__  # Dotted module path of this module
×
UNCOV
197
    file_base = os.path.splitext(os.path.basename(file_path))[0]
×
UNCOV
198
    modpath = this_modpath + '.' + file_base
×
UNCOV
199
    return modpath
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc