9. Mock WBEM server

New in pywbem 0.12 as experimental and finalized in 1.2.

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() .

An Interop namespace can be created by adding it via add_namespace(). The Interop namespace will be initially empty, and the necessary instance(s) of a CIM namespace class will be automatically created when registering the namespace provider CIMNamespaceProvider. See Mocking multiple CIM namespaces for details.

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: Behaves like ModifyClass(). The pywbem_mock implementation rejects modifications where the class to modifiy has either subclasses or instances and resolves the various qualifiers, class origin values and propagated values as the the CreateClass operation.

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=30, response_delay=None, disable_pull_operations=None, url=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.

New in pywbem 0.12 as experimental and finalized in 1.2.

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 pywbem.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.

url (string):

Defines a url to replace the default http://FakedURL.5988 url which is passed to the superclass. The url must be an acceptable syntax for WBEMConnection initialization. This is useful when multiple mocks are required for testing.

Raises

ValueError – Invalid arguments

Methods:

AssociatorNames(ObjectName[, AssocClass, ...])

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(ObjectName[, AssocClass, ...])

Retrieve the instances associated to a source instance, or the classes associated to a source class.

CloseEnumeration(context)

Close an open enumeration session, causing an early termination of an incomplete enumeration session.

CreateClass(NewClass[, namespace])

Create a class in a namespace.

CreateInstance(NewInstance[, namespace])

Create an instance in a namespace.

DeleteClass(ClassName[, namespace])

Delete a class.

DeleteInstance(InstanceName)

Delete an instance.

DeleteQualifier(QualifierName[, namespace])

Delete a qualifier type (= qualifier declaration).

EnumerateClassNames([namespace, ClassName, ...])

Enumerate the names of subclasses of a class, or of the top-level classes in a namespace.

EnumerateClasses([namespace, ClassName, ...])

Enumerate the subclasses of a class, or the top-level classes in a namespace.

EnumerateInstanceNames(ClassName[, namespace])

Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

EnumerateInstances(ClassName[, namespace, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace.

EnumerateQualifiers([namespace])

Enumerate the qualifier types (= qualifier declarations) in a namespace.

ExecQuery(QueryLanguage, Query[, namespace])

Execute a query in a namespace.

ExportIndication(NewIndication)

Send an indication to a WBEM listener.

GetClass(ClassName[, namespace, LocalOnly, ...])

Retrieve a class.

GetInstance(InstanceName[, LocalOnly, ...])

Retrieve an instance.

GetQualifier(QualifierName[, namespace])

Retrieve a qualifier type (= qualifier declaration).

InvokeMethod(MethodName, ObjectName[, Params])

Invoke a method on a target instance or on a target class.

IterAssociatorInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result.

IterAssociatorInstances(InstanceName[, ...])

Retrieve the instances associated to a source instance, using the Python generator idiom to return the result.

IterEnumerateInstancePaths(ClassName[, ...])

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(ClassName[, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.

IterQueryInstances(FilterQueryLanguage, ...)

Execute a query in a namespace, using the Python generator idiom to return the result.

IterReferenceInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result.

IterReferenceInstances(InstanceName[, ...])

Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result.

ModifyClass(ModifiedClass[, namespace])

Modify a class.

ModifyInstance(ModifiedInstance[, ...])

Modify the property values of an instance.

OpenAssociatorInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the instances associated to a source instance.

OpenAssociatorInstances(InstanceName[, ...])

Open an enumeration session to retrieve the instances associated to a source instance.

OpenEnumerateInstancePaths(ClassName[, ...])

Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

OpenEnumerateInstances(ClassName[, ...])

Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace.

OpenQueryInstances(FilterQueryLanguage, ...)

Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result.

OpenReferenceInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance.

OpenReferenceInstances(InstanceName[, ...])

Open an enumeration session to retrieve the association instances that reference a source instance.

PullInstancePaths(context, MaxObjectCount)

Retrieve the next set of instance paths from an open enumeration session.

PullInstances(context, MaxObjectCount)

Retrieve the next set of instances (without instance paths) from an open enumeration session.

PullInstancesWithPath(context, MaxObjectCount)

Retrieve the next set of instances (with instance paths) from an open enumeration session.

ReferenceNames(ObjectName[, ResultClass, Role])

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(ObjectName[, ResultClass, Role, ...])

Retrieve the association instances that reference a source instance, or the association classes that reference a source class.

SetQualifier(QualifierDeclaration[, namespace])

Create or modify a qualifier type (= qualifier declaration) in a namespace.

__enter__()

New in pywbem 1.2.

__exit__(exc_type, exc_value, traceback)

New in pywbem 1.2.

__repr__()

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()

Return a short representation of the WBEMConnection object for human consumption.

add_cimobjects(objects[, namespace])

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

add_namespace(namespace[, verbose])

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

add_operation_recorder(operation_recorder)

Internal: Add an operation recorder to this connection.

close()

Closes this connection.

compile_mof_file(mof_file[, namespace, ...])

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(mof_str[, namespace, ...])

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(class_names, ...[, ...])

Compile the classes defined by class_names and all of their dependences.

copy()

New in pywbem 1.3.

display_registered_providers()

Display information on the currently registered providers.

display_repository([namespaces, dest, ...])

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(interop_namespace)

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

install_subscription_providers(interop_namespace)

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

is_interop_namespace(namespace)

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

is_subclass(namespace, klass, superclass)

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([pull_op])

Internal: Low-level method used by the operation-specific methods of this class.

operation_recorder_stage_pywbem_args(method, ...)

Internal: Low-level method used by the operation-specific methods of this class.

operation_recorder_stage_result(ret, exc)

Internal: Low-level method used by the operation-specific methods of this class.

register_provider(provider[, namespaces, ...])

Register the provider object for specific namespaces and CIM classes.

remove_namespace(namespace[, verbose])

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 or WBEM listener.

cimrepository

The mocked in-memory CIM repository.

conn_id

connection 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

bool: 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 or WBEM listener, in the format host:port.

interop_namespace_names

NocaseList of string: 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

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as it was received (=raw).

last_raw_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as it was sent (=raw).

last_reply

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_reply_len

int: The size of the HTTP body in the CIM-XML response of the last operation, in Bytes.

last_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_request_len

int: 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

NocaseList of string: 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

Internal: Enablement status for all operation recorders of the connection.

operation_recorders

Tuple of BaseOperationRecorder subclass objects:

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 or WBEM listener.

response_delay

number: Artifically created delay for each operation, in seconds.

scheme

Normalized scheme of the URL of the WBEM server or WBEM listener, 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 or listener.

url

Normalized URL of the WBEM server or WBEM listener.

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 or WBEM listener during the TLS/SSL handshake.

__repr__()[source]

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()[source]

Return a short representation of the WBEMConnection object for human consumption.

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.

add_namespace(namespace, verbose=False)[source]

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

The namespace must not yet exist in the CIM repository.

If a namespace provider has already been created, this method must use that provider to create the namespace rather than try to create the namespace directly in the 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.

  • verbose (bool) – Verbose mode: Print a message about the namespace creation.

Raises
  • ValueError – Namespace argument must not be None.

  • CIMError – CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.

property 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

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 CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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 CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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) – The name of the CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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.

copy()[source]

New in pywbem 1.3.

Return a deep copy of the object with internal state reset and reusing the same repository and registries.

The returned object uses the same repository, provider registry and provider dependent registry objects as the original object. Besides that, all other user-specifiable attributes of the object are deep-copied, and all other internal state is reset.

property disable_pull_operations

bool: 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.

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.

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’.

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.

install_subscription_providers(interop_namespace, schema_pragma_file=None, verbose=None)[source]

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

Experimental: New in pywbem 1.3.0 as experimental.

Because these 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.

property interop_namespace_names

NocaseList of string: 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.

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

property namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

property provider_dependent_registry

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

Type

ProviderDependentRegistry

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.

remove_namespace(namespace, verbose=False)[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.

  • verbose (bool) – Verbose mode: Print a message about the namespace deletion.

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

property response_delay

number: 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.

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.

New in pywbem 0.13 as experimental and finalized in 1.2.

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 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:

__repr__()

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

__str__()

Return a short string representation of the DMTFCIMSchema object for human consumption.

build_schema_mof(class_names)

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.

__repr__()[source]

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

__str__()[source]

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

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 (string or list of 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.

property 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

property 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

property 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

property 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

property 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

property schema_zip_file

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

Type

string

property schema_zip_url

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

Type

string

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).

New in pywbem 1.0 as experimental and finalized in 1.2.

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:

__repr__()

Display summary of the repository

add_namespace(namespace)

Add a CIM namespace to the repository.

get_class_store(namespace)

Return the CIM class object store for the namespace provided.

get_instance_store(namespace)

Return the CIM instance object store for the namespace provided.

get_qualifier_store(namespace)

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

load(other)

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

print_repository([dest])

Print the CIM repository to a destination.

remove_namespace(namespace)

Remove a CIM namespace from the repository.

validate_namespace(namespace)

Validate if the namespace exists in the repository.

Attributes:

namespaces

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

__repr__()[source]

Display summary of the repository

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.

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.

property namespaces

NocaseList of string: 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.

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.

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.

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.

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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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:

__repr__()

Return repr(self).

create(name, cim_object)

Add the CIM object to the object store.

delete(name)

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

get(name[, copy])

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([copy])

Return an iterator to the CIM objects in the object store.

len()

Return the count of objects in this object store.

object_exists(name)

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

update(name, cim_object)

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

__repr__()[source]

Return repr(self).

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.

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

get(name, copy=True)[source]

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

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

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

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.

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:

conn = pywbem_mock.FakedWBEMConnection(...)

. . .

interop_ns = "interop"   # or "root/interop"
conn.add_namespace(interop_ns)
ns_provider = pywbem_mock.CIMNamespaceProvider(conn.cimrepository)
conn.register_provider(ns_provider, namespaces=interop_ns)

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.

NOTE: Bidirectional association support was added in pywbem version 1.5. originally the association was visible only in the target namespace for the CreateInstance so Associations and References only handled reference properties in that namespace.

This instance provider handles association instances that cross namespaces. Since the association must be available in all of the namespaces defined by the reference properties of a new instance (References and Associations requests can be issued using any of the reference properties in the instance), the CreateInstance creates the association instance in each namespace defined in a reference property of the instance (it creates shadow instances of the association in each namespace defined by a reference property in the association), ModifyInstance modifies the instance and shadow instances, and DeleteInstance deletes the instance and shadow instances. References and Association requests can be executed on instances defined in any namespace where the association is defined.

These shadow instances are visible in each affected namespaces with the GetInstance and EnumerateInstance requests.

This is transparent. The association instance is visible in each of the affected namespaces and References and Associations requests can be issued using any of the reference properties and the operation source instance.

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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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 to complete the CreateInstance, ModifyInstance, or DeleteInstance, in particular for instance providers that dynamically Create or Modify an instance.

Parameters

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

Methods:

CreateInstance(namespace, new_instance)

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

DeleteInstance(InstanceName)

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

ModifyInstance(modified_instance[, ...])

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

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

add_new_instance(new_instance)

Add the new instance to the repository.

class_exists(namespace, classname)

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

create_multi_namespace_instance(...)

Creates an instance of association new_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

create_new_instance_path(creation_class, ...)

Create the path for the new instance and insert it into the new_instance.path.

filter_properties(obj, property_list)

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.

find_multins_association_ref_namespaces(...)

Return list of namespaces in which this association participates excluding the target namespace.

get_class(namespace, classname[, ...])

Get class from CIM repository.

get_required_class(instance, namespace)

Get the class defined by instance.classname from the repository.

is_association(klass)

Test if klass is an association class.

is_interop_namespace(namespace)

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

is_subclass(klass, superclass, class_store)

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.

modify_multi_namespace_instance(...)

Modifies the instance of association modified_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

post_register_setup(conn)

Method called by provider registration after registation of provider is successful.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_instance_exists(path)

Confirm that the path defined by the path exists in the namespace defined for that path.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

validate_reference_property_endpoint_exists(prop)

Validate that the path defined for the reference property prop exists.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_type

Keyword defining the type of request the provider will service.

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).

  • The creation class of the new instance must not be an abstract class.

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.

  • If new_instance is an association, the reference properties must define existing end-point paths to instances or have value None.

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

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.

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.

  • If there was a property list for the request, only properties defined in that property list are included in the modified_instance.

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.

Validation executed for this default provider:

  • Validate that any reference properties to be modified that are not keys define an association end point instance that currently exists and that the en-point instances exist.

  • If the association crosses namespaces, validate that the association already exists in all namespaces defined in the reference properties.

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

add_new_instance(new_instance)[source]

Add the new instance to the repository. If the instance already exists raises CIMError exception

create_multi_namespace_instance(new_instance, orig_ns, assoc_namespaces)[source]

Creates an instance of association new_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

Each instance is the same as the original instance except that each has its own namespace definition in the CIMInstanceName and the reference properties differ if any reference property does not include the namespace in its definition.

Confirm that this is a multi-namespace association instance, that the class exists in all namespaces. If these tests are OK, confirm that the instance does not exist in any other namespace. Then, place the instance in the remote namespaces

Any case where the instances cannot be created for all required namespaces causes an exception.

Parameters
  • new_instance ((CIMInstance) –

    ) The new instance that will be created

  • orig_ns (string) – The namespace name attached to the CreateInstance request

  • assoc_namespaces (list of string) – List of the namespaces defined in reference properties including the original namespace (orig_ns)

Returns

If the instance is created, the CIM_InstanceName for the created instance is returned.

Asserts:

CIMError if error occurs in validity of other namespaces, class in other namespaces, or creating of instance in other namespaces.

static create_new_instance_path(creation_class, new_instance, namespace)[source]

Create the path for the new instance and insert it into the new_instance.path.

This default provider determines the instance path from the key properties in the new instance. A user-defined provider may do that as well, or invent key properties such as InstanceID. Specifying strict=True from_instance() verifies that all key properties exposed by the class are specified in the new instance, and raises ValueError if key properties are missing.

Parameters
  • creation_class (CIMClass) –

  • determine (The CIM class from which the instance was created. Used to) –

  • properties. (the key) –

  • new_instance (CIMInstance) – The instance from which the CIMInstanceName will be derived.

  • namespace – (string): The namespace in which the instance will be added.

Raises

CIMError if instance name cannot be created from instance.

find_multins_association_ref_namespaces(cim_object, target_namespace)[source]

Return list of namespaces in which this association participates excluding the target namespace. If an empty list is returned, this is not a multi-namespace association.

:param cim_object (CIMInstance or: class:`CIMInstanceName)

object from which references/keybindings searched to determine if multinamespace object. Must be an association.

Parameters

target_namespace (string) – The namespace name provided with the request call (ex. CreateInstance)

Returns

List of namespace names of namespaces in which this association instance participates if there are multiple namespaces. If no other namespaces are defined by reference properties, it returns None.

get_required_class(instance, namespace)[source]

Get the class defined by instance.classname from the repository. This is the common method to validate the class for create instance.

If the class does not exist, generate a CIMError.

static is_association(klass)[source]

Test if klass is an association class.

Return True if klass is an association class and value is True. If association qualifier exists but is False or does not exist return False.

modify_multi_namespace_instance(modified_instance, assoc_namespaces)[source]

Modifies the instance of association modified_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

The instances are the same except the instance path contains the namespace in which the instance exists.

Any case where the instances cannot be modified for all required namespaces causes an exception.

Parameters
  • modified_instance ((CIMInstance) –

    ) The modified instance that is to replace the original instance in the repository

  • assoc_namespaces (list of string) – List of the namespaces defined in reference properties including the original namespace (orig_ns)

Returns

If the instance is created, the CIM_InstanceName for the created instance is returned.

Asserts:

CIMError if error occurs in validity of other namespaces, class in other namespaces, or creating of instance in other namespaces.

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.

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

validate_instance_exists(path)[source]

Confirm that the path defined by the path exists in the namespace defined for that path. Null value for path allowed (i.e. no path defined). Returns True if the object exists or the path is empty otherwise False.

Parameters

path (pywbem.CIMInstanceName) – path to instance to be tested including namespace.

Returns

True if path exists in instance store or path is Null. False if path exists and is not in instance store.

validate_reference_property_endpoint_exists(prop)[source]

Validate that the path defined for the reference property prop exists. Generates INVALID_PARAMETER if it does not exist.

Parameters

prop (pywbem.CIMInstanceName) – Reference property containing CIMInstanceName as value or Null Value

Raises

CIMError if value of property is not a valid instance or Null

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_classnames = '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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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(methodname, localobject, params)

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

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

class_exists(namespace, classname)

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

filter_properties(obj, property_list)

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(namespace, classname[, ...])

Get class from CIM repository.

is_interop_namespace(namespace)

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

is_subclass(klass, superclass, class_store)

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(conn)

Method called by provider registration after registation of provider is successful.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_type

provider_type (string): Keyword defining the type of request the provider will service.

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 (pywbem.NocaseDict) –

    The input parameters for the method invocation, as a pywbem.NocaseDict object, 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 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.

provider_type = 'method'

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

9.6.5. CIM_Namespace provider

This module implements a user-defined provider for the class CIM_Namespace

This provider manages creation and deletion of the instances of the CIM_Namespace class and limits that activity to the server environment interop classname. The CIM_Namespace class is a DMTF defined class that defines an instance for each namespace in the server environment and allows the creation and deletion of server CIM namespaces to be controlled through creation and deletion of instances of the CIM_Namespace class.

class pywbem_mock.CIMNamespaceProvider(cimrepository)[source]

Implements the user defined provider for the class CIM_Namespace.

This provider provides the create, modify, and delete methods for adding an instance of the class CIM_Namspace when a namespace is created or deleted in a pywbem mock environment.

This class and the instances of this class only exist in the WBEM server Interop namespace per DMTF definitions.

This class __init__ saves the cimrepository variable used by methods in this class and by methods of its superclasses (i.e. InstanceWriteProvider).

The provider defines the class level attribute provider_classnames (CIM_Namespace)

This provider presumes that an Interop namespace has been created before the provider object is constructed and fails the constructor if there is not interop_namespace

Parameters

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

Methods:

CreateInstance(namespace, new_instance)

Create an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and if not yet existing create the new namespace in the CIM repository.

DeleteInstance(InstanceName)

Delete an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and in addition delete the namespace represented by it in the CIM repository.

ModifyInstance(modified_instance[, ...])

Modification of CIM_Namespace instance not allowed

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

add_new_instance(new_instance)

Add the new instance to the repository.

class_exists(namespace, classname)

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

create_cimnamespace_instance(conn, ...)

Build and execute CreateInstance for an instance of CIM_Namespace using the namespace parameter as the value of the name property in the instance.

create_multi_namespace_instance(...)

Creates an instance of association new_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

create_new_instance_path(creation_class, ...)

Create the path for the new instance and insert it into the new_instance.path.

filter_properties(obj, property_list)

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.

find_multins_association_ref_namespaces(...)

Return list of namespaces in which this association participates excluding the target namespace.

get_class(namespace, classname[, ...])

Get class from CIM repository.

get_required_class(instance, namespace)

Get the class defined by instance.classname from the repository.

is_association(klass)

Test if klass is an association class.

is_interop_namespace(namespace)

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

is_subclass(klass, superclass, class_store)

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.

modify_multi_namespace_instance(...)

Modifies the instance of association modified_instance in each namespace defined by reference properties of the association instance where the namespace in the reference property is not the namespace defined with the create instance call.

post_register_setup(conn)

Method called by FakedWBEMConnection.register_provider to complete initialization of this provider.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_instance_exists(path)

Confirm that the path defined by the path exists in the namespace defined for that path.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

validate_reference_property_endpoint_exists(prop)

Validate that the path defined for the reference property prop exists.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_classnames

provider_classnames (string): The classname for this provider

CreateInstance(namespace, new_instance)[source]

Create an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and if not yet existing create the new namespace in the CIM repository.

See ~pywbem_mock.InstanceWriteProvider.CreateInstance for documentation of validation and description of input parameters, noting extra conditions for this provider as described below:

Parameters
  • namespace (string) – Must be a valid Interop namespace.

  • new_instance (CIMInstance) –

    The following applies regarding its properties:

    • ’Name’ property: This property is required since it defines the name of the new namespace to be created.

    • ’CreationClassName’ property: This property is required and its value must match the class name of the new instance.

Raises

CIMError – (CIM_ERR_INVALID_PARAMETER) if namespace is not the Interop namespace in the CIM repository or the Name property does not exist or the other properties cannot be added to the instance.

DeleteInstance(InstanceName)[source]

Delete an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and in addition delete the namespace represented by it in the CIM repository.

See ~pywbem_mock.InstanceWriteProvider.CreateInstance for documentation of validation and description of input parameters, noting extra conditions for this provider as described below:

The namespace to be deleted must be empty and must not be the Interop namespace.

Parameters

InstanceName – (CIMInstanceName): The keybinding Name must exist; it defines the namespace to be deleted.

Raises
  • CIMError – (CIM_ERR_INVALID_PARAMETER)

  • CIMError – (CIM_ERR_NAMESPACE_NOT_EMPTY)

ModifyInstance(modified_instance, IncludeQualifiers=None)[source]

Modification of CIM_Namespace instance not allowed

__repr__()[source]

Return repr(self).

static create_cimnamespace_instance(conn, namespace, interop_namespace, klass)[source]

Build and execute CreateInstance for an instance of CIM_Namespace using the namespace parameter as the value of the name property in the instance. The instance is created in the interop_namespace

Parameters
  • namespace (string) – Namespace that this instance defines.

  • interop_namespace (string) – Interop namespace for this environment.

  • klass (CIMClass) – The CIM class CIM_Namespace which is used to create the instance.

Raises

CIMError – For errors encountered with CreateInstance

post_register_setup(conn)[source]

Method called by FakedWBEMConnection.register_provider to complete initialization of this provider. This method is called after the required classes are installed in the cim_repository

This is necessary because pywbem_mock does not allow user-defined providers for the instance read operations such as EnumerateInstances so the instance for each namespace must be exist in the repository.

This method:

  1. Inserts instances of CIM_Namespace for every namespace in the CIM repository.

provider_classnames = 'CIM_Namespace'

provider_classnames (string): The classname for this provider

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.

New in pywbem 1.1 as experimental and finalized in 1.2.

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:

__repr__()

Return repr(self).

add_dependents(mock_script_path, dependent_paths)

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

iter_dependents(mock_script_path)

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

load(other)

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

__repr__()[source]

Return repr(self).

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.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.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

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.OBJECTMANAGERCREATIONCLASSNAME = 'CIM_ObjectManager'

Value for the CIM_ObjectManagerCreationClassName defined in the CIM_ObjectManager class.

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.OPEN_MAX_TIMEOUT = 40

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

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.SYSTEMNAME = 'MockSystem_WBEMServerTest'

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