/
_mockmofwbemconnection.py
381 lines (310 loc) · 14.6 KB
/
_mockmofwbemconnection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#
# (C) Copyright 2018 InovaDevelopment.comn
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Karl Schopmeyer <inovadevelopment.com>
#
"""
Mock support for the WBEMConnection class to allow pywbem users to test the
pywbem client without requiring a running WBEM server.
For documentation, see mocksupport.rst.
"""
from pywbem import CIMError, CIM_ERR_INVALID_PARAMETER, \
CIM_ERR_NOT_FOUND, CIM_ERR_INVALID_SUPERCLASS
from pywbem._nocasedict import NocaseDict
from pywbem._mof_compiler import BaseRepositoryConnection
from pywbem._utils import _format
from ._resolvermixin import ResolverMixin
__all__ = []
class _MockMOFWBEMConnection(ResolverMixin, BaseRepositoryConnection):
"""
Create an adaption of the MOF compiler BaseRepositoryConnection class to
interface through the client API to the FakedWBEMConnection acting as the
interface to the CIM repository for mocking a WBEM server
This class adaption is private to pywbem_mock
"""
def __init__(self, faked_conn_object):
"""
Initialize the connection.
Parameters:
faked_conn_object (:class:`~pywbem_mock.FakedWBEMConnection`):
The object providing the CIM repository.
"""
self.classes = NocaseDict()
self.conn = faked_conn_object
self.conn_id = self.conn.conn_id
def _getns(self):
"""
:term:`string`: Return the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead.
"""
return self.conn.default_namespace
def _setns(self, value):
"""
Set the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead.
"""
self.conn.default_namespace = value
getns = _getns # for compatibility, used in the MOF compiler
default_namespace = property(
_getns, _setns, None,
"""
:term:`string`: The default repository namespace to be used.
The default repository namespace is the default namespace of the
underlying repository connection if there is such an underlying
connection, or the default namespace of this object.
Initially, the default namespace of this object is 'root/cimv2'.
This property is settable. Setting it will cause the default namespace
of the underlying repository connection to be updated if there is such
an underlying connection, or the default namespace of this object.
"""
)
def EnumerateInstanceNames(self, *args, **kwargs):
"""
Not Implemented because not used with the MOF compiler.
"""
assert False, 'EnumerateInstanceNames not implemented!'
def CreateInstance(self, *args, **kwargs):
"""
Create a CIM instance in the connected client.
This method:
1. Validates properties and the class
2. Sets the instance path to None to assuming that the
conn.CreateInstance creates a complete path.
3. Passes the NewInstance to conn.CreateInstance (the client
that is connected to a repository)
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateInstance`.
"""
inst = args[0] if args else kwargs['NewInstance']
ns = kwargs.get('namespace', self.default_namespace)
# Get list of properties in class defined for this instance
cln = inst.classname
cls = self.GetClass(cln, namespace=ns, IncludeQualifiers=True,
LocalOnly=False)
cls_key_properties = [p for p, v in cls.properties.items()
if 'key' in v.qualifiers]
# Validate all key properties are in instance
for pname in cls_key_properties:
if pname not in inst.properties:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format('CreateInstance failed. Key property {0!A} in '
'class {1!A} but not in new_instance: {2!A}',
pname, cln, str(inst)))
# Insure inst.path is empty before calling CreateInstance so that
# the path is built by CreateInstance. This is logical because
# the mock environment always requires a complete path to insert
# an instance into the repository.
inst.path = None
try:
path = self.conn.CreateInstance(inst, namespace=ns)
except KeyError: # pylint: disable=try-except-raise
raise
return path
def ModifyInstance(self, *args, **kwargs):
"""
This method is used by the MOF compiler only in the course of
handling CIM_ERR_ALREADY_EXISTS after trying to create an instance.
NOTE: It does NOT support the propertylist attribute that is part
of the CIM/XML definition of ModifyInstance and it requires that
each created instance include the instance path which means that
the MOF must include the instance alias on each created instance.
"""
mod_inst = args[0] if args else kwargs['ModifiedInstance']
self.conn.ModifyInstance(mod_inst)
def DeleteInstance(self, *args, **kwargs):
"""
Not implemented because not used by the MOF compiler
"""
assert False, 'DeleteInstance not implemented!'
def GetClass(self, *args, **kwargs):
"""Retrieve a CIM class from the local classes store if it exists
there or from the client interface defined by self.conn.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetClass`.
"""
cname = args[0] if args else kwargs['ClassName']
ns = kwargs.get('namespace', self.default_namespace)
try:
cc = self.classes[ns][cname]
except KeyError:
cc = self.conn.GetClass(*args, **kwargs)
try:
self.classes[ns][cc.classname] = cc
except KeyError:
self.classes[ns] = NocaseDict({cc.classname: cc})
if 'LocalOnly' in kwargs and not kwargs['LocalOnly']:
if cc.superclass:
try:
del kwargs['ClassName']
except KeyError:
pass
if args:
args = args[1:]
super_ = self.GetClass(cc.superclass, *args, **kwargs)
for prop in super_.properties.values():
if prop.name not in cc.properties:
cc.properties[prop.name] = prop
for meth in super_.methods.values():
if meth.name not in cc.methods:
cc.methods[meth.name] = meth
return cc
def CreateClass(self, *args, **kwargs):
"""
Override the CreateClass method in BaseRepositoryConnection.
Implements creation of the class through the connected client and
also sets it in the local client (NocaseDict).
This Create class implementation is special for the MOF compiler
because it includes the logic to retrieve classes missing from the
repository but required to define a correct repository. That includes
superclasses and other classes referenced by the class being defined.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.CreateClass`.
"""
cc = args[0] if args else kwargs['NewClass']
ns = kwargs.get('namespace', self.default_namespace)
if cc.superclass:
# Since this may cause additional GetClass calls
# IncludeQualifiers = True insures reference properties on
# instances with aliases get built correctly.
try:
self.GetClass(cc.superclass, namespace=ns, LocalOnly=True,
IncludeQualifiers=True)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_SUPERCLASS,
_format("Cannot create class {0!A} in namespace "
"{1!A} because its superclass {2!A} does "
"not exist",
cc.classname, self.getns(), cc.superclass),
conn_id=self.conn_id)
raise
# Class created in local repo before tests because that allows
# tests that may actually include this class to succeed in
# the test code below without previously putting the class into
# the repository defined by conn.
try:
# The following generates an exception for each new ns
self.classes[ns][cc.classname] = cc
except KeyError:
self.classes[ns] = NocaseDict([(cc.classname, cc)])
# Validate that references and embedded instance properties, methods,
# etc. have classes that exist in repo. This also institates the
# mechanism that gets insures that prerequisite classes are inserted
# into the repo.
objects = list(cc.properties.values())
for meth in cc.methods.values():
objects += list(meth.parameters.values())
for obj in objects:
# Validate that reference_class exists in repo
if obj.type == 'reference':
try:
self.GetClass(obj.reference_class, namespace=ns,
LocalOnly=True, IncludeQualifiers=True)
except KeyError:
raise CIMError(CIM_ERR_INVALID_PARAMETER,
obj.reference_class)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} referenced by element {1!A} "
"of class {2!A} in namespace {3!A} does "
"not exist",
obj.reference_class, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
# NOTE: Only delete when this is total failure
del self.classes[ns][cc.classname]
raise
elif obj.type == 'string':
if 'EmbeddedInstance' in obj.qualifiers:
eiqualifier = obj.qualifiers['EmbeddedInstance']
# The DMTF spec allows the value to be None
if eiqualifier.value is None:
continue
try:
self.GetClass(eiqualifier.value, namespace=ns,
LocalOnly=True,
IncludeQualifiers=False)
except KeyError:
raise CIMError(CIM_ERR_INVALID_PARAMETER,
eiqualifier.value)
except CIMError as ce:
if ce.status_code == CIM_ERR_NOT_FOUND:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
_format("Class {0!A} specified by "
"EmbeddInstance qualifier on element "
"{1!A} of class {2!A} in namespace "
"{3!A} does not exist",
eiqualifier.value, obj.name,
cc.classname, self.getns()),
conn_id=self.conn_id)
# Only delete when total failure
del self.classes[ns][cc.classname]
raise
self.conn.CreateClass(cc, namespace=ns)
def ModifyClass(self, *args, **kwargs):
"""
This method is used by the MOF compiler only in the course of
handling CIM_ERR_ALREADY_EXISTS after trying to execute CreateClass.
It executes a ModifyClass on the connected client
"""
modified_class = args[0] if args else kwargs['ModifiedClass']
ns = kwargs.get('namespace', self.default_namespace)
self.conn.ModifyClass(modified_class, namespace=ns)
def DeleteClass(self, *args, **kwargs):
"""
Not implemented because not called from the MOF compiler
"""
assert False, 'DeleteClass not implemented!'
def EnumerateQualifiers(self, *args, **kwargs):
"""Enumerate the qualifier types throught the connected client.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.EnumerateQualifiers`.
"""
rv = self.conn.EnumerateQualifiers(*args, **kwargs)
return rv
def GetQualifier(self, *args, **kwargs):
"""Retrieve a qualifier type from the connected client.
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.GetQualifier`.
"""
qualname = args[0] if args else kwargs['QualifierName']
ns = kwargs.get('namespace', self.default_namespace)
try:
qual = self.conn.GetQualifier(qualname, namespace=ns)
except KeyError: # pylint: disable=try-except-raise
raise
return qual
def SetQualifier(self, *args, **kwargs):
"""Create or modify a qualifier type in the connected client
For a description of the parameters, see
:meth:`pywbem.WBEMConnection.SetQualifier`.
"""
qual = args[0] if args else kwargs['QualifierDeclaration']
ns = kwargs.get('namespace', self.default_namespace)
self.conn.SetQualifier(qual, namespace=ns)
def DeleteQualifier(self, *args, **kwargs):
"""
Not implemented because not called from the MOF compiler
"""
assert False, 'DeleteQualifier not implemented!'