def __init__(self, creds, MethodName, ObjectName, namespace = 'root/cimv2',
                 **kwargs):

        # Convert string to CIMClassName

        obj = ObjectName

        if isinstance(obj, StringTypes):
            obj = CIMClassName(obj, namespace = namespace)

        if isinstance(obj, CIMInstanceName) and obj.namespace is None:
            obj = ObjectName.copy()
            obj.namespace = namespace

        # Make the method call

        payload = self.methodcallPayload(
            MethodName,
            obj,
            namespace,
            **kwargs)

        WBEMClientFactory.__init__(
            self, 
            creds, 
            operation = 'MethodCall', 
            method = MethodName,
            object = obj, 
            payload = payload)
Example #2
0
    def __init__(self,
                 creds,
                 MethodName,
                 ObjectName,
                 namespace='root/cimv2',
                 **kwargs):

        # Convert string to CIMClassName

        obj = ObjectName

        if isinstance(obj, StringTypes):
            obj = CIMClassName(obj, namespace=namespace)

        if isinstance(obj, CIMInstanceName) and obj.namespace is None:
            obj = ObjectName.copy()
            obj.namespace = namespace

        # Make the method call

        payload = self.methodcallPayload(MethodName, obj, namespace, **kwargs)

        WBEMClientFactory.__init__(self,
                                   creds,
                                   operation='MethodCall',
                                   method=MethodName,
                                   object=obj,
                                   payload=payload)
Example #3
0
def test_complexassoc_classnames(conn, ns, target, ro, rr, ac, rc, mof,
                                 exp_rslt, complex_assoc_mof, cond):
    # pylint: disable=redefined-outer-name,invalid-name
    """
    Test associatornames class operations against a ternary model defined by
    the fixture complex_assoc_mof. We do not test the associator calls
    since that logic just takes the names and expands to return instances
    """
    if not cond:
        pytest.skip("Condition for test case not met")

    skip_if_moftab_regenerated()

    mof = mof or ""
    conn.compile_mof_string(complex_assoc_mof + mof, namespace=ns)

    if ns is not None:
        target = CIMClassName(target, namespace=ns)
    if cond == 'pdb':
        # pylint: disable=import-outside-toplevel
        import pdb
        pdb.set_trace()  # pylint: disable=forgotten-debug-statement

    rtn_clns = conn.AssociatorNames(target,
                                    AssocClass=ac,
                                    Role=ro,
                                    ResultRole=rr,
                                    ResultClass=rc)
    exp_ns = ns or conn.default_namespace

    assert isinstance(rtn_clns, list)
    for cln in rtn_clns:
        assert isinstance(cln, CIMClassName)
        assert cln.host == conn.host
        assert cln.namespace == exp_ns

    exp_clns = [
        CIMClassName(classname=n, namespace=exp_ns, host=conn.host)
        for n in exp_rslt
    ]
    if VERBOSE:
        print('\nACT %s\nEXP %s' %
              ([c.classname
                for c in rtn_clns], [c.classname for c in exp_clns]))

    request = "pywbemcli class associators {0} --role {1} --assoc-class {2} " \
        "--result-role {3} --result-class {4}". \
        format(target, ro, ac, rr, rc)
    save_data(conn, complex_assoc_mof, request, rtn_clns, exp_clns)

    assert set(cln.classname.lower() for cln in exp_clns) == \
        set(cln.classname.lower() for cln in rtn_clns)
Example #4
0
def test_complexref_classnames(conn, ns, target, ro, rc, mof, exp_rslt,
                               complex_assoc_mof, cond):
    # pylint: disable=redefined-outer-name,invalid-name
    """
    Test referencenames class operations against a ternary model defined by
    the fixture complex_assoc_mof
    """
    if not cond:
        pytest.skip("Condition for test case not met")

    skip_if_moftab_regenerated()

    mof = mof or ""
    conn.compile_mof_string(complex_assoc_mof + mof, namespace=ns)

    if ns is not None:
        target = CIMClassName(target, namespace=ns)
    if cond == 'pdb':
        # pylint: disable=import-outside-toplevel
        import pdb
        pdb.set_trace()  # pylint: disable=forgotten-debug-statement

    rtn_clns = conn.ReferenceNames(target, ResultClass=rc, Role=ro)
    exp_ns = ns or conn.default_namespace

    assert isinstance(rtn_clns, list)
    for cln in rtn_clns:
        assert isinstance(cln, CIMClassName)
        assert cln.host == conn.host
        assert cln.namespace == exp_ns

    exp_clns = [
        CIMClassName(classname=n, namespace=exp_ns, host=conn.host)
        for n in exp_rslt
    ]

    request = "pywbemcli class references {0} --role {1} --result_class {2}". \
        format(target, ro, rc)
    response = [c.classname for c in exp_clns]
    exp_response = [c.classname for c in exp_clns]
    save_data(conn, complex_assoc_mof, request, response, exp_response)

    if VERBOSE:
        print('\nACT %s\nEXP %s' %
              ([c.classname
                for c in rtn_clns], [c.classname for c in exp_clns]))

    assert set(cln.classname.lower() for cln in exp_clns) == \
        set(cln.classname.lower() for cln in rtn_clns)
Example #5
0
    def __init__(self, creds, classname, namespace='root/cimv2', **kwargs):
        self.classname = classname
        self.namespace = namespace
        self.context = None
        self.property_filter = (None, None)
        self.result_component_key = None

        if not kwargs.get('MaxObjectCount'):
            kwargs['MaxObjectCount'] = DEFAULT_ITER_MAXOBJECTCOUNT

        if 'PropertyFilter' in kwargs:
            self.property_filter = kwargs['PropertyFilter']
            del kwargs['PropertyFilter']

        if 'ResultComponentKey' in kwargs:
            self.result_component_key = kwargs['ResultComponentKey']
            del kwargs['ResultComponentKey']

        payload = self.imethodcallPayload('OpenEnumerateInstances',
                                          namespace,
                                          ClassName=CIMClassName(classname),
                                          **kwargs)

        WBEMClientFactory.__init__(self,
                                   creds,
                                   operation='MethodCall',
                                   method='OpenEnumerateInstances',
                                   object=namespace,
                                   payload=payload)
Example #6
0
def cmd_class_delete(context, classname, options):
    """Delete a class from the WBEM server repository"""
    if options['namespace']:
        classname = CIMClassName(classname, namespace=options['namespace'])

    try:
        instnames = context.conn.EnumerateInstanceNames(classname)
        subclassnames = context.conn.EnumerateClassNames(ClassName=classname,
                                                         DeepInheritance=True)
    except Error as er:
        raise_pywbem_error_exception(er)

    if subclassnames:
        raise click.ClickException('Delete rejected; subclasses exist')

    if not options['force']:
        if instnames:
            raise click.ClickException('Delete rejected; instances exist')
    else:
        for instname in instnames:
            context.conn.DeleteInstance(instname)

    instnames = context.conn.EnumerateInstanceNames(classname)
    if instnames:
        raise click.ClickException('Delete rejected; instance delete failed')

    try:
        context.conn.DeleteClass(classname)
        if context.verbose:
            context.spinner_stop()
            click.echo('Deleted class {}.'.format(classname))
    except Error as er:
        raise_pywbem_error_exception(er)
Example #7
0
def cmd_class_associators(context, classname, options):
    """
    Execute the references request operation to get references for
    the classname defined
    """
    if options['namespace']:
        classname = CIMClassName(classname, namespace=options['namespace'])

    try:
        if options['names_only']:
            results = context.conn.AssociatorNames(
                classname,
                AssocClass=options['assoc_class'],
                Role=options['role'],
                ResultClass=options['result_class'],
                ResultRole=options['result_role'])
        else:
            results = context.conn.Associators(
                classname,
                AssocClass=options['assoc_class'],
                Role=options['role'],
                ResultClass=options['result_class'],
                ResultRole=options['result_role'],
                IncludeQualifiers=options['no_qualifiers'],
                IncludeClassOrigin=options['include_classorigin'],
                PropertyList=resolve_propertylist(options['propertylist']))

        display_cim_objects(context,
                            results,
                            context.output_format,
                            summary=options['summary'],
                            sort=True)

    except Error as er:
        raise_pywbem_error_exception(er)
Example #8
0
def test_leaks_CIMClassName_minimal():
    """
    Test function with a minimal CIMClassName object (i.e. no keybindings).
    """
    _ = CIMClassName(
        'CIM_Foo',
        namespace='root',
        host='woot.com',
    )
Example #9
0
    def __init__(self, creds, obj, namespace='root/cimv2', **kwargs):

        if isinstance(obj, CIMInstanceName):
            kwargs['ObjectName'] = obj
        else:
            kwargs['ObjectName'] = CIMClassName(obj)

        payload = self.imethodcallPayload('References', namespace, **kwargs)

        WBEMClientFactory.__init__(self,
                                   creds,
                                   operation='MethodCall',
                                   method='References',
                                   object=namespace,
                                   payload=payload)
Example #10
0
    def __init__(self, creds, classname, namespace='root/cimv2', **kwargs):

        self.classname = classname
        self.namespace = namespace

        payload = self.imethodcallPayload('GetClass',
                                          namespace,
                                          ClassName=CIMClassName(classname),
                                          **kwargs)

        WBEMClientFactory.__init__(self,
                                   creds,
                                   operation='MethodCall',
                                   method='GetClass',
                                   object=namespace,
                                   payload=payload)
Example #11
0
    def add_filter(self, sub_mgr, server_id, filter_id, owned=True):
        """
        Create a single filter definition in the sub_mgr (which adds it to
        the repository) and returns the path of the new filter instance.
        This creates a filter specifically these tests
        """
        # pylint: disable=attribute-defined-outside-init
        self.test_class = 'Test_IndicationProviderClass'
        self.test_class_namespace = 'test/TestProvider'

        self.test_query = 'SELECT * from %s' % self.test_class
        self.test_classname = CIMClassName(self.test_class,
                                           namespace=self.test_class_namespace)

        filter_ = sub_mgr.add_filter(server_id,
                                     self.test_class_namespace,
                                     self.test_query,
                                     query_language="DMTF:CQL",
                                     filter_id=filter_id,
                                     owned=owned)
        return filter_.path
Example #12
0
        "Object is a CIMInstance object",
        dict(
            obj=CIMInstance('CIM_Foo'),
            exp_type_name=u'string',  # embedded object
        ),
        None,
        None,
        True),
    ("Object is a CIMInstanceName object",
     dict(
         obj=CIMInstanceName('CIM_Foo'),
         exp_type_name=u'reference',
     ), None, None, True),
    ("Object is a CIMClassName object",
     dict(
         obj=CIMClassName('CIM_Foo'),
         exp_type_name=None,
     ), TypeError, None, True),
]


@pytest.mark.parametrize(
    "desc, kwargs, exp_exc_types, exp_warn_types, condition",
    TESTCASES_CIMTYPE)
@simplified_test_function
def test_cimtype(testcase, obj, exp_type_name):
    """
    Test function for cimtype().
    """

    # The code to be tested
Example #13
0
def run_test(svr_url, listener_host, user, password, http_listener_port, \
             https_listener_port, requested_indications, repeat_loop):
    """
        Runs a test that:
        1. Creates a server
        2. Creates a dynamic listener and starts ti
        3. Creates a filter and subscription
        4. Calls the server to execute a method that creates an indication
        5. waits for indications to be received.
        6. Removes the filter and subscription and stops the listener
    """
    if os.path.exists(LOGFILE):
        os.remove(LOGFILE)
    try:
        conn = WBEMConnection(svr_url, (user, password), no_verification=True)
        server = WBEMServer(conn)

        # Create subscription_manager here to be sure we can communicate with
        # server before Creating listener, etc.
        sub_mgr = WBEMSubscriptionManager(
            subscription_manager_id='pegasusIndicationTest')

        # Add server to subscription manager
        server_id = sub_mgr.add_server(server)
        old_filters = sub_mgr.get_all_filters(server_id)
        old_subs = sub_mgr.get_all_subscriptions(server_id)
        # TODO filter for our sub mgr
        if len(old_subs) != 0 or len(old_filters) != 0:
            sub_mgr.remove_subscriptions(server_id,
                                         [inst.path for inst in old_subs])
            for filter_ in old_filters:
                sub_mgr.remove_filter(server_id, filter_.path)

    except ConnectionError as ce:
        print('Connection Error %s with %s' % (ce, svr_url))
        sys.exit(2)

    except Error as er:
        print('Error communicationg with WBEMServer %s' % er)
        sys.exit(1)

    # Create the listener and listener call back and start the listener
    #pylint: disable=global-statement
    global LISTENER
    ####stream=sys.stderr,
    logging.basicConfig(filename='pegasusindicationtest.log',
                        level=logging.INFO,
                        format='%(asctime)s %(levelname)s: %(message)s')
    # Create and start local listener
    LISTENER = WBEMListener(listener_host,
                            http_port=http_listener_port,
                            https_port=https_listener_port)

    # Start connect and start listener.
    LISTENER.add_callback(consume_indication)
    LISTENER.start()

    listener_url = '%s://%s:%s' % ('http', 'localhost', http_listener_port)
    sub_mgr.add_listener_destinations(server_id, listener_url)

    # Create a dynamic alert indication filter and subscribe for it
    filter_ = sub_mgr.add_filter(server_id,
                                 TEST_CLASS_NAMESPACE,
                                 TEST_QUERY,
                                 query_language="DMTF:CQL")
    subscriptions = sub_mgr.add_subscriptions(server_id, filter_.path)

    # Request server to create indications by invoking method
    # This is pegasus specific
    class_name = CIMClassName(TEST_CLASS, namespace=TEST_CLASS_NAMESPACE)

    while repeat_loop > 0:
        repeat_loop += -1
        global RECEIVED_INDICATION_COUNT, INDICATION_START_TIME
        RECEIVED_INDICATION_COUNT = 0
        INDICATION_START_TIME = None
        if send_request_for_indications(conn, class_name,
                                        requested_indications):
            # Wait for indications to be received.
            success = wait_for_indications(requested_indications)
            if not success:
                insts = conn.EnumerateInstances('PG_ListenerDestinationQueue',
                                                namespace='root/PG_Internal')
                for inst in insts:
                    print('%s queueFullDropped %s, maxretry %s, InQueue %s' % \
                          (inst['ListenerDestinationName'],
                           inst['QueueFullDroppedIndications'],
                           inst['RetryAttemptsExceededIndications'],
                           inst['CurrentIndications']))
        if repeat_loop > 0:
            time.sleep(requested_indications / 150)

    sub_mgr.remove_subscriptions(server_id,
                                 [inst.path for inst in subscriptions])
    sub_mgr.remove_filter(server_id, filter_.path)
    sub_mgr.remove_server(server_id)
    LISTENER.stop()

    # Test for all expected indications received.
    if RECEIVED_INDICATION_COUNT != requested_indications:
        print('Incorrect count of indications received expected=%s, received'
              '=%s' % (requested_indications, RECEIVED_INDICATION_COUNT))
        sys.exit(1)
    else:
        print('Success, %s indications' % requested_indications)
    print('Max time between indications %s' % MAX_TIME_BETWEEN_INDICATIONS)
Example #14
0
     TypeError,
     None,
     False  # Fails with connection failure.
 ),
 ("Test enumerateinstances, fails, classname is not CIMClassname or Str",
  dict(
      init_kwargs={},
      method='enumerateinstances',
      args=[CIMInstanceName("CIM_Blah")],
      kwargs={},
  ), TypeError, None, OK),
 ("Test GetInstance, invalid InstanceName tyhpe",
  dict(
      init_kwargs={},
      method='getinstance',
      args=[CIMClassName("CIM_Blah")],
      kwargs={},
  ), TypeError, None, OK),
 ("Test ModifyInstance, No path in ModifiedInstance",
  dict(
      init_kwargs={},
      method='modifyinstance',
      args=[CIMInstance("CIMBlah")],
      kwargs={},
  ), ValueError, None, OK),
 ("Test EnumerateInstances, Invalid args type",
  dict(
      init_kwargs={},
      method='enumerateinstances',
      args=[CIMClass("CIMBlah")],
      kwargs={},