9. Mock WBEM server

Experimental: New in pywbem 0.12.0 as experimental.

9.1. Overview

The ‘pywbem_mock’ module of pywbem provides a mock WBEM server that enables using the pywbem client library without a real WBEM server. This is useful for testing the pywbem client library itself as well as for the development and testing of Python programs that use the pywbem client library.

The pywbem_mock.FakedWBEMConnection class establishes an in-process mock WBEM server and represents a faked connection to that mock WBEM server. That class acts as both the client API and as an API for managing the mocked WBEM server.

The pywbem_mock.FakedWBEMConnection class is a subclass of pywbem.WBEMConnection and replaces its internal methods that use HTTP/HTTPS to communicate with a WBEM server with methods that communicate with the mock WBEM server. As a result, the operation methods of FakedWBEMConnection are those inherited from WBEMConnection, so they have exactly the same input parameters, output parameters, return values, and even most of the raised exceptions, as when invoked on a WBEMConnection object against a real WBEM server.

The mock WBEM server has an in-memory repository of CIM objects (the CIM repository). Each FakedWBEMConnection object creates its own CIM repository that contains the same kinds of CIM objects a WBEM server repository contains: CIM classes, CIM instances, and CIM qualifier declarations types, contained in CIM namespaces. Because FakedWBEMConnection operates only on the CIM repository, the class does not have any connection- or security-related constructor parameters.

Like WBEMConnection, FakedWBEMConnection has a default CIM namespace that is created in the CIM repository upon FakedWBEMConnection object creation. Additional namespaces in the CIM repository can be created with add_namespace() .

The CIM repository must contain the CIM classes, CIM instances and CIM qualifier declaration types that are needed for the operations that are invoked. This results in a behavior of the mock WBEM server that is close to the behavior of the operations of a real WBEM server. FakedWBEMConnection has methods that provide for adding CIM classes, instances and qualifier types to its CIM repository by providing them as CIM objects, or by compiling MOF. See Building a mocked CIM repository for details.

The following example demonstrates setting up a mock WBEM server, adding several CIM objects defined in a MOF string to its CIM repository, and executing WBEM operations on the faked connection:

import pywbem
import pywbem_mock

# MOF string defining qualifiers, class, and instance
mof = '''
    Qualifier Key : boolean = false,
        Scope(property, reference),
        Flavor(DisableOverride, ToSubclass);
    Qualifier Description : string = null,
        Scope(any),
        Flavor(EnableOverride, ToSubclass, Translatable);
    Qualifier In : boolean = true,
        Scope(parameter),
        Flavor(DisableOverride, ToSubclass);

        [Description ("This is a dumb test class")]
    class CIM_Foo {
            [Key, Description ("This is key prop")]
        string InstanceID;
            [Description ("This is some simplistic data")]
        Uint32 SomeData;
            [Description ("This is a method without parameters")]
        string Fuzzy();
            [Description ("This is a second method with parameter")]
        uint32 Delete([IN, Description('blahblah']
          boolean Immediate);
    };

    instance of CIM_Foo as $I1 { InstanceID = "I1"; SomeData=3 };
    '''

# Create a faked connection including a mock WBEM server with a CIM repo
conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/cimv2')

# Compile the MOF string and add its CIM objects to the default namespace
# of the CIM repository
conn.compile_mof_string(mof)

# Perform a few operations on the faked connection:

# Enumerate top-level classes in the default namespace (without subclasses)
classes = conn.EnumerateClasses();
for cls in classes:
    print(cls.tomof())

# Get the 'Description' qualifier type in the default namespace
qd = conn.GetQualifier('Description')

# Enumerate subclasses of 'CIM_Foo' in the default namespace (without subclasses)
classes2 = conn.EnumerateClasses(classname='CIM_Foo')

# Get 'CIM_Foo' class in the default namespace
my_class = conn.GetClass('CIM_Foo')

# Get a specific instance of 'CIM_Foo' in the default namespace
inst = conn.GetInstance(CIMInstanceName('CIM_Foo', {'InstanceID': "I1"})

The mock WBEM server supports:

  1. All of the WBEMConnection operation methods that communicate with the WBEM server (see below for the operations supported and their limitations).
  2. Multiple CIM namespaces and a default namespace on the faked connection.
  3. Gathering time statistics and delaying responses for a predetermined time.
  4. WBEMConnection logging except that there are no HTTP entries in the log.
  5. User-defined providers that replace the the default providers specific request methods, CIM classes, and namespaces. See User-defined providers.

The mock WBEM server does NOT support:

  1. CIM-XML protocol security and security constructor parameters of WBEMConnection.
  2. Processing of queries defined for ExecQuery() in languages like CQL and WQL. The mocked operation parses only the very general portions of the query for class/instance name and properties.
  3. Filter processing of FQL (see DSP0212) the Filter Query Language parameter QueryFilter used by the Open… operations because it does not implement the parser/processor for the FQL language. It returns the same data as if the filter did not exist.
  4. Providing data in the trace variables for last request and last reply in WBEMConnection: last_request, last_raw_request, last_reply, last_raw_reply, last_request_len, or last_reply_len.
  5. Log entries for HTTP request and response in the logging support of WBEMConnection, because it does not actually build the HTTP requests or responses.
  6. Generating CIM indications.
  7. Some of the functionality that may be implemented in real WBEM servers such as the __Namespace__ class/provider. Note that such capabilities can be at least partly built on top of the existing capabilities by implementing user-defined providers. Thus the CIM_Namespace class is supported with the user defined provider in the pywbem_mock directory but only registered if the user wants to use the provider.
 +----------------------------------+
 |                                  |
 | +------------------------------+ |           +-------------+
 | |                              | |           |             |
 | | WBEM Server Mock Methods     | |           | Main        |
 | |                              | |           | Provider    |
 | |            All other Requests+------------>+             |
 | |  CreateInstance, ModifyInst  +------+      | Class ,assoc|
 | |  DeleteInstance, InvokeMeth  | |    |      | some inst   |
 | +------------^-----------------+ |    |      | requests    +--+
 |              |                   |    |      +-------------+  |
 | +------------+-----------------+ |    |                       |
 | | WBEM Server Mock Interface   | |    |      +-------------+  |     +-----------+
 | |                              | |    |      |             |  |     | Instance  |
 | +------------^-----------------+ |    |      | Provider    |  |     | Write     |
 |              |                   |    |      | Dispatcher  |  |     | Provider  |
 |              |                   |    |      |             +------->+ (Default) |
 |              |                   |    |      | Dispatches  |  |     +-|---|-----+       +----------+
 | +------------+-----------------+ |    |      | methods to  |  | +-----|   |-------------+ User     |
 | |                              | |    +----->+ default or  +----------------------------> Instance |
 | |  Client API request methods  | |           | registered  |  | |                       | Providers|
 | |  from WBEM Connection        | |           | user        |  | |   +------------+      |          +-----+
 | |                              | |           | providers   |  | |   |            |      +----------+     |
 | |   *CreateClass, etc.         | |           |             +------->+ Method     |                       |
--->                              | |           |             |  | |   | Provider   |                       |
 | |                              | |           |             |  | |   | (Default)  |                       |
 | |                              | |           +-----------+-+  | |   +-----|------+                       |
 | +------------------------------+ |                       |    | |         |------------------------+     |
 | +------------------------------+ |                       +-------------------------------> User    |     |
 | |  Mock Environment management | |                            | |                        | Method  |     |
 | |  methods                     | |                            | |                        | Providers     |
 | |  * Mof Compiler, add objects | |                            | |                        |         |     |
 | |  * Manage namespaces         | |                            | |                        +---------+     |
 | |  * Register user providers   +---------+    +---------------v-V----------------------------------+     |
 | +------------------------------+ |       |    |                                                    |     |
 |  FakedWBEMConnection             |       +---->          CIM Repository                            <-----+
 +----------------------------------+            |                                                    |
                                                 +----------------------------------------------------+

Diagram of flow of requests operations through mocker

9.2. WBEM operations of a mock WBEM server

The pywbem_mock.FakedWBEMConnection class supports the same WBEM operations that are supported by the pywbem.WBEMConnection class and in addition a set of methods for setting up its mocked CIM repository, and for registering user-defined providers for selected WBEM operations.

These faked WBEM operations generally adhere to the behavior requirements defined in DSP0200 for handling input parameters and returning a result.

The faked WBEM operations get the data to be returned from the CIM repository of the mock WBEM server, and put the data provided in operation parameters that modify objects (create, modify, and delete operations) into the CIM repository.

However, because the pywbem mock support is only a simulation of a WBEM server and intended to be used primarily for testing, there are limitations and differences between the behavior of the faked WBEM operations and a real WBEM server.

The descriptions below describe differences between the faked WBEM operations of the pywbem mock support and the operations of a real WBEM server, and the effects of the operation modes of the CIM repository.

9.2.1. Faked instance operations

The operations that retrieve instances require instances in the repository for the instances to be recovered and that the classes for these instances exist in the repository.

  • GetInstance: Behaves like GetInstance(). Returns an instance defined by the instance name input parameter if that instance exists in the repository.

  • EnumerateInstances: Behaves like EnumerateInstances(), returning all instances of the CIM class defined on input and subclasses of this class filtered by the optional attributes for property names, etc.

  • EnumerateInstanceNames: Behaves like EnumerateInstances(), Returns the instance name of all instances of the pywbem.CIMClass defined on input and subclasses of this class.

  • CreateInstance: Behaves like CreateInstance().

    Creates the defined instance in the CIM repository.

    If there is no user-defined provider (see User-defined providers)for the class defined in the NewInstance parameter operation requires that all key properties be specified in the new instance since the CIM repository has no support for dynamically setting key properties and all key properties are required to get the newly defined instance with other requests. If a user-defined provider exists for the class, the behavior depends on that provider.

  • ModifyInstance: Behaves like ModifyInstance(). Modifies the instance defined by the instance name provided on input if that instance exists in the repository. It modifies only the properties defined by the instance provided and will not modify any key properties. If there is a user-defined provider defined for this operation, that provider may modify the default behavior.

  • DeleteInstance: Behaves like DeleteInstance(). Deletes the instance defined by the instance name provided on input if that instance exists. If there is a user-defined provider defined for this operation, that provider may modify the default behavior.

  • ExecQuery: This operation is not currently implemented.

See User-defined providers for more information on writing a user-defined provider.

9.2.2. Faked association operations

The faked association operations support both instance-level use and class-level requests. Class-level use requires the CIM repository to be in full mode, while instance-level use works in both operation modes of the CIM repository.

  • AssociatorNames: Behaves like AssociatorNames(), with the following requirements: The source, target, and association classes and their subclasses must exist in the CIM repository for both class-level use and instance-level use.
  • Associators: Behaves like Associators(), with the requirements described for AssociatorNames, above.
  • ReferenceNames: Behaves like ReferenceNames(), with the requirements described for AssociatorNames, above.
  • References: Behaves like References(), with the requirements described for AssociatorNames, above.

9.2.3. Faked method invocation operation

The faked method invocation operation (InvokeMethod) behaves like InvokeMethod(), but because of the nature of InvokeMethod, the user must provide an implementation of InvokeMethod based on the API defined in InvokeMethod().

NOTE: InvokeMethod is the method name pywbem and other clients and WBEM servers use for what the DMTF defines as extrinsic methods.

See User-defined providers for more information on writing a user-defined provider.

9.2.4. Faked pull operations

The faked pull operations behave like the pull operations of WBEMConnection, with the following exceptions:

  • The filter query related parameters FilterQuery and FilterQueryLanguage are ignored and no such filtering takes place.
  • The ContinueOnError parameter is ignored because injecting an error into the processing of the pull operations is not supported by the pywbem mock support, so no failures can happen during the processing of the pull operations.
  • The OperationTimeout parameter is currently ignored. As a result, there will be no timeout if the response_delay property is set to a time larger than the OperationTimeout parameter.

The faked pull operations are:

9.2.5. Faked iter operations

The iter operations on a faked connection are in fact the iter operations on WBEMConnection, because they do not directly issue requests and responses on the connection, but instead are a layer on top of underlying operations. For example, IterEnumerateInstances invokes either pull operations (i.e. OpenEnumerateInstances followed by PullInstancesWithPath) or traditional operations (i.e. EnumerateInstances). The use of pull vs. traditional operations is controlled via the use_pull_operations init parameter of FakedWBEMConnection.

The iter operations are:

9.2.6. Faked class operations

Class operations only work if the CIM repository is in full operation mode.

  • GetClass: Behaves like GetClass(). Requires that the class to be returned is in the CIM repository.
  • EnumerateClasses: Behaves like EnumerateClasses(). Requires that the class specified in the ClassName parameter be in the CIM repository.
  • EnumerateClassNames: Behaves like EnumerateClassNames(). Requires that the class specified in the ClassName parameter be in the CIM repository.
  • CreateClass: Behaves like CreateClass(). Requires that the superclass of the new class (if it specifies one) is in the CIM repository.
  • DeleteClass: Behaves like DeleteClass(), with the following difference: This operation additionally deletes all direct and indirect subclasses of the class to be deleted, and all instances of the classes that are being deleted. Requires that the class to be deleted is in the CIM repository.
  • ModifyClass: Not currently implemented.

9.2.7. Faked qualifier declaration operations

Qualifier operations declaration include the following.

  • SetQualifier: Behaves like SetQualifier(). Requires that the specified qualifier type is in the CIM repository.
  • GetQualifier: Behaves like GetQualifier(). Requires that the specified qualifier type is in the CIM repository.
  • EnumerateQualifiers: Behaves like EnumerateQualifiers(). Requires that the qualifier types to be returned are in the CIM repository.
  • DeleteQualifier: - Not implemented.

9.3. FakedWBEMConnection class

class pywbem_mock.FakedWBEMConnection(default_namespace='root/cimv2', use_pull_operations=False, stats_enabled=False, timeout=None, response_delay=None, disable_pull_operations=None)[source]

A subclass of pywbem.WBEMConnection that mocks the communication with a WBEM server by utilizing a local in-memory CIM repository to generate responses in the same way the WBEM server would.

Experimental: New in pywbem 0.12 as experimental.

Each FakedWBEMConnection object has its own CIM repository which contains multiple CIM namespaces, and each namespace may contain CIM qualifier types (declarations), CIM classes and CIM instances.

This class provides only a subset of the init parameters of WBEMConnection because it does not have a connection to a WBEM server. It uses a faked and fixed URL for the WBEM server (http://FakedUrl) as a means of identifying the connection by users.

Logging of the faked operations is supported via the pywbem logging facility and can be controlled in the same way as for WBEMConnection. For details, see WBEM operation logging.

Some of the longer running methods of this class add time statistics to the WBEMConnection.statistics. For details on how to get the statistics, see WBEM operation statistics.

Parameters:
  • default_namespace (string) – Default namespace. This parameter has the same characteristics as the same-named init parameter of WBEMConnection.
  • use_pull_operations (bool) – Flag to control whether pull or traditional operations are used in the iter… operations. This parameter has the same characteristics as the same-named init parameter of WBEMConnection.
  • timeout (number) – This parameter has the same characteristics as the same-named init parameter of WBEMConnection.
  • stats_enabled (bool) – Flag to enable operation statistics. This parameter has the same characteristics as the same-named init parameter of WBEMConnection.
  • response_delay (number) –

    Artifically created delay for each operation, in seconds. This must be a positive number. Delays less than a second or other fractional delays may be achieved with float numbers. None disables the delay.

    Note that the response_delay property can be used to set this delay subsequent to object creation.

  • disable_pull_operations (bool) –

    Flag to allow user to disable the pull operations ( Open… and Pull.. requests). The default is None which enables pull operations to execute. Setting the flag to True causes pull operations to raise CIMError(CIM_ERR_NOT_SUPPORTED).

    The disable_pull_operations property can be used to set this variable.

Methods

AssociatorNames Retrieve the instance paths of the instances associated to a source instance, or the class paths of the classes associated to a source class.
Associators Retrieve the instances associated to a source instance, or the classes associated to a source class.
CloseEnumeration Close an open enumeration session, causing an early termination of an incomplete enumeration session.
CreateClass Create a class in a namespace.
CreateInstance Create an instance in a namespace.
DeleteClass Delete a class.
DeleteInstance Delete an instance.
DeleteQualifier Delete a qualifier type (= qualifier declaration).
EnumerateClassNames Enumerate the names of subclasses of a class, or of the top-level classes in a namespace.
EnumerateClasses Enumerate the subclasses of a class, or the top-level classes in a namespace.
EnumerateInstanceNames Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.
EnumerateInstances Enumerate the instances of a class (including instances of its subclasses) in a namespace.
EnumerateQualifiers Enumerate the qualifier types (= qualifier declarations) in a namespace.
ExecQuery Execute a query in a namespace.
GetClass Retrieve a class.
GetInstance Retrieve an instance.
GetQualifier Retrieve a qualifier type (= qualifier declaration).
InvokeMethod Invoke a method on a target instance or on a target class.
IterAssociatorInstancePaths Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result.
IterAssociatorInstances Retrieve the instances associated to a source instance, using the Python generator idiom to return the result.
IterEnumerateInstancePaths Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.
IterEnumerateInstances Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.
IterQueryInstances Execute a query in a namespace, using the Python generator idiom to return the result.
IterReferenceInstancePaths Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result.
IterReferenceInstances Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result.
ModifyClass Modify a class.
ModifyInstance Modify the property values of an instance.
OpenAssociatorInstancePaths Open an enumeration session to retrieve the instance paths of the instances associated to a source instance.
OpenAssociatorInstances Open an enumeration session to retrieve the instances associated to a source instance.
OpenEnumerateInstancePaths Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.
OpenEnumerateInstances Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace.
OpenQueryInstances Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result.
OpenReferenceInstancePaths Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance.
OpenReferenceInstances Open an enumeration session to retrieve the association instances that reference a source instance.
PullInstancePaths Retrieve the next set of instance paths from an open enumeration session.
PullInstances Retrieve the next set of instances (without instance paths) from an open enumeration session.
PullInstancesWithPath Retrieve the next set of instances (with instance paths) from an open enumeration session.
ReferenceNames Retrieve the instance paths of the association instances that reference a source instance, or the class paths of the association classes that reference a source class.
References Retrieve the association instances that reference a source instance, or the association classes that reference a source class.
SetQualifier Create or modify a qualifier type (= qualifier declaration) in a namespace.
add_cimobjects Add CIM classes, instances and/or CIM qualifier types (declarations) to the specified CIM namespace of the CIM repository.
add_namespace Add a CIM namespace to the CIM repository of the faked connection.
add_operation_recorder Experimental: Add an operation recorder to this connection.
compile_mof_file Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the CIM repository.
compile_mof_string Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the CIM repository.
compile_schema_classes Compile the classes defined by class_names and all of their dependences.
display_registered_providers Display information on the currently registered providers.
display_repository Display the namespaces and objects in the CIM repository in one of multiple formats to a destination.
find_interop_namespace Find the Interop namespace in the CIM repository, or return None.
install_namespace_provider FakedWBEMConnection user method to install the namespace provider in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace
is_interop_namespace Tests if a namespace name is a valid Interop namespace name.
is_subclass Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified namespace.
operation_recorder_reset Experimental: Low-level method used by the operation-specific methods of this class.
operation_recorder_stage_pywbem_args Experimental: Low-level method used by the operation-specific methods of this class.
operation_recorder_stage_result Experimental: Low-level method used by the operation-specific methods of this class.
register_provider Register the provider object for specific namespaces and CIM classes.
remove_namespace Remove a CIM namespace from the CIM repository of the faked connection.

Attributes

ca_certs Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server.
cimrepository The mocked in-memory CIM repository.
conn_id Connection ID (a unique ID) of this connection.
creds Credentials for HTTP authentication with the WBEM server.
debug Boolean indicating that debug is enabled for this connection.
default_namespace Name of the CIM namespace to be used by default (if no namespace is specified for an operation).
disable_pull_operations Boolean flag to set option to disable the execution of the open and pull operation request handlers in the CIM repository.
host Normalized host and port number of the WBEM server, in the format host:port.
interop_namespace_names The valid Interop namespace names.
last_operation_time Elapsed time of the last operation that was executed via this connection in seconds or None.
last_raw_reply CIM-XML data of the last response received from the WBEM server on this connection, formatted as it was received (=raw).
last_raw_request CIM-XML data of the last request sent to the WBEM server on this connection, formatted as it was sent (=raw).
last_reply CIM-XML data of the last response received from the WBEM server on this connection, formatted as prettified XML.
last_reply_len The size of the HTTP body in the CIM-XML response of the last operation, in Bytes.
last_request CIM-XML data of the last request sent to the WBEM server on this connection, formatted as prettified XML.
last_request_len The size of the HTTP body in the CIM-XML request of the last operation, in Bytes.
last_server_response_time Server-measured response time of the last request, or None.
namespaces The names of the namespaces that exist in the CIM repository.
no_verification Boolean indicating that verifications are disabled for this connection.
operation_recorder_enabled Experimental: Enablement status for all operation recorders of the connection.
operation_recorders Experimental: The operation recorders of this connection.
provider_dependent_registry The registry for provider dependent files, in context of a mock script.
proxies Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server.
response_delay Artifically created delay for each operation, in seconds.
scheme Normalized scheme of the URL of the WBEM server, for example ‘http’ or ‘https’.
statistics Statistics for this connection.
stats_enabled Statistics enablement status for this connection.
timeout Timeout in seconds, for requests sent to the server.
url Normalized URL of the WBEM server.
use_pull_operations Boolean indicating that the client should attempt the use of pull operations in any Iter…() methods.
x509 X.509 client certificate and key file to be presented to the WBEM server during the TLS/SSL handshake.

Details

namespaces

The names of the namespaces that exist in the CIM repository.

Type:NocaseList of string
interop_namespace_names

The valid Interop namespace names.

Only these names may be the Interop namespace and only one Interop namespace may exist in a WBEM server environment. This list is defined in pywbem.WBEMServer.INTEROP_NAMESPACES.

Type:NocaseList of string
cimrepository

The mocked in-memory CIM repository.

The CIM repository is the data store for CIM classes, CIM instances, and CIM qualifier declarations, all partitioned by CIM namespaces.

Type:InMemoryRepository
provider_dependent_registry

The registry for provider dependent files, in context of a mock script.

Type:ProviderDependentRegistry
response_delay

Artifically created delay for each operation, in seconds. If None, there is no delay.

This attribute is settable. For details, see the description of the same-named init parameter of this class.

Type:number
disable_pull_operations

Boolean flag to set option to disable the execution of the open and pull operation request handlers in the CIM repository. This emulates the characteristic in some CIM servers that did not implement pull operations. The default is to allow pull operations. All pull operations requests may be forbidden from executing by setting disable_pull_operations to True.

This attribute is settable. For details, see the description of the same-named init parameter of this class.

Type:bool
add_namespace(namespace)[source]

Add a CIM namespace to the CIM repository of the faked connection.

The namespace must not yet exist in the CIM repository.

Parameters:

namespace (string) – The name of the CIM namespace to be added to the CIM repository. Must not be None. Any leading or trailing slash characters are removed before the string is used to define the namespace name.

Raises:
  • ValueError – Namespace argument must not be None.
  • CIMError – CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.
remove_namespace(namespace)[source]

Remove a CIM namespace from the CIM repository of the faked connection.

The namespace must exist in the CIM repository and must be empty.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.

Raises:
  • ValueError – Namespace argument must not be None
  • CIMError – (CIM_ERR_NOT_FOUND) if the namespace does not exist in the CIM repository.
  • CIMError – (CIM_ERR_NAMESPACE_NOT_EMPTY) if the namespace is not empty.
  • CIMError – (CIM_ERR_NAMESPACE_NOT_EMPTY) if attempting to delete the default connection namespace. This namespace cannot be deleted from the CIM repository
is_interop_namespace(namespace)[source]

Tests if a namespace name is a valid Interop namespace name.

This method does not access the CIM repository for this test; it merely compares the specified namespace name against the list of valid Interop namespace names returned by interop_namespace_names().

Parameters:namespace (string) – The namespace name that is to be tested.
Returns:Indicates whether the namespace name is a valid Interop namespace name.
Return type:bool
find_interop_namespace()[source]

Find the Interop namespace in the CIM repository, or return None.

The Interop namespace is identified by comparing all namespace names in the CIM repository against the list of valid Interop namespace names returned by interop_namespace_names().

Returns:The name of the Interop namespace if one exists in the CIM repository or otherwise None.
Return type:string
install_namespace_provider(interop_namespace, schema_pragma_file=None, verbose=None)[source]

FakedWBEMConnection user method to install the namespace provider in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace

Because this provider requires a set of classes from the DMTF schema, the schema_pragma_file install the schema is required.

This method should only be called once at the creation of the mock environment.

Parameters:
  • interop_namespace (string) – The Interop namespace defined for this environment
  • schema_pragma_file (string) –

    File path defining a CIM schema pragma file for the set of CIM classes that make up a schema such as the DMTF schema. This file must contain a pragma statement for each of the classes defined in the schema.

    If None, no attempt is made to any CIM classes required for the provider and it is assumed that the CIM classes are already installed

  • verbose (bool) – If True, displays progress information as providers are installed.
Raises:
  • CIMError – with status code appropriate for any
  • error encountered in the installation of the provider.
compile_mof_file(mof_file, namespace=None, search_paths=None, verbose=None)[source]

Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the CIM repository.

If the namespace does not exist, CIMError with status CIM_ERR_INVALID_NAMESPACE is raised.

This method supports all MOF pragmas, and specifically the include pragma.

If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises CIMError.

If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises CIMError.

In all cases where this method raises an exception, the CIM repository remains unchanged.

Parameters:
  • mof_file (string) – Path name of the file containing the MOF definitions to be compiled.
  • namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
  • search_paths (iterable of string) – An iterable of directory path names where MOF dependent files will be looked up. See the description of the search_path init parameter of the MOFCompiler class for more information on MOF dependent files.
  • verbose (bool) – Controls whether to issue more detailed compiler messages.
Raises:
compile_mof_string(mof_str, namespace=None, search_paths=None, verbose=None)[source]

Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the CIM repository.

If the namespace does not exist, CIMError with status CIM_ERR_INVALID_NAMESPACE is raised.

This method supports all MOF pragmas, and specifically the include pragma.

If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises CIMError.

If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises CIMError.

In all cases where this method raises an exception, the CIM repository remains unchanged.

Parameters:
  • mof_str (string) – A string with the MOF definitions to be compiled.
  • namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
  • search_paths (iterable of string) – An iterable of directory path names where MOF dependent files will be looked up. See the description of the search_path init parameter of the MOFCompiler class for more information on MOF dependent files.
  • verbose (bool) – Controls whether to issue more detailed compiler messages.
Raises:
compile_schema_classes(class_names, schema_pragma_files, namespace=None, verbose=False)[source]

Compile the classes defined by class_names and all of their dependences. The class names must be classes in the defined schema and with pragma statements in a schema pragma file. Each schema pragma file in the schema_pragma_files parameter must be in a directory that also encompasses the MOF files for all of the classes defined in the schema pragma file and the dependencies of those classes. While the relative paths of all of the CIM class files is defined in the schema_pragma_file the pywbem MOF compiler may also search for dependencies (ex. superclasses, references, etc.) that are not specifically listed in the class_names and the path of the schema_pragma_file is the top level directory for that search. The mof schema directory must include:

  1. Qualifier declarations defined in a single file with the name qualifiers.mof defined within the directory defined by the schema_mof_dir parameter
  2. The file schema_pragma_file that defines the location of all of the CIM class files within the a schema mof directory hierarchy. This is the schema_pragma_file attribute of the DMTFCIMSchema class.
  3. The MOF files, one for each class, for the classes that could be compiled within the directory hierarchy defined by schema_mof_dir.

Only the leaf class names need be included in the class_names list since the compiler will find all dependencies as part of the dependency resolution for the compile of each class in class_names.

Parameters:
  • class_names (string or list of string) – Class names of the classes to be compiled. These class names must be a subset of the classes defined in schema_pragma_file.
  • schema_pragma_files (string or list of string) – Relative or absolute file path(s) of schema pragma files that include a MOF pragma include statement for each CIM class to be compiled. This file path is available from pywbem_mock.DMTFCIMSchema.schema_pragma_file.
  • namespace (string) – Namespace into which the classes and qualifier declarations will be installed.
  • verbose (bool) – If True, progress messages are output to stdout as the schema is downloaded and expanded. Default is False.
Raises:
  • MOFCompileError – For errors in MOF parsing, finding MOF dependencies or issues with the CIM repository.
  • CIMError – Other errors relating to the target server environment.
add_cimobjects(objects, namespace=None)[source]

Add CIM classes, instances and/or CIM qualifier types (declarations) to the specified CIM namespace of the CIM repository.

This method adds a copy of the objects presented so that the user may modify the objects without impacting the repository.

If the namespace does not exist, CIMError with status CIM_ERR_INVALID_NAMESPACE is raised.

The method imposes very few limits on the objects added. It does require that the superclass exist for any class added and that instances added include a path component. If the qualifier flavor attributes are not set, it sets them to those defined in the Qualifier Declarations if those exist.

If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method fails, and the CIM repository remains unchanged.

If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method fails, and the CIM repository remains unchanged.

Parameters:
  • objects (CIMClass or CIMInstance or CIMQualifierDeclaration, or list of them) – CIM object or objects to be added to the CIM repository. The list may contain different kinds of CIM objects.
  • namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
Raises:
  • ValueError – Invalid input CIM object in objects parameter.
  • TypeError – Invalid type in objects parameter.
  • CIMError – CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.
  • CIMError – Failure related to the CIM objects in the CIM repository.
display_repository(namespaces=None, dest=None, summary=False, output_format='mof')[source]

Display the namespaces and objects in the CIM repository in one of multiple formats to a destination.

Parameters:
  • namespaces (string or list of string) – Limits display output to the specified CIM namespace or namespaces. If None, all namespaces of the CIM repository are displayed.
  • dest (string) – File path of an output file. If None, the output is written to stdout.
  • summary (bool) – Flag for summary mode. If True, only a summary count of CIM objects in the specified namespaces of the CIM repository is produced. If False, both the summary count and the details of the CIM objects are produced.
  • output_format (string) – Output format, one of: ‘mof’, ‘xml’, or ‘repr’.
register_provider(provider, namespaces=None, schema_pragma_files=None, verbose=None)[source]

Register the provider object for specific namespaces and CIM classes. Registering a provider tells the FakedWBEMConnection that the provider implementation provided with this method as the provider parameter is to be executed as the request response method for the namespaces defined in the namespaces parameter, the provider type defined in the ‘provider_type` attribute of the provider and the class(es) defined in the provider provider_classnames attribute of the provider.

The provider registration process includes:

  1. Validation that the namespaces defined for the provider exist.
  2. Validation that the superclass of the provider is consistent with the provider_type attribute defined in the provider.
  3. Installation of any CIM classes defined by the provider provider_classnames attribute including dependencies for these classes using the schema_pragma_files parameter to define the MOF compiler search directories for dependencies.
  4. Adding the provider to the registry of user_providers so that any of the request methods defined for the provider_type are passed to this provider in place of the default request processors.
  5. Execute post_register_setup() call to the provider to allow the provider to perform any special setup functionality.

Providers can only be registered for the following request response methods:

  1. provider_type = ‘instance’: defines methods for CreateInstance, ModifyInstance, and DeleteInstance requests within a subclass of the InstanceWriteProvider class.
  2. provider_type = ‘method’: defines a InvokeMethod method within a subclass of the MethodProvider class.

Each classname in a particular namespace may have at most one provider registered

Parameters:
  • provider (instance of subclass of pywbem_mock.InstanceWriteProvider or pywbem_mock.MethodProvider) – An instance of the user provider class which is a subclass of pywbem_mock.InstanceWriteProvider. The methods in this subclass override the corresponding methods in InstanceWriteProvider. The method call parameters must be the same as the defult method in InstanceWriteProvider and it must return data in the same format if the default method returns data.
  • namespaces (string or list of string) –

    Namespace or namespaces for which the provider is to be registered.

    If None, the default namespace of the connection will be used.

  • schema_pragma_files (string or list of string) –

    File paths defining a schema pragma file MOF for the set of CIM classes that make up a schema such as the DMTF schema. These files must contain include pragma statements defining the file location of the classes to be compiled for the defined provider and for any dependencies required to compile those classes. The directory containing each schema pragma file is passed to the MOF compiler as the search path for compile dependencies.

    See pywbem.MOFCompiler for more information on the search_paths parameter.

  • verbose (bool) – Flag to enable detailed display of actions
Raises:
  • TypeError – Invalid provider_type retrieved from provider or provider_type does not match superlclass or the namespace parameter is invalid.
  • ValueError – Provider_type retrieved from provider is not a valid string.
  • ValueError – Classnames parameter retrieved from provider not a valid string or iterable or namespace does not exist in repository.
display_registered_providers()[source]

Display information on the currently registered providers.

Parameters:dest (string) – File path of an output file. If None, the output is written to stdout.

9.4. Building a mocked CIM repository

The CIM repository of a mock WBEM server needs to contain the CIM namespaces, and within them, the CIM qualifier declarations, CIM classes, and CIM instances required by the user. These are created as part of the setup of any particular pywbem mock environment. Thus, if the user only requires CIM_ComputerSystem in a particular namespace, only that class and its dependent classes and qualifier declarations need be in that namespace in the CIM repository, along with instances of the classes that will satisfy the client methods executed.

The classes FakedWBEMConnection and DMTFCIMSchema provide the tools to build the CIM repository.

CIM namespaces are created in the CIM repository by defining a default namespace for the FakedWBEMConnection object, and by using the add_namespace() method to create additional namespaces.

There are multiple ways to add CIM objects to a target namespace of the CIM repository:

  • From CIM objects, using the add_cimobjects() method.

    The specified CIM objects are added to or updated in a target namespace of the CIM repository. Dependent classes and qualifier types of these objects must already exist in the target namespace.

  • From definitions of the CIM objects in a MOF string or a MOF file, using the compile_mof_string() or compile_mof_file() methods.

    The CIM objects defined in the MOF are added to or updated in a target namespace of the CIM repository. Dependent classes and qualifier types of these objects must already exist in the target namespace.

  • From CIM class names and a schema search path containing the MOF files of one or more schemas, using the compile_schema_classes() method.

    The schema MOF files can either be provided by the user, or the DMTF CIM schema can be automatically downloaded from the DMTF using the DMTFCIMSchema() class.

    The specified CIM classes are added to or updated in a target namespace of the CIM repository, and their dependent classes and qualifier types are added to the target namespace from the schemas in the search path as needed.

    The dependent classes and qualifier types are determined automatically and recursively. This includes superclasses, reference classes (used in reference properties and reference parameters), and embedded classes (i.e. classes referenced through the EmbeddedInstance qualifier). Thus, a user building a CIM repository does not have to track down those dependent classes and qualifier types, and instead only needs to know the schema(s) to be used and the creation classes for any CIM instances. This also means that there is normally no reason to compile the complete schema which is much larger than the classes that are minimally needed.

It may take a combination of all of the above methods to build a CIM repository that satisfies a particular usage requirement. A typical approach for building a CIM repository is:

  1. Establish the MOF subtrees for the schema(s) needed. That can be a downloaded version of the DMTF CIM schema, local modifications to a version of the DMTF CIM schema, user-defined schemas including schemas derived from the DMTF CIM schema, or a combination thereof.
  2. Create the CIM namespaces needed, either as the default namespace or by adding namespaces, including the interop namespace.
  3. For each CIM namespace needed, create the set of needed CIM classes and qualifier types by using the compile_schema_classes() method and specifying the set of creation classes of the CIM instances that are intended to be added, and specifying the pragma MOF files of the schema(s) added in step 1 as a schema search path.
  4. For each CIM namespace needed, create the set of needed CIM instances by defining and compiling instance MOF, or by creating and adding CIMInstance objects, or both. Often defining MOF is easier for this because it simplifies the definition of association instances with the instance alias.
  5. Register user-defined providers such as the CIMNamespaceProvider or user-written providers for the creation classes of the CIM instances that have non-default instance write behavior or that need CIM methods to be supported. See User-defined providers for details.

9.4.1. Example: Set up qualifier types and classes in DMTF CIM schema

This example creates a mock WBEM server using root/interop as the default namespace and compiles the classes defined in the list ‘classes’ from DMTF schema version 2.49.0 into the CIM repository along with all of the qualifier types defined by the DMTF CIM schema and any dependent classes (superclasses, etc.).

import pywbem
import pywbem_mock

conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/interop')

# Leaf classes that are to be compiled along with their dependent classes
leaf_classes = ['CIM_RegisteredProfile',
                'CIM_Namespace',
                'CIM_ObjectManager',
                'CIM_ElementConformsToProfile',
                'CIM_ReferencedProfile']

# Download DMTF CIM schema version 2.49.0 into directory my_schema_dir.
schema = DMTFCIMSchema((2, 49, 0), "my_schema_dir", leaf_classes,
                       verbose=True)

# Compile the leaf classes, looking up dependent classes and qualifier
# types from the downloaded DMTF CIM schema.
conn.compile_schema_classes(leaf_classes, schema.schema_pragma_file
                            verbose=True)

# Display the resulting repository
conn.display_repository()

9.4.2. Example: Set up qualifier types and classes from MOF

This example creates a mock WBEM server and sets up its CIM repository with qualifier types and classes that are defined in a MOF string.

import pywbem
import pywbem_mock

tst_namespace = 'root/blah'
conn = pywbem_mock.FakedWBEMConnection()

# Add some qualifier types and classes to the CIM repo by compiling MOF
mof = '''
    Qualifier Key : boolean = false,
        Scope(property, reference),
        Flavor(DisableOverride, ToSubclass);

    Qualifier Association : boolean,
        Scope(class),
        Flavor(DisableOverride, ToSubclass);

    class TST_Class1 {
          [Key]
        string InstanceID;
        string Prop1;
    };

    class TST_Class2 {
          [Key]
        string InstanceID;
        string Prop2;
    };

      [Association]
    class TST_Association12 {
          [Key]
        TST_Class1 REF Ref1;
          [Key]
        TST_Class2 REF Ref2;
    };
'''
conn.compile_mof_string(mof, tst_namespace)

conn.display_repository()

Here is the output from displaying the CIM repository in the example above:

# ========Mock Repo Display fmt=mof namespaces=all =========


# NAMESPACE root/blah

# Namespace root/blah: contains 2 Qualifier Declarations

Qualifier Association : boolean,
    Scope(class),
    Flavor(DisableOverride, ToSubclass);

Qualifier Key : boolean = false,
    Scope(property, reference),
    Flavor(DisableOverride, ToSubclass);

# Namespace root/blah: contains 3 Classes

   [Association ( true )]
class TST_Association12 {

      [Key ( true )]
   TST_Class1 REF Ref1;

      [Key ( true )]
   TST_Class2 REF Ref2;

};

class TST_Class1 {

      [Key ( true )]
   string InstanceID;

   string Prop1;

};

class TST_Class2 {

      [Key ( true )]
   string InstanceID;

   string Prop2;

};

============End Repository=================

9.4.3. Example: Set up instances from single CIM objects

Based on the CIM repository content of the previous example, this example adds two class instances and one association instance from their CIM objects using the add_cimobjects() method.

c1_key = pywbem.CIMProperty('InstanceID', type='string', value='111')
c1_path = pywbem.CIMInstanceName(
    'TST_Class1',
    keybindings={c1_key.name: c1_key.value},
)
c1 = pywbem.CIMInstance(
    'TST_Class1',
    properties=[
        c1_key,
        pywbem.CIMProperty('Prop1', type='string', value='1'),
    ],
    path=c1_path,
)

c2_key = pywbem.CIMProperty('InstanceID', type='string', value='222')
c2_path = pywbem.CIMInstanceName(
    'TST_Class2',
    keybindings={c2_key.name: c2_key.value},
)
c2 = pywbem.CIMInstance(
    'TST_Class2',
    properties=[
        c2_key,
        pywbem.CIMProperty('Prop2', type='string', value='2'),
    ],
    path=c2_path,
)

a12_key1 = pywbem.CIMProperty('Ref1', type='reference', value=c1_path)
a12_key2 = pywbem.CIMProperty('Ref2', type='reference', value=c2_path)
a12_path = pywbem.CIMInstanceName(
    'TST_Association12',
    keybindings={
        a12_key1.name: a12_key1.value,
        a12_key2.name: a12_key2.value,
    },
)
a12 = pywbem.CIMInstance(
    'TST_Association12',
    properties=[
        a12_key1,
        a12_key2,
    ],
    path=a12_path,
)

conn.add_cimobjects([c1, c2, a12], tst_namespace)

conn.display_repository()

This adds the instances to the repository display of the previous example:

# Namespace root/blah: contains 3 Instances

#  Path=/root/blah:TST_Class1.InstanceID="111"
instance of TST_Class1 {
   InstanceID = "111";
   Prop1 = "1";
};

#  Path=/root/blah:TST_Class2.InstanceID="222"
instance of TST_Class2 {
   InstanceID = "222";
   Prop2 = "2";
};

#  Path=/root/blah:TST_Association12.Ref1="/:TST_Class1.InstanceID=\"111\"",Ref2="/:TST_Class2.InstanceID=\"222\""
instance of TST_Association12 {
   Ref1 = "/:TST_Class1.InstanceID=\"111\"";
   Ref2 = "/:TST_Class2.InstanceID=\"222\"";
};

9.4.4. DMTF CIM schema download support

A CIM schema is the collection of CIM qualifier declarations and CIM classes and available a single tested, coherent package with a defined major, minor, update version number. The DMTF regularly releases updates to the DMTF CIM schema that represent all of the classes approved by the DMTF. The MOF representation of a DMTF schema release is packaged as a single zip file and is available on the DMTF web site ( https://www.dmtf.org/standards/cim ).

Because CIM schemas are the source of most of the classes that a WBEM server normally implements it was important to create a simple mechanism to include the DMTF CIM classes and qualifier declarations from a CIM schema in the CIM repository of FakedWBEMConnection.

The DMTFCIMSchema class downloads the DMTF CIM schema zip file defined by version from the DMTF web site into a defined directory, unzips the MOF files into a subdirectory and makes this subdirectory available as a property of the DMTFCIMSchema object.

The implementation of this class depends on all of the qualiifiers and classes in the CIM schema having unique class names; this is always true for DMTF CIM schema releases to assure that they can be installed in the same namespace in a WBEM server repository.

Once aCIM schema is extracted into the individual MOF files it consumes considerable space since it expands to almost 3000 files. Therefore it is logical to remove all of the individual MOF files when not being used and also if the schema information is to be committed to be used in testing in an environment like github. Therefore, a method clean() removes all of the MOF files from local storage. They are restored the next time the DMTFCIMSchema object for the same version is constructed.

The DMTF maintains two versions of each released schema:

  • Final - This schema does not contain any of the schema classes that are marked experimental. It is considered the stable release.
  • Experimental - Contains the classes in the final schema plus other classes that are considered experimental. It is considered less stable and the experimental classes with the Experimental qualifier are subject to incompatible changes .

DMTFCIMSchema will install either the final or experimental schema depending on the value of the use_experimental parameter.

Because it is usually necessary to compile only a subset of the DMTF CIM classes into a CIM repository for any test, the DMTFCIMSchema class provides a build_schema_mof() method to create a list of MOF pragmans that includes only a subset of the classes in the downloaded CIM Schema. The task of listing classes to be compiled is futher simplified because the pywbem MOF compiler searches the DMTF schema for prerequisite classes (superclasses, reference classes, and EmbeddedInstance classes) so that generally only the leaf CIM classes required for the repository need to be in the class list. This speeds up the process of compiling DMTF CIM classes for any test significantly.

class pywbem_mock.DMTFCIMSchema(schema_version, schema_root_dir, use_experimental=False, verbose=False)[source]

DMTFCIMSchema represents a DMTF CIM Schema downloaded from the DMTF web site.

This class manages the download of the DMTF schema zip file and extraction of MOF files of DMTF CIM schema releases into a directory that can be used by compile_schema_classes() to compile into a CIM repository with class and qualifier declarations from the schema.

The init method downloads the schema if the schema_root_dir or the schema zip file do not exist into the directory defined by the schema_root_dir parameter and extracts the MOF files into schema_mof_dir.

If the schema zip file is already downloaded it simply sets the DMTFCIMSchema property values.

If the schema zip file was previously downloaded but schema_mof_dir does not exist the directory is created and the MOF files are extracted into this directory.

Parameters:
  • schema_version (tuple of 3 integers (m, n, u) –

    Represents the DMTF CIM schema version m.n.u where:

    • m is the DMTF CIM schema major version
    • n is the DMTF CIM schema minor version
    • u is the DMTF CIM schema update version

    This must represent a DMTF CIM schema that is available from the DMTF web site.

  • schema_root_dir (string) –

    Path name of the schema root directory into which the DMTF CIM schema zip file is downloaded and in which a subdirectory for the extracted MOF files for the schema version defined is created

    Multiple DMTF CIM schemas may be maintained in the same schema_root_dir simultaneously because the MOF for each schema is extracted into a subdirectory identified by the schema version information See schema_mof_dir.

  • use_experimental (bool) –

    If True, the experimental version of the defined DMTF schema is installed.

    If False, (default) the final version of the defined DMTF schema is installed.

  • verbose (bool) – If True, progress messages are output to stdout as the schema is downloaded and expanded. Default is False.
Raises:
  • ValueError – if the schema cannot be retrieved from the DMTF web site.
  • TypeError – if the schema_version is not a valid tuple with 3 integer components

Methods

build_schema_mof Build a string that includes the #include pragma statement for the CIM schema classes defined in class_names using the DMTF CIM schema defined by this instance of the class.
clean Remove all of the MOF files and the schema_mof_dir for the defined schema.
remove The schema_mof_dir directory is removed if it esists and the schema_zip_file is removed if it exists.

Attributes

schema_mof_dir Path name of the directory in which the DMTF CIM Schema MOF files are extracted from the downloaded zip file.
schema_pragma_file Path name of the schema pragma file for the DMTF CIM schema.
schema_root_dir Path name of the directory in which the DMTF CIM schema zip file is downloaded.
schema_version The DMTF CIM schema version as a tuple of 3 integers with major version, minor version, and update version.
schema_version_str The DMTF CIM schema version as a string in the form major version>.<minor version>.<update version>.
schema_zip_file Path name of the DMTF CIM schema zip file after being downloaded from the DMTF web site.
schema_zip_url URL of the DMTF CIM schema zip file that is downloaded from the DMTF web site.

Details

schema_version

The DMTF CIM schema version as a tuple of 3 integers with major version, minor version, and update version.

Example: (2, 49, 0) defines DMTF CIM schema version 2.49.0.

Type:tuple()
schema_version_str

The DMTF CIM schema version as a string in the form major version>.<minor version>.<update version>.

Example: “2.49.0” defines DMTF CIM schema version 2.49.0.

Type:string
schema_root_dir

Path name of the directory in which the DMTF CIM schema zip file is downloaded. The MOF files are extracted into the subdirectory indicated by schema_mof_dir.

Type:string
schema_mof_dir

Path name of the directory in which the DMTF CIM Schema MOF files are extracted from the downloaded zip file. This property can be used as the MOF compiler search path for compiling classes in the DMTF CIM schema. This directory will also contain the schema pragma file.

Type:string
schema_pragma_file

Path name of the schema pragma file for the DMTF CIM schema. This file contains #pragama include statements for all of the classes and qualifier declarations of the schema.

The classes are represented with one file per class, and the qualifier declarations are in the files qualifiers.mof and qualifiers_optional.mof.

The path name of the schema pragma file is of the general form:

<schema_mof_dir>/cim_schema_<schema_version_str>.mof

Example:

schemas/dmtf/moffinal2490/cim_schema_2.49.0.mof
Type:string
schema_zip_file

Path name of the DMTF CIM schema zip file after being downloaded from the DMTF web site.

Type:string
schema_zip_url

URL of the DMTF CIM schema zip file that is downloaded from the DMTF web site.

Type:string
__str__()[source]

Return a short string representation of the DMTFCIMSchema object for human consumption. This displays the major properties of the object.

__repr__()[source]

Return a string representation of the DMTFCIMSchema object that is suitable for debugging.

build_schema_mof(class_names)[source]

Build a string that includes the #include pragma statement for the CIM schema classes defined in class_names using the DMTF CIM schema defined by this instance of the class.

The class names in class_names can be just leaf classes within the schema . The pywbem MOF compiler will search for dependent classes including superclasses, and other classes referenced as the classes are compiled.

It builds a compilable MOF string in the form:

#pragma locale ("en_US")
#pragma include ("System/CIM_ComputerSystem.mof")
...

with a #pragma include for each class name in the class_names list.

The resulting set of #pragma statements is in the same order as the original pragmas. In some cases that could be important because the cim schema pragma file is ordered to missing dependencies and conflicts between class mof compiles

Parameters:class_names (list of string or string) –

These must be class names of classes in the DMTF CIM schema represented by this DMTFCIMSchema object. This parameter can be a string if there is only a single class name to be included.

If the returned string is compiled, the MOF compiler will search the directory defined by schema_mof_dir for classes referenced by each class in this list including super classes, classed defined by reference properties, and classes defined by an embedded-object.

Returns:Valid MOF containing pragma statements for all of the classes in schema_classes.
Return type:string
Raises:ValueError – If any of the classnames in schema_classes are not in the DMTF CIM schema installed
clean()[source]

Remove all of the MOF files and the schema_mof_dir for the defined schema. This is useful because while the downloaded schema is a single compressed zip file, it creates several thousand MOF files that take up considerable space.

The next time the DMTFCIMSchema object for this schema_version and schema_root_dir is created, the MOF file are extracted again.

remove()[source]

The schema_mof_dir directory is removed if it esists and the schema_zip_file is removed if it exists. If the schema_root_dir is empty after these removals that directory is removed.

9.4.5. In-memory CIM repository classes

The class InMemoryRepository implements a CIM repository that stores the CIM objects in memory. It contains an object store (InMemoryObjectStore) for each type of CIM object (classes, instances, qualifier declarations) and for each CIM namespace in the repository. Each object store for a CIM object type contains the CIM objects of that type in a single CIM namespace.

The CIM repository of a mock WBEM server represented by a FakedWBEMConnection object is a InMemoryRepository object that is created and destroyed automatically when the FakedWBEMConnection object is created and destroyed.

The CIM repository of a mock WBEM server is accessible through its pywbem_mock.FakedWBEMConnection.cimrepository property.

class pywbem_mock.InMemoryRepository(initial_namespace=None)[source]

A CIM repository that maintains the data in memory using the methods defined in its superclass (~pywbem_mock:BaseObjectStore). This implementation creates the repository as multi-level dictionary elements to define the namespaces and within each namespace the CIM classes, CIM instances, and CIM qualifiers in the repository.

Initialize an empty in-memory CIM repository and optionally add a namespace in the repository..

Parameters:initial_namespace – (string or None): Optional initial namespace that will be added to the CIM repository.

Methods

add_namespace Add a CIM namespace to the repository.
get_class_store Return the CIM class object store for the namespace provided.
get_instance_store Return the CIM instance object store for the namespace provided.
get_qualifier_store Return the CIM qualifier declaration object store for the namespace provided.
load Replace the data in this object with the data from the other object.
print_repository Print the CIM repository to a destination.
remove_namespace Remove a CIM namespace from the repository.
validate_namespace Validate if the namespace exists in the repository.

Attributes

namespaces The names of the namespaces that exist in this CIM repository.

Details

__repr__()[source]

Display summary of the repository

print_repository(dest=None)[source]

Print the CIM repository to a destination. This displays information on the items in the data base and is only a diagnostic tool.

Parameters:dest (string) – File path of an output file. If None, the output is written to stdout.
validate_namespace(namespace)[source]

Validate if the namespace exists in the repository. If the namespace does not exist a KeyError is raised.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Raises:
  • KeyError – If the namespace is not defined in the repository.
  • ValueError – if the namespace is None.
add_namespace(namespace)[source]

Add a CIM namespace to the repository.

The namespace must not yet exist in the CIM repository.

Parameters:namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises:ValueError – If the namespace argument is None or the namespace already exists.
remove_namespace(namespace)[source]

Remove a CIM namespace from the repository.

The namespace must exist in the repository and must be empty.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Raises:
  • ValueError – Namespace argument is None or the repository namespace is not empty.
  • KeyError – Namespace does not exist in the CIM repository.
namespaces

The names of the namespaces that exist in this CIM repository.

Note that if there were any leading or trailing slash (“/”) characters in namespace parameters used to add the namespaces to the repository, they will be removed from the namespaces returned with this property.

Type:NocaseList of string
get_class_store(namespace)[source]

Return the CIM class object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM class object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – Namespace argument is None.
  • KeyError – Namespace does not exist in the repository
get_instance_store(namespace)[source]

Return the CIM instance object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM instance object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – Namespace argument is None.
  • KeyError – Namespace argument does exist in the repository.
get_qualifier_store(namespace)[source]

Return the CIM qualifier declaration object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM qualifier declaration object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – namespace parameter is None
  • KeyError – namespace argument does exist in therepository.
load(other)[source]

Replace the data in this object with the data from the other object.

This is used to restore the object from a serialized state, without changing its identity.

class pywbem_mock.InMemoryObjectStore(cim_object_type)[source]

A store for CIM objects of a single type (CIM classes, CIM instances, or CIM qualifier declarations) that maintains its data in memory.

Methods

create Add the CIM object to the object store.
delete Delete the CIM object identified by name from the object store.
get Get with deepcopy because the pywbem .copy is only middle level and we need to completely isolate the repository.
iter_names Only copies the names for those objects that use CIMNamespaceName as the name.
iter_values Return an iterator to the CIM objects in the object store.
len Return the count of objects in this object store.
object_exists Test if the CIM object identified by name exists in the object store.
update Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

Attributes

Details

object_exists(name)[source]

Test if the CIM object identified by name exists in the object store.

Parameters:name (string or CIMInstanceName) – Name by which the object is identified in the object store.
Returns:Indicates whether the CIM object exists in the object store.
Return type:bool
get(name, copy=True)[source]

Get with deepcopy because the pywbem .copy is only middle level and we need to completely isolate the repository.

create(name, cim_object)[source]

Add the CIM object to the object store.

Parameters:
  • name (string or CIMInstanceName) – Name by which the CIM object will be identified in the object store.
  • cim_object (CIM object) – The CIM object to be added to the object store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises:

ValueError – If CIM object already exists in the object store.

update(name, cim_object)[source]

Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

Parameters:
  • name (string or CIMInstanceName) – Name by which the object is identified in the object store.
  • cim_object (CIM object) – The CIM object to replace the original CIM object in the data store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises:

KeyError – If no CIM object with name exists in the object store.

delete(name)[source]

Delete the CIM object identified by name from the object store.

Parameters:name (string or CIMInstanceName) – Name by which the object to be deleted is identified in the object store.
Raises:KeyError – If there is no object with name in this object store
iter_names()[source]

Only copies the names for those objects that use CIMNamespaceName as the name. The others are immutable ex. classname.

iter_values(copy=True)[source]

Return an iterator to the CIM objects in the object store. This allows iteration through all the objects in this object store using iterator methods.

The order of returned CIM objects is undetermined.

Parameters:copy (bool) – Copy the objects before returning them. This is the default behavior and also the mode that should be used unless the user is certain the object will NOT be modified after it is returned.
Returns:An iterator for the objects in the object store. If copy == True, each object is copied before it is returned.
Return type:iterator
len()[source]

Return the count of objects in this object store.

Returns:Integer that is count of objects in this object store.
Return type:int

9.5. Mocking multiple CIM namespaces

The mock WBEM server allows creating multiple CIM namespaces in its CIM repository and adding CIM objects in some or all of those namespaces.

There is a default namespace created when the FakedWBEMConnection object is created from either the value of the default_namespace init parameter or its default value root/cimv2.

However, a working WBEM environment normally includes at least two namespaces:

  1. An interop namespace which contains the parts of the model that deal with the WBEM server itself and with the implemented model (ex. CIM_Namespace, CIM_ObjectManager, CIM_RegisteredProfile, etc.) and which must be publically discoverable without the user knowing what CIM namespaces exist in the WBEM server.
  2. A user namespace containing the CIM objects for the user model.

Pywbem_mock includes a user-defined provider for the CIM_Namespace class that can be enabled by adding code similar to the following to the setup of a mock environment.

# Register the provider for the CIM_Namespace class, assuming that
# dependent classes and qualifier types have already been created in
# the interop namespace.
ns_provider = pywbem_mock.CIMNamespaceProvider(conn.cimrepository)
interop_namespace = "interop"   # or "root/interop"
conn.add_namespace(interop_namespace)
conn.register_provider(ns_provider, namespaces=interop_namespace)

9.6. User-defined providers

Within the mock WBEM server, the response to client requests is normally determined by provider methods that use data in the CIM repository to generate responses (ex. GetInstance gets the instances from the repository, possibly filters properties and returns the instance). However, it is expected that the user may want WBEM operations on specific CIM classes to have side effects, or manage the returns differently than the normal responses.

Thus, for example, the DMTF-defined CIM_Namespace class represents the namespaces in the CIM repository. That means that its provider method for CreateInstance must create a namespace as a side effect, and that its provider methods for GetInstance or EnumerateInstances must inspect the set of namespaces in the CIM repository to generate responses, etc.

Another example of user-defined providers are classes that create their key property values automatically, for example classes that have a single InstanceID key. The provider method for CreateInstance of such classes would ignore the values for the key properties provided in the NewInstance parameter, and determine the key values on its own.

Also, the InvokeMethod operation depends on a specific provider method for the invoked CIM method in the mock WBEM server.

To meet these needs, the capability is provided to users to write user-defined providers that replace the default providers for defined classes and operations.

User-defined providers are written by implementing subclasses of specific provider classes and registering these subclasses as providers using register_provider().

The WBEM operations supported by user-defined providers can be implemented one by one. If a user-defined provider does not implement all WBEM operations, the default implementation will be used.

The following table shows the WBEM operations for which user-defined providers are supported, and the corresponding provider types:

WBEM operation Provider type Superclass Provider description
CreateInstance instance write InstanceWriteProvider User-defined instance write providers
ModifyInstance instance write InstanceWriteProvider User-defined instance write providers
DeleteInstance instance write InstanceWriteProvider User-defined instance write providers
InvokeMethod method MethodProvider User-defined method providers

9.6.1. Creating user-defined providers

A user-defined provider can be created as follows:

  1. Define a subclass of the superclass listed in the table above, with the methods and attributes listed below.

    Example for an instance write provider:

    from pywbem_mock import InstanceWriteProvider
    
    class MyInstanceProvider(InstanceWriteProvider):
    
        . . .
    
    1. Optional: It may have an __init__() method.

      The __init__() method takes as input parameters at least the cimrepository parameter and passes it to the superclass, and may have additional init parameters the user-defined provider requires (that are not passed on to the superclass). Additional init parameters are possible because the user creates the provider object when registering it with register_provider(). Having an __init__() method is optional if no additional init parameters are defined.

      Example for an __init__() method that does not define additional init parameters (and that could therefore be omitted):

      def __init__(self, cimrepository):
          super(MyInstanceWriteProvider, self).__init__(cimrepository)
      
    2. It must have a declaration of the CIM class(es) served by the provider.

      The CIM class or classes served by the provider are declared with a class attribute named provider_classnames. Its value must be a single string or a list/tuple of strings with the CIM class names (in any lexical case).

      provider_classnames = 'CIM_Foo'
      

      or

      provider_classnames = ['CIM_Foo', 'CIM_Foo_blah']
      
    3. It must have an implementation of the Python methods for the WBEM operations that are overwritten by the provider.

      This must be all or a subset of the WBEM operations defined for the provider type. WBEM operations not implemented in the user-defined provider class default to implementations in the superclass. See Python operation methods in user-defined providers for details.

      Example for an CreateInstance method of an instance write provider that just calls superclass method to perform the work (and that could therefore be omitted):

      def CreateInstance(self, namespace, NewInstance):
          return super(MyInstanceWriteProvider, self).CreateInstance(
              namespace, NewInstance)
      
    4. Optional: It may define a post register setup method.

      The provider may override the post_register_setup() method of the provider superclass to do any special setup it needs. That method includes the current connection as a parameter so that WBEM operations on the same or on different classes can be executed. That method will be called during invocation of register_provider(), after the provider registration is successful.

      Example:

      def post_register_setup(self, conn):
        # code that performs post registration setup for the provider
      
  2. Register the user-defined provider using pywbem_mock.FakedWBEMConnection.register_provider().

    This specifies the CIM namespaces for which the user-defined provider will be active. These namespaces must already exist in the CIM repository if the mock WBEM server.

    provider = MyInstanceProvider(self.cimrepository)
    conn.register_provider(provider,
                           namespaces=['root/interop', 'root/cimv2'])
    

9.6.2. Python operation methods in user-defined providers

The Python operation methods (i.e. the Python methods implementing WBEM operations) in user-defined providers may:

  • provide parameter or CIM repository validation in addition to the normal request validation,
  • modify parameters of the request,
  • abort the request with a pywbem.CIMError exception,
  • make modifications to the CIM repository.

The Python operation methods may call the corresponding superclass method to complete the CIM repository modification, or may implement the code to complete the modification. In any case, once a Python operation method returns, the CIM repository needs to reflect any changes on CIM objects the WBEM operation is normally expected to perform.

The Python operation methods have access to:

  • methods defined in the superclass of the provider, including :class:~pywbem_mock.BaseProvider`
  • methods to access the CIM repository using the methods defined in InMemoryRepository

The input parameters for the Python operation methods will have been already validated, including:

  • The input parameters have the correct Python type as per the descriptions in the superclasses.
  • The CIM namespace exists in the CIM repository.
  • The CIM class of a CIM instance or instance path specified as an input parameter exists in that namespace of the CIM repository.
  • The CIM properties of a CIM instance specified as an input parameter are defined in the CIM class of the instance and have the correct CIM types.
  • The CIM instance does not yet exist for CreateInstance and does exist for ModifyInstance.

The Python operation methods should raise any exceptions using pywbem.CIMError using the CIM status codes defined in DSP0200.

9.6.3. User-defined instance write providers

The InstanceWriteProvider class provides the default implementations of the CreateInstance, ModifyInstance and DeleteInstance provider methods by means of CreateInstance(), ModifyInstance(), and DeleteInstance().

A user-defined instance write provider may implement some or all of these provider methods. The method descriptions linked above provide a detailed definition of the input parameters, return values, and required behavior.

The following is a simple example of a user-defined instance write provider that serves the ‘CIM_Foo’ and ‘CIM_FooFoo’ classes and implements CreateInstance for the purpose of setting a value for the ‘InstanceID’ key property:

import uuid
from pywbem_mock import InstanceWriteProvider

class MyInstanceProvider(InstanceWriteProvider):

    # CIM classes served by this provider
    provider_classnames = ['CIM_Foo', 'CIM_FooFoo']

    def CreateInstance(self, namespace, new_instance):
        new_instance.properties["InstanceID"] = \
            "{}.{}".format(new_instance.classname, uuid.uuid4())
        return super(MyInstanceProvider, self).CreateInstance(
            namespace, new_instance)

Because the provider in this example does not implement the ModifyInstance and DeleteInstance methods, these operations will use their default implementations from InstanceWriteProvider.

The provider in this example does not need to implement an __init__() method, because no additional init parameters are needed.

class pywbem_mock.InstanceWriteProvider(cimrepository=None)[source]

This class defines those instance provider methods that may have user- defined providers that override the default provider implementation in this class.

User providers are defined by creating a subclass of this class and defining a new provider method for one of the methods in this class with the same signature.

Note that user-defined providers may, in turn, call the default providers in this class.

Parameters:cimrepository (BaseRepository or subclass) – The CIM repository to be used by the provider.

Methods

CreateInstance Default provider method for pywbem.WBEMConnection.CreateInstance().
DeleteInstance Default provider method for pywbem.WBEMConnection.DeleteInstance().
ModifyInstance Default provider method for pywbem.WBEMConnection.CreateInstance().
add_namespace Add a CIM namespace to the CIM repository.
class_exists Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.
filter_properties Remove properties from an instance or class that aren’t in the property_list parameter.
find_interop_namespace Find the Interop namespace name in the CIM repository, or return None.
get_class Get class from CIM repository.
is_interop_namespace Tests if a namespace name is a valid Interop namespace name.
is_subclass Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e.
post_register_setup Method called by provider registration after registation of provider is successful.
remove_namespace Remove a CIM namespace from the CIM repository.
validate_namespace Validates that a namespace is defined in the CIM repository.

Attributes

cimrepository Instance of class that represents the CIM repository.
interop_namespace_names The valid Interop namespace names.
namespaces The names of the namespaces that exist in the CIM repository.
provider_type Keyword defining the type of request the provider will service.

Details

provider_type = 'instance-write'

Keyword defining the type of request the provider will service. The type for this provider class is predefined as ‘instance’.

Type:string
CreateInstance(namespace, new_instance)[source]

Default provider method for pywbem.WBEMConnection.CreateInstance().

Create a new CIM instance in the CIM repository of the mock WBEM server.

Validation already performed by the provider dispatcher that calls this provider method:

  • The provider method is called only for the registered class and namespace (only applies to user-defined providers).
  • The Python types of all input parameters to this provider method are as specified below.
  • The namespace exists in the CIM repository.
  • The creation class of the new instance exists in the namespace in the CIM repository.
  • All properties specified in the new instance are exposed (i.e. defined and inherited with any overrides resolved) by the creation class in the CIM repository, and have the same type-related attributes (i.e. type, is_array, embedded_object).

Validation that should be performed by this provider method:

  • new_instance does not specify any properties that are not allowed to be initialized by the client, depending on the model implemented by the provider.
  • new_instance specifies all key properties needed by the provider, depending on the model implemented by the provider. The CIM repository will reject any new instance that does not have all key properties specified.
  • The new instance (i.e. an instance with the new instance path) does not exist in the CIM repository. This validation needs to be done by the provider because the determination of the key properties for the new instance path may depend on the model implemented by the provider. The CIM repository will reject the creation of instances that already exist, so this check can be delegated to the repository once the new instance path has been determined.
Parameters:
  • namespace (string) – The name of the CIM namespace in which the CIM instance is to be created, in any lexical case, and with leading and trailing slash characters removed.
  • new_instance (CIMInstance) –

    A representation of the CIM instance to be created.

    This object is a deep copy of the original client parameter, and may be modified by the provider as needed, before storing it in the CIM repository.

    The property names in this object have been adjusted to match the lexical case of the property definitions in the creation class of the instance in the CIM repository.

    The classname attribute of this object will specify the creation class for the new instance, in any lexical case.

    The properties attribute of this object will specify the initial property values for the new CIM instance, with property names in any lexical case. Key properties may or may not be included.

    The path attribute of this object will be None.

    The qualifiers attribute of this object, if non-empty, should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.

Returns:

Instance path of the new CIM instance.

Return type:

CIMInstanceName

Raises:

CIMError – The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER - CIM_ERR_ALREADY_EXISTS

ModifyInstance(modified_instance, IncludeQualifiers=None)[source]

Default provider method for pywbem.WBEMConnection.CreateInstance().

Modify an existing CIM instance in the CIM repository of the mock WBEM server.

NOTE: This method specifies the namespace in modified_instance.path rather than as a separate input parameter.

The modification of the instance in the CIM repository that is performed by the provider should be limited to property value changes (including addition of properties if not yet set on the instance), because instance-level qualifiers have been deprecated in CIM.

The set of properties that are to be modified in the CIM instance has already been determined by the caller so that the modified_instance parameter specifies exactly the set of properties to be modified. Therefore, this provider method does not have a property list parameter.

Validation already performed by the provider dispatcher that calls this provider method:

  • The provider method is called only for the registered class and namespace (only applies to user-defined providers).
  • The Python types of all input parameters to this provider method are as specified below.
  • The classnames in modified_instance are consistent between instance and instance path.
  • The namespace exists in the CIM repository.
  • The creation class of the instance to be modified exists in the namespace of the CIM repository.
  • The instance to be modified exists in the namespace of the CIM repository.
  • All properties in modified_instance that are to be modified are exposed (i.e. defined and inherited with any overrides resolved) by the creation class in the CIM repository, and have the same type-related attributes (i.e. type, is_array, embedded_object).
  • No key properties are requested to change their values.

Validation that should be performed by this provider method:

  • modified_instance does not specify any changed values for properties that are not allowed to be changed by the client, depending on the model implemented by the provider.
Parameters:
  • modified_instance (CIMInstance) –

    A representation of the modified CIM instance, also indicating its instance path, with exactly the set of properties to be modified.

    This object is a deep copy of the original client parameter, and may be modified by the provider as needed, before storing it in the CIM repository.

    The path attribute of this object will be set and is the instance path of the instance to be modified in the CIM repository. Its namespace, classname and keybindings attributes will be set. The names will be in any lexical case.

    The classname attribute of this object will specify the creation class of the instance to be modified, in any lexical case.

    The properties attribute of this object will specify exactly the set of properties that are to be updated, taking into account the original ModifiedInstance and PropertyList input parameters of the ModifyInstance() client call. The lexical case of the property names has been adjusted to match the lexical cae of the property definitions in the creation class in the CIM repository.

    The qualifiers attribute of this object, if non-empty, should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.

  • IncludeQualifiers (bool) – This parameter should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.
Raises:

CIMError – The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER

DeleteInstance(InstanceName)[source]

Default provider method for pywbem.WBEMConnection.DeleteInstance().

Delete an existing instance in the CIM repository of the mock WBEM server.

NOTE: This method specifies the namespace in InstanceName rather than as a separate input parameter.

The provider is not responsible for determining other instances that depend on the instance to be deleted (e.g. association instances referencing the instance to be deleted); such dependency detection and handling is done elsewhere.

Validation already performed by the provider dispatcher that calls this provider method:

  • The provider method is called only for the registered class and namespace (only applies to user-defined providers).
  • The Python types of all input parameters to this provider method are as specified below.
  • The namespace exists in the CIM repository.
  • The creation class of the instance to be deleted exists in the namespace of the CIM repository.
  • The instance to be deleted exists in the namespace of the CIM repository.
Parameters:InstanceName (CIMInstanceName) –

The instance path of the instance to be deleted with the following attributes:

  • classname: Name of the creation class of the instance.
  • keybindings: Keybindings of the instance.
  • namespace: Name of the CIM namespace containing the instance. Will not be None.
  • host: Will be None.
Raises:None
post_register_setup(conn)[source]

Method called by provider registration after registation of provider is successful. Using this method is optional for registration cases where the provider must execute some activity (ex. modify the CIM repository after successful provider registration).

Override this method in the user-defined provider subclass to execute this method.

Parameters:conn (WBEMConnection) – Current connection which allows client methods to be executed from within this method.

9.6.4. User-defined method providers

The MethodProvider class provides the default implementation of the InvokeMethod provider method by means of InvokeMethod().

The default implementation raises CIMError with CIM_ERR_METHOD_NOT_AVAILABLE, because there is no meaningful default implementation of CIM methods. A user-defined method provider implements this provider method. The method description linked above provides a detailed definition of the input parameters, return values, and required behavior.

The following example implements method Method1 defined in class CIM_Foo_sub_sub that is defined as follows:

    [Description ("Subclass of CIM_Foo_sub")]
class CIM_Foo_sub_sub : CIM_Foo_sub {

    string cimfoo_sub_sub;

        [Description("Sample method with input and output parameters")]
    uint32 Method1(
        [IN ( false), OUT, Description("Response param 2")]
      string OutputParam2);
};

The example implementation of method Method1 in the user-defined method provider modifies the value of property cimfoo_sub_sub of the instance, and returns it as its output parameter OutputParam2:

from pywbem import CIMInstanceName, CIMError, \
    CIM_ERR_INVALID_PARAMETER, CIM_ERR_METHOD_NOT_AVAILABLE
from pywbem_mock import MethodProvider

class MyMethodProvider(MethodProvider):

    provider_classname = 'CIM_Foo_sub_sub'

    def InvokeMethod(self, methodname, localobject, params):

        if methodname.lower() == 'method1':
            if isinstance(localobject, CIMClassName):
                raise CIMError(
                    CIM_ERR_INVALID_PARAMETER,
                    "CIM method {0} must be invoked on a CIM instance".
                    format(methodname))
            return self.Method1(localobject, params)
        else:
            raise CIMError(CIM_ERR_METHOD_NOT_AVAILABLE)

    def Method1(self, localobject, params):
        '''
        Implementation of CIM method 'Method1'.
        '''
        namespace = localobject.namespace
        instance_store = self.cimrepository.get_instance_store(namespace)

        # Get the instance the method was invoked on, from the CIM
        # repository (as a copy)
        instance = instance_store.get(localobject.path)  # a copy

        # Modify a property value in the local copy of the instance
        if 'cimfoo_sub_sub' not in instance.properties:
            instance.properties['cimfoo_sub_sub'] = 'new'
        instance.properties['cimfoo_sub_sub'] += '+'

        # Update the instance in the CIM repository from the changed
        # local instance
        instance_store.update(localobject.path, instance)

        # Return the property value in the output parameter
        outputparam2 = instance.properties['cimfoo_sub_sub']
        out_params = [
            CIMParameter('OutputParam2', type='string', value=outputparam2),
        ]

        # Set the return value of the CIM method
        return_value = 0

        return (return_value, out_params)
class pywbem_mock.MethodProvider(cimrepository=None)[source]

This class defines the provider class that handles the default InvokeMethod.

User method providers are defined by creating a subclass of this class and defining an InvokeMethod based on the method in this class.

Parameters:cimrepository (BaseRepository or subclass) – Defines the repository to be used by the provider.

Methods

InvokeMethod Default provider method for pywbem.WBEMConnection.InvokeMethod().
add_namespace Add a CIM namespace to the CIM repository.
class_exists Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.
filter_properties Remove properties from an instance or class that aren’t in the property_list parameter.
find_interop_namespace Find the Interop namespace name in the CIM repository, or return None.
get_class Get class from CIM repository.
is_interop_namespace Tests if a namespace name is a valid Interop namespace name.
is_subclass Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e.
post_register_setup Method called by provider registration after registation of provider is successful.
remove_namespace Remove a CIM namespace from the CIM repository.
validate_namespace Validates that a namespace is defined in the CIM repository.

Attributes

cimrepository Instance of class that represents the CIM repository.
interop_namespace_names The valid Interop namespace names.
namespaces The names of the namespaces that exist in the CIM repository.
provider_type Keyword defining the type of request the provider will service.

Details

provider_type = 'method'

Keyword defining the type of request the provider will service. The type for this class is predefined as ‘method’

Type:provider_type (string)
InvokeMethod(methodname, localobject, params)[source]

Default provider method for pywbem.WBEMConnection.InvokeMethod().

Invoke a CIM method (static or dynamic) on a target CIM object (class or instance) in the CIM repository of the mock WBEM server.

This default provider always raises CIMError(CIM_ERR_METHOD_NOT_FOUND) because there is no concept of a default method invocation behavior in in CIM (other than raising this error). A user-defined method provider is necessary to have a meaningful implementation of a method invocation.

Validation already performed by the provider dispatcher that calls this provider method:

  • The provider method is called only for the registered class and namespace (only applies to user-defined providers).
  • The Python types of all input parameters to this provider method are as specified below.
  • The namespace exists in the CIM repository.
  • For instance-level use:
    • The creation class of the target instance exists in the namespace of the CIM repository.
    • The target instance exists in the namespace of the CIM repository.
    • The creation class of the target instance exposes the method to be invoked.
  • For class-level use:
    • The target class exists in the namespace of the CIM repository.
    • The target class exposes the method to be invoked.
    • The method exposed by the creation class is a static method as per its ‘Static’ qualifier.
  • The set of specified CIM method input parameters matches exactly the set of input parameters defined by the method in the CIM repository (as detected by their ‘In’ qualifier in the creation class), w.r.t. parameter name and type-related attributes (type, is_array, embedded_object).

Validation that should be performed by this provider method:

  • MethodName is the name of a method the provider implements.
  • Constraints on the values of input parameters.
Parameters:
  • methodname (string) – Name of the CIM method to be invoked, in any lexical case.
  • objectname

    (CIMInstanceName or CIMClassName): A reference to the target CIM object, as follows:

    • For instance-level use: The instance path of the target instance, as a CIMInstanceName object, with the following attributes:
      • classname: Will be set, in any lexical case.
      • keybindings: Will be set, with key names in any lexical case.
      • namespace: Will be set, in any lexical case, and with leading and trailing slash characters removed.
      • host: Will be None.
    • For class-level use: The class path of the target class, as a CIMClassName object, with the following attributes:
      • classname: Will be set, in any lexical case.
      • namespace: Will be set, in any lexical case, and with leading and trailing slash characters removed.
      • host: Will be None.
  • params (NocaseDict) –

    The input parameters for the method invocation, with items as follows:

    • key (string): The parameter name, in any lexical case.
    • value (CIMParameter): The parameter value.
Returns:

The return value and output parameters of the method invocation:

  • return_value (CIM data type): Return value of the method invocation.

  • out_params (colletions.abc.Sequence or colletions.abc.Mapping): Output parameters of the method invocation.

    If Sequence, the items must be CIMParameter in any order, with these attributes set:

    If Mapping, the items must be as follows:

Return type:

tuple() (return_value, out_params)

Raises:

CIMError – (CIM_ERR_METHOD_NOT_FOUND) because the default method is only a placeholder for the API and documentation and not a real InvokeMethod action implementation.

post_register_setup(conn)[source]

Method called by provider registration after registation of provider is successful. Using this method is optional for registration cases where the provider must execute some activity (ex. modify the CIM repository after successful provider registration).

Override this method in the user-defined provider subclass to execute this method.

Parameters:conn (WBEMConnection) – Current connection which allows client methods to be executed from within this method.

9.7. Registry for provider dependent files

A faked WBEM connection provides a registry for provider dependent files in its provider_dependent_registry property of type pywbem_mock.ProviderDependentRegistry.

This registry can be used by callers to register and look up the path names of additional dependent files of a mock script, in context of that mock script.

The pywbemtools project makes use of this registry for validating whether its mock cache is up to date w.r.t. additional dependent files a mock script has used.

class pywbem_mock.ProviderDependentRegistry[source]

A registry for provider dependent files in context of a mock script.

This registry allows registering additional dependent files in context of a mock script, and to look them up again.

The registry works with the path names of the mock script and dependent files and normalizes these path names as follows:

  • The path is relative to the user’s home directory, if possible. If not possible (i.e. on Windows when on a different drive than the home directory), the path is absolute.
  • The path does not contain redundant path separators or same-level or up-level directories.
  • On case insensitive file systems, the lexical case is normalized to lower case.
  • The native path seprarators of the operating system are used.

Methods

add_dependents Add dependent files to the registry, in context of a mock script.
iter_dependents Iterate through the path names of the dependent files that are registered for a mock script.
load Replace the data in this object with the data from the other object.

Attributes

Details

add_dependents(mock_script_path, dependent_paths)[source]

Add dependent files to the registry, in context of a mock script.

Parameters:
  • mock_script_path (string) – Path name of the mock script. May be relative or absolute, and will be normalized to look up the registered dependents.
  • dependent_paths (string or list of string) – Path name(s) of provider dependent files to be registered. May be relative or absolute, and will be normalized when registering them.
iter_dependents(mock_script_path)[source]

Iterate through the path names of the dependent files that are registered for a mock script.

If the mock script is not registered, the iteration is empty.

The iterated path names are the normalized path names, but with a path that makes them accessible from within the current directory.

Parameters:mock_script_path (string) – Path name of the mock script. May be relative or absolute, and will be normalized to look up the registered dependents.
Returns:A generator iterator for the path names of the dependent files.
Return type:iterator
load(other)[source]

Replace the data in this object with the data from the other object.

This is used to restore the object from a serialized state, without changing its identity.

9.8. Configuration of mocked behavior

Pywbem_mock supports several variables that provide configuration and behavior control of the mock environment.

These configuration variables can be modified by the user directly after importing pywbem. For example:

import pywbem_mock
pywbem_mock.config.SYSTEMNAME = 'MyTestSystemName'

Note that the pywbem source file defining these variables should not be changed by the user. Instead, the technique shown in the example above should be used to modify the configuration variables.

pywbem_mock.config.OBJECTMANAGERNAME = 'FakeObjectManager'

Name for the object manager It is used in defining user-defined provider properties for CIM_Namespace provider and CIM_ObjectManager provider if if they are defined.

pywbem_mock.config.OBJECTMANAGERCREATIONCLASSNAME = 'CIM_ObjectManager'

Value for the CIM_ObjectManagerCreationClassName defined in the CIM_ObjectManager class.

pywbem_mock.config.SYSTEMNAME = 'MockSystem_WBEMServerTest'

The name of the mock object. This string value becomes part of the CIM_ObjectNamager instance and CIM_Namespace instances

pywbem_mock.config.SYSTEMCREATIONCLASSNAME = 'CIM_ComputerSystem'

Name for the property SystemCreationClassname defined a number of CIM classes that are used by the pywbem_mock including CIM_Namespace

pywbem_mock.config.DEFAULT_MAX_OBJECT_COUNT = 100

Default value for the MaxObjectCount parameter of the Open…() methods of the mock WBEM server, if the value was not provided by the user.

pywbem_mock.config.OPEN_MAX_TIMEOUT = 40

Maximum value for the OperationTimeout parameter of the Open…() methods of the mock WBEM server.

pywbem_mock.config.IGNORE_INSTANCE_IQ_PARAM = True

Use of the IncludeQualifiers parameter on instance requests is DEPRECATED in DMTF DSP0200. The definition of IncludeQualifiers is ambiguous and when this parameter is set to true, WBEM clients cannot be assured that any qualifiers will be returned. A WBEM client should always set this parameter to false. To minimize the impact of this recommendation on WBEM clients, a WBEM server may choose to treat the value of IncludeQualifiers as false for all requests.

The following variable forces pywbem_mock to ignore the client supplied variable and not return qualifiers on EnumerateInstances and GetInstance responses.

  • True (default): pywbem_mock always removes qualifiers from instances in responses
  • False: pywbem_mock uses value of input parameter or its default to determine if qualifiers are to be removed
pywbem_mock.config.IGNORE_INSTANCE_ICO_PARAM = True

Use of the IncludeClassOrigin parameter on instance requests is DEPRECATED. A WBEM server may choose to treat the value of IncludeClassOrigin parameter as false for all requests, otherwise the implementation shall support the original behavior as defined in the rest of this paragraph. If the IncludeClassOrigin input parameter is true, the CLASSORIGIN attribute shall be present on all appropriate elements in each returned Instance. If it is false, no CLASSORIGIN attributes are present.

The following variable forces pywbem_mock to ignore the client supplied variable and not return qualifiers on EnumerateInstances and GetInstance responses.

  • True (default): pywbem_mock always removes class origin attributes from instances in responses
  • False: pywbem_mock uses value of input parameter or its default to determine if class origin attributes are to be removed

9.9. Mocker base classes

Some bases classes are included in this documentation in order to provide the descriptions for inherited methods and properties in the previous class descriptions of the mock WBEM server.

class pywbem_mock.BaseRepository[source]

An abstract base class defining the required APIs to provide access to a a CIM repository. The API provides functions to:

  1. Manage CIM namespaces in the data repository including creation, deletion and getting a list of the existing namespaces.
  2. Access the object store for each CIM object type in the repository for the objects of the following CIM types: (CIMClass, CIMInstance, and CIMQualifierDeclaration) so that methods of the BaseObjectStore are used to access and manipulate CIM objects of a single CIM type by namespace in the repository.

Methods

add_namespace Add a CIM namespace to the repository.
get_class_store Return the CIM class object store for the namespace provided.
get_instance_store Return the CIM instance object store for the namespace provided.
get_qualifier_store Return the CIM qualifier declaration object store for the namespace provided.
remove_namespace Remove a CIM namespace from the repository.
validate_namespace Validate if the namespace exists in the repository.

Attributes

namespaces The names of the namespaces that exist in this CIM repository.

Details

namespaces

The names of the namespaces that exist in this CIM repository.

Note that if there were any leading or trailing slash (“/”) characters in namespace parameters used to add the namespaces to the repository, they will be removed from the namespaces returned with this property.

Type:NocaseList of string
validate_namespace(namespace)[source]

Validate if the namespace exists in the repository. If the namespace does not exist a KeyError is raised.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Raises:
  • KeyError – If the namespace is not defined in the repository.
  • ValueError – if the namespace is None.
add_namespace(namespace)[source]

Add a CIM namespace to the repository.

The namespace must not yet exist in the CIM repository.

Parameters:namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises:ValueError – If the namespace argument is None or the namespace already exists.
remove_namespace(namespace)[source]

Remove a CIM namespace from the repository.

The namespace must exist in the repository and must be empty.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Raises:
  • ValueError – Namespace argument is None or the repository namespace is not empty.
  • KeyError – Namespace does not exist in the CIM repository.
get_class_store(namespace)[source]

Return the CIM class object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM class object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – Namespace argument is None.
  • KeyError – Namespace does not exist in the repository
get_instance_store(namespace)[source]

Return the CIM instance object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM instance object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – Namespace argument is None.
  • KeyError – Namespace argument does exist in the repository.
get_qualifier_store(namespace)[source]

Return the CIM qualifier declaration object store for the namespace provided.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.

Returns:

CIM qualifier declaration object store for the namespace provided.

Return type:

InMemoryObjectStore

Raises:
  • ValueError – namespace parameter is None
  • KeyError – namespace argument does exist in therepository.
class pywbem_mock.BaseObjectStore(cim_object_type)[source]

An abstract class that defines the APIs for the methods of an object store for CIM objects including CIMClass, CIMInstance, and CIMQualifierDeclaration objects that constitute a WBEM server repository. This class provides the abstract methods for creating, accessing, and deleting, CIM objects of a single CIM object type in the repository.

CIM objects in the object store are identified by a name which is part of the methods that access the CIM objects and must be unique within a single object store.

Each object store conatins only a single CIM object type.

Instantiate the self.cim_object_type variable.

Parameters:cim_object_type (CIM object) – The Pywbem CIM object type as defined in cim_types.py for the objects in the data store. Used to verify values on create.

Methods

create Add the CIM object to the object store.
delete Delete the CIM object identified by name from the object store.
get Return the CIM object identified by name if it exists in the object store.
iter_names Return an iterator to the names of the CIM objects in the object store.
iter_values Return an iterator to the CIM objects in the object store.
len Return the count of objects in this object store.
object_exists Test if the CIM object identified by name exists in the object store.
update Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

Attributes

Details

object_exists(name)[source]

Test if the CIM object identified by name exists in the object store.

Parameters:name (string or CIMInstanceName) – Name by which the object is identified in the object store.
Returns:Indicates whether the CIM object exists in the object store.
Return type:bool
get(name, copy=True)[source]

Return the CIM object identified by name if it exists in the object store.

Parameters:
  • name (string or CIMInstanceName) – Name by which the object is identified in the object store
  • copy (bool) – If True, returns a copy of the object to insure that modifying the returned object does not change the data store. The default behavior is True . If copy is False, the object in the object store is returned but if it is modified by the user, the object in the store may be modified also.
Returns:

Returns the CIM object identified by the name parameter.

Return type:

CIM object

Raises:

KeyError – CIM object identified with name not in the object store

create(name, cim_object)[source]

Add the CIM object to the object store.

Parameters:
  • name (string or CIMInstanceName) – Name by which the CIM object will be identified in the object store.
  • cim_object (CIM object) – The CIM object to be added to the object store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises:

ValueError – If CIM object already exists in the object store.

update(name, cim_object)[source]

Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

Parameters:
  • name (string or CIMInstanceName) – Name by which the object is identified in the object store.
  • cim_object (CIM object) – The CIM object to replace the original CIM object in the data store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises:

KeyError – If no CIM object with name exists in the object store.

delete(name)[source]

Delete the CIM object identified by name from the object store.

Parameters:name (string or CIMInstanceName) – Name by which the object to be deleted is identified in the object store.
Raises:KeyError – If there is no object with name in this object store
iter_names()[source]

Return an iterator to the names of the CIM objects in the object store. Objects may be accessed using iterator methods.

The order of returned names is undetermined.

Returns:An iterator for the names of CIM objects in the object store.
Return type:iterator
iter_values(copy=True)[source]

Return an iterator to the CIM objects in the object store. This allows iteration through all the objects in this object store using iterator methods.

The order of returned CIM objects is undetermined.

Parameters:copy (bool) – Copy the objects before returning them. This is the default behavior and also the mode that should be used unless the user is certain the object will NOT be modified after it is returned.
Returns:An iterator for the objects in the object store. If copy == True, each object is copied before it is returned.
Return type:iterator
len()[source]

Return the count of objects in this object store.

Returns:Integer that is count of objects in this object store.
Return type:int
class pywbem_mock.BaseProvider(cimrepository)[source]

BaseProvider is the top level class in the provider hiearchy and includes methods required by both builtin providers and user-defined providers. This class is not intended to be executed directly.

Parameters:cimrepository (BaseRepository or subclass) – Defines the repository to be used by providers. The repository is fully initialized but contains only objects defined by the FakedWbemConnection methods that create objects in the repository (ex. compile_file())

Methods

add_namespace Add a CIM namespace to the CIM repository.
class_exists Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.
filter_properties Remove properties from an instance or class that aren’t in the property_list parameter.
find_interop_namespace Find the Interop namespace name in the CIM repository, or return None.
get_class Get class from CIM repository.
is_interop_namespace Tests if a namespace name is a valid Interop namespace name.
is_subclass Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e.
remove_namespace Remove a CIM namespace from the CIM repository.
validate_namespace Validates that a namespace is defined in the CIM repository.

Attributes

cimrepository Instance of class that represents the CIM repository.
interop_namespace_names The valid Interop namespace names.
namespaces The names of the namespaces that exist in the CIM repository.

Details

cimrepository

Instance of class that represents the CIM repository.

The CIM repository is the data store for CIM classes, CIM instances, and CIM qualifier declarations. All access to the mocker CIM data must pass through this variable to the CIM repository. See BaseRepository for a description of the repository interface.

The mocker may use subclasses of BaseRepository for specific functionality. Thus, InMemoryRepository implements an InMemory CIM repository that must be initialized for each FakedWbemConnection construction.

Type:BaseRepository or subclass
namespaces

The names of the namespaces that exist in the CIM repository.

Type:NocaseList of string
interop_namespace_names

The valid Interop namespace names.

Only these names may be the Interop namespace and only one Interop namespace may exist in a WBEM server environment. This list is defined in pywbem.WBEMServer.INTEROP_NAMESPACES.

Type:NocaseList of string
validate_namespace(namespace)[source]

Validates that a namespace is defined in the CIM repository. Returns only if namespace is valid. Otherwise it generates an exception.

Parameters:namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Any leading or trailing slash characters are ignored.
Raises:CIMError – (CIM_ERR_INVALID_NAMESPACE) Namespace does not exist.
add_namespace(namespace)[source]

Add a CIM namespace to the CIM repository.

The namespace must not yet exist in the CIM repository and the repository can contain only one Interop namespace.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository. Must not be None. Any leading or trailing slash characters are removed before the string is used to define the namespace name.

Raises:
  • ValueError – Namespace argument must not be None.
  • CIMError – CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.
  • CIMError – CIM_ERR_ALREADY_EXISTS if the namespace is one of the possible Interop namespace names and an interop namespace already exists in the CIM repository.
remove_namespace(namespace)[source]

Remove a CIM namespace from the CIM repository.

The namespace must exist in the CIM repository and must be empty.

Parameters:

namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.

Raises:
  • ValueError – Namespace argument must not be None.
  • CIMError – CIM_ERR_NOT_FOUND if the namespace does not exist in the CIM repository.
  • CIMError – CIM_ERR_NAMESPACE_NOT_EMPTY if the namespace icontains objects.
  • CIMError – CIM_ERR_NAMESPACE_NOT_EMPTY if attempting to delete the default connection namespace. This namespace cannot be deleted from the CIM repository
is_interop_namespace(namespace)[source]

Tests if a namespace name is a valid Interop namespace name.

This method does not access the CIM repository for this test; it merely compares the specified namespace name against the list of valid Interop namespace names returned by interop_namespace_names.

Parameters:namespace (string) – The namespace name that is to be tested.
Returns:Indicates whether the namespace name is a valid Interop namespace name.
Return type:bool
find_interop_namespace()[source]

Find the Interop namespace name in the CIM repository, or return None.

The Interop namespace is identified by comparing all namespace names in the CIM repository against the list of valid Interop namespace names returned by interop_namespace_names.

Returns:The name of the Interop namespace if one exists in the CIM repository or None.
Return type:string
get_class(namespace, classname, local_only=None, include_qualifiers=None, include_classorigin=None, property_list=None)[source]

Get class from CIM repository. Gets the class defined by classname from the CIM repository, creates a copy, expands the copied class to include superclass properties if not localonly, and filters the class based on propertylist and includeClassOrigin.

This method executes all of the filter actions on the class that are defined for the GetClass operation and so returns a class that satisfies the behavior requirements of the GetClass client request operation defined in DSP0200 . (see: pywbem.WBEMConnection.GetClass())

It also sets the propagated attribute.

Parameters:
  • classname (string) – Name of class to retrieve
  • namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.
  • local_only (bool) – If True or None, only properties and methods in this specific class are returned. None means not supplied by client and the normal server default is True. If False, properties and methods from the superclasses are included.
  • include_qualifiers (bool) – If True or None, include qualifiers. None is the server default if the parameter is not provided by the client. If False, do not include qualifiers.
  • include_classorigin (bool) – If True, return the class_origin attributes of properties and methods. If False or None (use server default), class_origin attributes of properties and methods are not returned
  • property_list (list of string) – Properties to be included in returned class. If None, all properties are returned. If empty list, no properties are returned
Returns:

Copy of the CIM class in the CIM repository if found. Includes superclass properties installed and filtered in accord with the local_only, etc. arguments.

Return type:

CIMClass

Raises:
  • CIMError – (CIM_ERR_NOT_FOUND) if class not found in CIM repository.
  • CIMError – (CIM_ERR_INVALID_NAMESPACE) if namespace does not exist.
class_exists(namespace, classname)[source]

Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.

Returns:True if class exists and False if it does not exist.
Return type:bool
Raises:Exception if the namespace does not exist
static filter_properties(obj, property_list)[source]

Remove properties from an instance or class that aren’t in the property_list parameter.

Parameters:
  • obj (CIMClass or CIMInstance) – The class or instance from which properties are to be filtered
  • property_list (list of string) – List of properties which are to be included in the result. If None, remove nothing. If empty list, remove everything. else remove properties that are not in property_list. Duplicated names are allowed in the list and ignored.
is_subclass(klass, superclass, class_store)[source]

Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e. in the namespace of that class store).

This test is done by starting at the class and walking its superclasses up to the root, so it is not as expensive as determining all subclasses of a given class.

Parameters:
  • klass (string) – Class name of the class.
  • superclass (string) – Class name of the superclass.
  • class_store (BaseObjectStore) – Class store of the CIM repository to search for the classes.
Returns:

Boolean indicating whether the class is a (direct or indirect) subclass of the superclass, or the same class.

Return type:

bool

Raises:

KeyError – Class or superclass does not exist in the class store.