9. Mock support

Experimental: New in pywbem 0.12.0 as experimental.

9.1. Overview

The pywbem package contains the pywbem_mock subpackage which provides mock support that enables usage of the pywbem library without a WBEM server. This subpackage is used for testing the pywbem library itself and can be used for the development and testing of Python programs that use the pywbem library.

The pywbem mock support consists of the pywbem_mock.FakedWBEMConnection class that establishes a faked connection. That 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 instead operate on a local in-memory repository of CIM objects (the mock repository).

As a result, the operation methods of FakedWBEMConnection are those inherited from WBEMConnection, so they have the exact same input parameters, output parameters, return values, and even most of the raised exceptions, as when being invoked on a WBEMConnection object against a WBEM server.

Each FakedWBEMConnection object has its own mock repository. The mock repository contains the same kinds of CIM objects a WBEM server repository contains: CIM classes, CIM instances, and CIM qualifier types (declarations), all contained in CIM namespaces.

Because FakedWBEMConnection operates only on the mock repository, the class does not have any connection- or security-related constructor parameters.

Like WBEMConnection, FakedWBEMConnection has a default CIM namespace that can be set upon object creation.

FakedWBEMConnection has some additional methods that provide for adding CIM classes, instances and qualifier types to its mock repository. See Building the mock repository for details.

There are no setup methods to remove or modify CIM objects in the mock repository. However, if needed, that can be done by using operation methods such as DeleteClass() or ModifyInstance().

The mock repository supports two operation modes:

  • full mode: The repository must contain the classes and qualifier types that are needed for the operations that are invoked. This results in a behavior of the faked operations that is close to the behavior of the operations of a real WBEM server.
  • lite mode: The repository does not need to contain any classes and qualifier types, and can be used when it contains only instances. This simplifies the setup of the mock repository for users, but it also affects the behavior of the faked instance operations to be farther away from the behavior of the operations of a real WBEM server. For example, the faked EnumerateInstances operation will not return instances of subclasses when DeepInheritance is set, because without looking at classes, there is no way it can find out what the subclasses are. And of course, class operations and qualifier operations that retrieve objects don’t work at all if the mock repository does not contain them.

The operation mode of the mock repository is selected when creating a FakedWBEMConnection object, through its repo_lite init parameter. Full mode is the default.

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

import pywbem
import pywbem_mock

# MOF string defining qualifiers, class, and instance
mof = """
    # CIM qualifier types (declarations)
    Qualifier Key : boolean = false,
        Scope(property, reference),
        Flavor(DisableOverride, ToSubclass);
    Qualifier Description : string = null,
        Scope(any),
        Flavor(EnableOverride, ToSubclass, Translatable);

    # A CIM class declaration
         [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);
    };

    # A CIM instance
    instance of CIM_Foo as $I1 { InstanceID = "I1"; SomeData=3 };
    """

# Create a faked connection (with a mock repository in full mode)
conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/cimv2')

# Compile the MOF string and add its CIM objects to the default namespace
# of the mock 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();

# 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"})

Pywbem mock supports:

  1. All of the WBEMConnection operation methods that communicate with the WBEM server (see below for list of 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.

Pywbem mock does NOT support:

  1. CIM-XML protocol security and security constructor parameters of WBEMConnection.
  2. Dynamic WBEM server providers in that the data for responses is from the mock repository that is built before the request rather than from resources accessed by such providers. This means there is no dynamic determination of property values for newly created CIM instances. Therefore, creating CIM instances requires that all keybinding values as well as all other property values must be provided as input to the CreateInstance() operation by the user.
  3. 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.
  4. Filter processing of the FQL (see DSP0212) 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.
  5. 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.
  6. Log entries for HTTP request and response in the logging support of WBEMConnection, because it does not actually build the HTTP requests or responses.
  7. Generating CIM indications.
  8. Some of the functionality that may be implemented in real WBEM servers such as the __Namespace__ class/provider or the CIM_Namespace class/provider, because these are WBEM server-specific implementations and not WBEM request level capabilities. Note that such capabilities can be at least partly built on top of the existing capabilities by inserting corresponding CIM instances into the mock repository.

9.2. Faked WBEM operations

The pywbem_mock.FakedWBEMConnection class supports the same WBEM operations that are supported by the pywbem.WBEMConnection class.

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

The faked operations get the data to be returned from the mock repository of the faked connection, and put the data provided in operation parameters that modify objects (create, modify, and delete operations) into that mock 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 a number of limitations and differences between the behavior of the faked operations and a real WBEM server.

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

9.2.1. Faked instance operations

Instance operations work in both operation modes of the repository.

The operations that retrieve objects require instances in the repository for the instances to be recovered. We allow some of these methods to try to return data if the class repository is empty but they may react differently if there are classes in the repository.

  • GetInstance: Behaves like GetInstance(), except that the behavior of property selection for the returned instance when LocalOnly is set depends on the operation mode of the mock repository: In lite mode, property selection is based upon the class_origin attribute of the properties of the instance. In full mode, property selection is based upon the classes in which they are defined.
  • EnumerateInstances: Behaves like EnumerateInstances(), except for these differences when the mock repository is in lite mode: When DeepInheritance is set, instances of subclasses of the specified class will not be returned, and LocalOnly is ignored and treated as if it was set to False.
  • EnumerateInstanceNames: Behaves like EnumerateInstances(), except for this difference when the mock repository is in lite mode: When DeepInheritance is set, instances of subclasses of the specified class will not be returned.
  • CreateInstance: Behaves like CreateInstance(), except for these differences: This operation requires that all key properties are specified in the new instance since the mock repository has no support for dynamically setting key properties as a dynamic provider for the class in a real WBEM server might have. This operation requires that the mock repository is in full mode and that the class of the new instance exists in the mock repository. It fails with not supported if the mock repository is in lite mode.
  • ModifyInstance: Behaves like ModifyInstance(). This operation requires that the mock repository is in full mode and that the class of the instance exists in the mock repository. It fails with not supported if the mock repository is in lite mode.
  • DeleteInstance: Behaves like DeleteInstance(), except for this difference depending on the operation mode of the mock repository: In lite mode, the operation does not check for existence of the class of the instance. In full mode, the operation validates the existence of the class of the instance. In the current implementation, this operation does not check for association instances referencing the instance to be deleted, so any such instances become dangling references.
  • ExecQuery: This operation is not currently implemented. Once implemented: Behaves like ExecQuery(), except that it returns instances based on a very limited parsing of the query string: Generally, the SELECT and FROM clauses are evaluated, and the WHERE clause is ignored. The query string is not validated for correctness. The query language is not validated.

9.2.2. Faked association operations

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

  • AssociatorNames: Behaves like AssociatorNames(), with the following exceptions and requirements: For class-level use, the mock repository must be in full mode and the source, target, and association classes and their subclasses must exist in the mock repository. For instance-level use, correct results are returned if the mock repository is in full mode and the the source, target, and association classes and their subclasses exist in the repository. More limited results are returned in lite mode, because the class hierarchy is not considered when selecting the instances to be returned.
  • Associators: Behaves like Associators(), with the exceptions and requirements described for AssociatorNames, above.
  • ReferenceNames: Behaves like ReferenceNames(), with the exceptions and requirements described for AssociatorNames, above.
  • References: Behaves like References(), with the exceptions and 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 a callback function that performs the actual task of the CIM method. The mock repository must be in full operation mode.

The callback function must have the signature defined in the method_callback_interface() function and must be registered with the mock repository through add_method_callback() for a particular combination of namespace, class, and CIM method name.

When the callback function is invoked on behalf of an InvokeMethod operation, the target object of the method invocation (class or instance) is provided to the callback function, in addition to the method input parameters.

The callback function can access the mock repository of the faked connection using the normal WBEM operation methods.

The callback function is expected to return a tuple consisting of two items:

The following is an example for invoking the faked InvokeMethod operation with a simple callback function.

import pywbem
import pywbem_mock

def method1_callback(conn, objectname, methodname, params):
    """
    Callback function that demonstrates what can be done, without being
    really useful.
    """

    # Access input parameters
    ip1 = params['IP1']

    # Access the mock repository through the faked connection object.
    # In case of a static CIM method, objectname is a CIMClassName object.
    cl = conn.GetClass(objectname)

    # Set return value and output parameters
    rtn_val = 0
    op1 = CIMParameter('OP1', 'string', value='Some output data')
    return rtn_val, [op1]

mof = """
    Qualifier In : boolean = true,
        Scope(parameter),
        Flavor(DisableOverride, ToSubclass);

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

    Qualifier Out : boolean = false,
        Scope(parameter),
        Flavor(DisableOverride, ToSubclass);

    class TST_Class {

        string InstanceID;

          [Static,
           Description("Static method with input and output parameters")]
        uint32 Method1(
            [IN, Description("Input param 1")]
          string IP1,
            [IN (false), OUT, Description("Output param 1")]
          string OP1);
"""

# Create a faked connection
conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/cimv2')

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

# Register the method callback function to the mock repository, for the
# default namespace of the connection
conn.add_method_callback('TST_Class', 'Method1', method1_callback)

# Invoke static method Method1
params = [('IP1', 'someData')]
result = conn.InvokeMethod('Method1', 'TST_Class', Params=params)

print('Return value: %r' % result[0])
print('Output parameters: %r' % (result[1],))

9.2.4. Callback functions for faked method invocation

The callback functions for faked method invocation must have the following signature:

pywbem_mock.method_callback_interface(conn, objectname, methodname, **params)[source]

Experimental: New in pywbem 0.12 as experimental.

Interface for user-provided callback functions for CIM method invocation on a faked connection.

Parameters:
  • conn (FakedWBEMConnection) – Faked connection. This can be used to access the mock repository of the faked connection, via its operation methods (e.g. GetClass).
  • objectname (CIMInstanceName or CIMClassName) –

    The object path of the target object of the invoked method, as follows:

    • Instance-level call: The instance path of the target instance, as a CIMInstanceName object which has its namespace property set to the target namespace of the invocation. Its host property will not be set.
    • Class-level call: The class path of the target class, as a CIMClassName object which has its namespace property set to the target namespace of the invocation. Its host property will not be set.
  • methodname (string) – The CIM method name that is being invoked. This is the method name for which the callback function was registered. This parameter allows a single callback function to be registered for multiple methods.
  • params (NocaseDict) –

    The input parameters for the method that were passed to the InvokeMethod operation.

    Each dictionary item represents a single input parameter for the CIM method and is a CIMParameter object, regardless of how the input parameter was passed to the InvokeMethod() method.

    The CIMParameter object will have at least the following properties set:

    • name (string): Parameter name (case independent).
    • type (string): CIM data type of the parameter.
    • value (CIM data type): Parameter value.
Returns:

The callback function must return a tuple consisting of:

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

  • out_params (iterable of CIMParameter):

    Each item represents a single output parameter of the CIM method. The CIMParameter objects must have at least the following properties set:

    • name (string): Parameter name (case independent).
    • type (string): CIM data type of the parameter.
    • value (CIM data type): Parameter value.

Return type:

tuple

Raises:

Since the callback function mocks a CIM method invocation, it should raise CIMError exceptions to indicate failures. Any other exceptions raised by the callback function will be mapped to CIMError exceptions with status CIM_ERR_FAILED and a message that contains information about the exception including a traceback.

9.2.5. 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.6. 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 simply 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.7. Faked class operations

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

  • GetClass: Behaves like GetClass(). Requires that the class to be returned is in the mock repository.
  • EnumerateClasses: Behaves like EnumerateClasses(). Requires that the class specified in the ClassName parameter as well as the classes to be returned are in the mock repository.
  • EnumerateClassNames: Behaves like EnumerateClassNames(). Requires that the class specified in the ClassName parameter as well as the classes to be returned are in the mock repository.
  • CreateClass: Behaves like CreateClass(). Requires that the superclass of the new class (if it specifies one) is in the mock 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 mock repository.
  • ModifyClass: Not currently implemented.

9.2.8. Faked qualifier operations

Qualifier operations only work if the mock repository is in full operation mode.

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

9.3. Building the mock repository

The following methods can be used to add CIM instances, classes and qualifier types to the mock repository of a FakedWBEMConnection() object:

  • add_cimobjects() adds the specified CIM objects to the mock repository.

    The reason for having this method in addition to CreateInstance is that it performs fewer checks.

  • compile_mof_string() and compile_mof_file() compile MOF in a string or file, respectively, and add the resulting CIM objects to the mock repository.

    These methods allow the user to easily build a consistent mock repository by defing the MOF for the objects to be inserted into the repository.

In all cases, the existing mock repository content is used for resolving any prerequisite objects:

  • For a CIM class to be added, the superclass of that class as well as CIM qualifier types for the qualifiers used by that class must exist.
  • For a CIM instance to be added, its CIM creation class must exist.

Some CIM objects that are used by a CIM object to be added do not need to exist in the mock repository, which in fact allows forward references:

  • CIM classes specified in reference properties or in reference parameters of methods of a class to be added do not need to exist.
  • CIM classes specified in qualifiers (for example, in the EmbeddedInstance qualifier) of a class to be added do not need to exist.

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

This example creates a faked connection and sets up its mock 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 mock 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()

This code displays the mock repository in MOF format after adding these objects:

# ========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.3.2. Example: Set up instances from single CIM objects

Based on the mock repository content of the previous example, this example adds two class instances and one association instance from their CIM objects.

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

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

Experimental: New in pywbem 0.12 as experimental.

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

For a description of the operation methods on this class, see Faked WBEM operations.

Each FakedWBEMConnection object has its own mock 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.

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 operaitons are used in the iter operations. 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.

  • repo_lite (bool) – Flag to set the operation mode of the mock repository. If True, lite mode is set. If False, full mode is set.
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 constructor parameter.

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 namespace of the mock repository.

If the CIM namespace does not exist, it is created.

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 mock repository remains unchanged.

Parameters:
  • mof_file (string) – Path name of the file containing the MOF definitions to be compiled.
  • namespace (string) – The name of the target CIM namespace in the mock repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
  • search_paths (iterable of string) – An iterable of directory path names where MOF dependent files will be looked up. See the description of the search_path init parameter of the MOFCompiler class for more information on MOF dependent files.
  • verbose (bool) – Controls whether to issue more detailed compiler messages.
Raises:
  • IOError – MOF file not found.
  • MOFParseError – Compile error in the MOF.
  • CIMError – Failure related to the CIM objects in the mock repository.
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 namespace of the mock repository.

If the CIM namespace does not exist, it is created.

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 mock repository remains unchanged.

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

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

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

If the CIM namespace does not exist, it is created.

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 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 mock 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 mock repository remains unchanged.

Parameters:
  • objects (CIMClass or CIMInstance or CIMQualifierDeclaration, or list of them) – CIM object or objects to be added to the mock repository. The list may contain different kinds of CIM objects.
  • namespace (string) – The name of the target CIM namespace in the mock 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.
add_method_callback(classname, methodname, method_callback, namespace=None)[source]

Register a callback function for a CIM method that will be called when the CIM method is invoked via InvokeMethod.

Parameters:
  • classname (string) –

    The CIM class name for which the callback function is registered.

    The faked InvokeMethod implementation uses this information to look up the callback function from its parameters.

    For method invocations on a target instance, this must be the class name of the creation class of the target instance.

    For method invocations on a target class, this must be the class name of the target class.

  • methodname (string) –

    The CIM method name for which the callback function is registered.

    The faked InvokeMethod implementation uses this information to look up the callback function from its parameters.

  • method_callback (method_callback_interface()) – The callback function.
  • namespace (string) –

    The CIM namespace for which the callback function is registered.

    If None, the callback function is registered for the default namespace of the connection.

    The faked InvokeMethod implementation uses this information to look up the callback function from its parameters.

display_repository(namespaces=None, dest=None, summary=False, output_format='mof')[source]

Display the namespaces and objects in the mock 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 mock repository are displayed.
  • dest (string) – File path of the 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 mock 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’.