def test_init(self, desc, files, init_kwargs, exp_attrs, exp_exc, exp_exc_regex): # pylint: disable=no-self-use """ Test initialization of a WBEMConnection object. """ try: for fname in files: open(fname, 'a').close() # create empty file if exp_exc is not None: with pytest.raises(exp_exc) as exc_info: # The code to be tested WBEMConnection('http://localhost', **init_kwargs) exc = exc_info.value exc_msg = str(exc) if exp_exc_regex: assert re.search(exp_exc_regex, exc_msg) else: # The code to be tested conn = WBEMConnection('http://localhost', **init_kwargs) for name in exp_attrs: exp_value = exp_attrs[name] act_value = getattr(conn, name) assert act_value == exp_value finally: for fname in files: os.remove(fname)
def test_log_output_conn(self): # pylint: disable=redefined-outer-name """ Test log output of creating a WBEMConnection object and executing a GetQualifier operation that fails. """ url = 'http://dummy:5988' # File URL to get quick result conn = WBEMConnection(url) try: conn.GetQualifier('Association') except ConnectionError: pass else: raise AssertionError("ConnectionError exception not raised") exp_line_patterns = [ r".*-{0}\..*-Connection:.* WBEMConnection\(url='{1}'".format( LOGGER_API_CALLS_NAME, url), r".*-{0}\..*-Request:.* GetQualifier\(QualifierName='Association'". format(LOGGER_API_CALLS_NAME), r".*-{0}\..*-Request:.* POST /cimom .* CIMMethod:'GetQualifier'". format(LOGGER_HTTP_NAME), r".*-{0}\..*-Exception:.* GetQualifier.*ConnectionError".format( LOGGER_API_CALLS_NAME), ] with open(TEST_OUTPUT_LOG, "r") as log_fp: log_lines = log_fp.readlines() assert len(log_lines) == len(exp_line_patterns) for i, pattern in enumerate(exp_line_patterns): assert re.match(pattern, log_lines[i])
def test_with_params(self, irval, ec, eos, eos_exp, exctype_exp): # pylint: disable=no-self-use,protected-access """ Test combminations of IRETURNVALUE, EOS and EnumerationContext for both good and fail responses. """ conn = WBEMConnection('http://localhost') result = [(u'IRETURNVALUE', {}, irval), (u'EnumerationContext', None, ec), (u'EndOfSequence', None, eos)] if exctype_exp: with pytest.raises(exctype_exp): # pylint: disable=protected-access result = conn._get_rslt_params(result, 'root/blah') else: # pylint: disable=protected-access result = conn._get_rslt_params(result, 'root/blah') # the _get_rslt_params method sets context to None if eos True ecs = None if eos_exp is True else (ec, 'root/blah') assert result == (irval, eos_exp, ecs)
def test_namespace_slashes_set(self): # pylint: disable=no-self-use """Test stripping of leading and trailing slashes in default namespace of wbem connection when setting the attribute""" conn = WBEMConnection('http://localhost', None, default_namespace=None) with pytest.warns(DeprecationWarning): conn.default_namespace = '//root/blah//' assert conn.default_namespace == 'root/blah'
def test_conn_set_timeout(): """ Test setting the 'timeout' property of WBEMConnection. """ conn = WBEMConnection('http://localhost', timeout=20) assert conn.timeout == 20 conn.timeout = 25 assert conn.timeout == 25
def test_close(self): # pylint: disable=no-self-use """ Test closing a connection once. """ conn = WBEMConnection('http://localhost') assert conn.session is not None conn.close() assert conn.session is None
def test_stats_enabled(self): # pylint: disable=no-self-use """ Test the property stats_enabled setter """ conn = WBEMConnection('http://localhost') assert conn.stats_enabled is False conn.stats_enabled = True assert conn.stats_enabled is True conn.stats_enabled = False assert conn.stats_enabled is False
def test_close_method(self): # pylint: disable=no-self-use """ Test closing a connection and invoking a CIM method. """ conn = WBEMConnection('http://localhost') conn.close() assert conn.session is None with pytest.raises(ConnectionError) as exc_info: conn.InvokeMethod(ObjectName='CIM_Foo', MethodName='M1') exc = exc_info.value assert re.match(r'is closed', str(exc))
def test_close_imethod(self): # pylint: disable=no-self-use """ Test closing a connection and invoking an intrinsic operation. """ conn = WBEMConnection('http://localhost') conn.close() assert conn.session is None with pytest.raises(ConnectionError) as exc_info: conn.GetClass('CIM_Foo') exc = exc_info.value assert re.match(r'is closed', str(exc))
def setup_method(self): """Setup that is run before each test method.""" # pylint: disable=protected-access WBEMConnection._reset_logging_config() configure_loggers_from_string('all=file', TEST_OUTPUT_LOG, propagate=True, connection=True) # pylint: disable=attribute-defined-outside-init self.logger = logging.getLogger(LOGGER_API_CALLS_NAME) assert self.logger is not None
def test_close_export(self): # pylint: disable=no-self-use """ Test closing a connection and invoking an export operation. """ conn = WBEMConnection('http://localhost') conn.close() assert conn.session is None indi = CIMInstance("CIM_AlertIndication") with pytest.raises(ConnectionError) as exc_info: conn.ExportIndication(NewIndication=indi) exc = exc_info.value assert re.match(r'is closed', str(exc))
def connect(self, url, timeout=None): self.log('setup connection {0} timeout {1}'.format(url, timeout)) conn = WBEMConnection(url, (args['username'], args['password']), NAMESPACE, timeout=timeout, no_verification=True, ca_certs=None) # enable saving of xml for display conn.debug = args['debug'] self.log('Connected {0}'.format(url)) return conn
def test_missing(self): # pylint: disable=no-self-use """ Test both Enum context and EndOfSequence completely missing. Generates exception """ conn = WBEMConnection('http://localhost') result = [(u'IRETURNVALUE', {}, {})] with pytest.raises(ParseError): # pylint: disable=protected-access result = conn._get_rslt_params(result, 'namespace')
def test_namespace_slashes_init(self): # pylint: disable=no-self-use """Test stripping of leading and trailing slashes in default namespace of wbem connection when initializing""" conn = WBEMConnection('http://localhost', None, default_namespace='//root/blah//') assert conn.default_namespace == 'root/blah'
def connect_server(server_url, creds, namespace): """ Connect to the server return the connection object. This call should not generate any exceptions """ return WBEMConnection(server_url, creds, default_namespace=namespace, no_verification=True)
def test_context_manager(self): # pylint: disable=no-self-use """ Test the use of WBEMConnection as a context manager. """ with WBEMConnection('http://localhost:5988') as conn: assert isinstance(conn, WBEMConnection) assert conn.url == 'http://localhost:5988' assert conn.session is not None assert conn.session is None
def test_logger_propagate(self, tmp_dir, logger_names, propagate): # pylint: disable=redefined-outer-name """Test log event propagation behavior.""" short_name, logger_name = logger_names # The testing approach is to log to files and check their contents. # Neither LogCapture nor OutputCapture seemed to work with pytest. logger_filename = os.path.join(tmp_dir.path, 'pywbem.xxx.log') pkg_filename = os.path.join(tmp_dir.path, 'pywbem.log') # Create a log handler on the 'pywbem.<xxx>' logger to be tested configure_logger(short_name, log_dest='file', log_filename=logger_filename, detail_level='all', connection=True, propagate=propagate) # Create a log handler on the 'pywbem' logger (parent) pkg_logger = logging.getLogger('pywbem') pkg_handler = logging.FileHandler(pkg_filename, encoding="UTF-8") pkg_handler.setLevel(logging.DEBUG) pkg_formatter = logging.Formatter('%(asctime)s-%(name)s-%(message)s') pkg_handler.setFormatter(pkg_formatter) pkg_logger.addHandler(pkg_handler) # Create a log event WBEMConnection('bla') # Verify the 'propagate' attribute of the logger to be tested logger = logging.getLogger(logger_name) assert logger.propagate == propagate for h in logger.handlers + pkg_logger.handlers: try: h.flush() h.close() except AttributeError: pass pkg_logger.removeHandler(pkg_handler) with open(logger_filename) as logger_fp: logger_line = logger_fp.read() assert re.match(r'.*-%s\..*-Connection:' % logger_name, logger_line) with open(pkg_filename) as pkg_fp: pkg_line = pkg_fp.read() if propagate: assert re.match(r'.*-pywbem.*-Connection:', pkg_line) else: assert pkg_line == '' # Clean up the Python logging configuration configure_logger(short_name, connection=False)
def test_connection_defaults(self): # pylint: disable=no-self-use """ Test creation of a connection with default init parameters. """ conn = WBEMConnection('http://localhost') assert conn.url == 'http://localhost' assert conn.creds is None assert conn.x509 is None assert conn.use_pull_operations is False assert conn.stats_enabled is False
def main(prog): """ Parse command line arguments, connect to the WBEM server and open the interactive shell. """ args, url = parse_args(prog) creds = None if args.user is not None and args.password is None: args.password = _getpass.getpass('Enter password for %s: ' % args.user) if args.user is not None or args.password is not None: creds = (args.user, args.password) # if client cert and key provided, create dictionary for # wbem connection x509_dict = None if args.cert_file is not None: x509_dict = {"cert_file": args.cert_file} if args.key_file is not None: x509_dict.update({'key_file': args.key_file}) conn = WBEMConnection(url, creds, default_namespace=TEST_NAMESPACE, no_verification=True, x509=x509_dict, ca_certs=args.ca_certs, timeout=args.timeout, stats_enabled=True) if args.record is not None: yamlfp = TestClientRecorder.open_file(args.record, 'a') conn.add_operation_recorder(TestClientRecorder(yamlfp)) print('Test with response sizes=%s response_counts=%s, pull_sizes=%s\n' % (args.response_size, args.response_count, args.pull_size)) run_tests(conn, args.response_size, args.response_count, args.pull_size, args.verbose) return 0
def Connect(self, namespace='root/ibm', printing=False): from pywbem import WBEMConnection server_uri = f'https://{self.ip.rstrip()}' conn = WBEMConnection(server_uri, (self.login, self.password), namespace, no_verification=True) return conn
def explore_server(server_url, username, password): print("WBEM server URL:\n %s" % server_url) conn = WBEMConnection(server_url, (username, password)) server = WBEMServer(conn) print("Brand:\n %s" % server.brand) print("Version:\n %s" % server.version) print("Interop namespace:\n %s" % server.interop_ns) print("All namespaces:") for ns in server.namespaces: print(" %s" % ns) print("Advertised management profiles:") org_vm = ValueMapping.for_property(server, server.interop_ns, 'CIM_RegisteredProfile', 'RegisteredOrganization') indications_profile = None server_profile = None for inst in server.profiles: org = org_vm.tovalues(inst['RegisteredOrganization']) name = inst['RegisteredName'] vers = inst['RegisteredVersion'] print(" %s %s Profile %s" % (org, name, vers)) if org == "DMTF" and name == "Indications": indications_profile = inst if org == "SNIA" and name == "Server": server_profile = inst if indications_profile is not None: print("Central instances for DMTF Indications profile (component):") try: ci_paths = server.get_central_instances(indications_profile.path, "CIM_IndicationService", "CIM_System", ["CIM_HostedService"]) except Exception as exc: print("Error: %s" % str(exc)) ci_paths = [] for ip in ci_paths: print(" %s" % str(ip)) if server_profile is not None: print("Central instances for SNIA Server profile (autonomous):") try: ci_paths = server.get_central_instances(server_profile.path) except Exception as exc: print("Error: %s" % str(exc)) ci_paths = [] for ip in ci_paths: print(" %s" % str(ip))
def test_missing(self): """ Test both Enum context and EndOfSequence completely missing. Generates exception """ result = [(u'IRETURNVALUE', {}, {})] with pytest.raises(CIMError) as exec_info: # pylint: disable=protected-access result = WBEMConnection._get_rslt_params(result, 'namespace') exc = exec_info.value assert exc.status_code_name == 'CIM_ERR_INVALID_PARAMETER'
def main(): """ Get arguments and call the execution function """ # if less than required arguments, use the defaults if len(sys.argv) < 8: print("Usage: %s server_url username password namespace classname " "max_open, max_pull" % sys.argv[0]) server_url = SERVER_URL username = USERNAME password = PASSWORD namespace = TEST_NAMESPACE classname = TEST_CLASS max_open = 0 max_pull = 100 else: server_url = sys.argv[1] username = sys.argv[2] password = sys.argv[3] namespace = sys.argv[4] classname = sys.argv[5] max_open = sys.argv[6] max_pull = sys.argv[7] print('Parameters: server_url=%s\n username=%s\n namespace=%s\n' \ ' classname=%s\n max_open=%s,\n max_pull=%s' % \ (server_url, username, namespace, classname, max_open, max_pull)) # connect to the server conn = WBEMConnection(server_url, (username, password), default_namespace=namespace, no_verification=True) #Call method to execute the enumeration sequence and return instances try: instances = execute_request(conn, classname, max_open, max_pull) # print the resulting instances for instance in instances: print('\npath=%s\n%s' % (instance.path, instance.tomof())) # handle exceptions except CIMError as ce: print('Operation Failed: CIMError: code=%s, Description=%s' % \ (ce.status_code_name, ce.status_description)) sys.exit(1) except Error as err: print ("Operation failed: %s" % err) sys.exit(1) return 0
def test_attrs_deprecated_setters(self, attr_name, value): """ Test that the setting of certain attributes is deprecated. """ conn = WBEMConnection('http://localhost') with pytest.warns(DeprecationWarning) as rec_warnings: # The code to be tested setattr(conn, attr_name, value) assert len(rec_warnings) == 1 attr_value = getattr(conn, attr_name) assert attr_value == value
def test_with_params(self, irval, ec, eos, eos_exp, exc_exp): """ Test combminations of IRETURNVALUE, EOS and EnumerationContext for both good and fail responses. """ result = [(u'IRETURNVALUE', {}, irval), (u'EnumerationContext', None, ec), (u'EndOfSequence', None, eos)] if exc_exp: with pytest.raises(CIMError) as exec_info: # pylint: disable=protected-access result = WBEMConnection._get_rslt_params(result, 'root/blah') exc = exec_info.value assert exc.status_code_name == 'CIM_ERR_INVALID_PARAMETER' else: # pylint: disable=protected-access result = WBEMConnection._get_rslt_params(result, 'root/blah') # the _get_rslt_params method sets context to None if eos True ecs = None if eos_exp is True else (ec, 'root/blah') assert result == (irval, eos_exp, ecs)
def test_add_same_twice(self): # pylint: disable=no-self-use """ Test addition of same recorder twice""" conn = WBEMConnection('http://localhost') conn.add_operation_recorder(LogOperationRecorder()) # pylint: disable=protected-access assert len(conn._operation_recorders) == 1 with pytest.raises(ValueError): conn.add_operation_recorder(LogOperationRecorder())
def execute_request(server_url, creds, namespace, classname): """ Open a connection with the server_url and creds, and enumerate instances defined by the functions namespace and classname arguments. Displays either the error return or the mof for instances returned. """ print('Requesting url=%s, ns=%s, class=%s' % \ (server_url, namespace, classname)) try: # Create a connection CONN = WBEMConnection(server_url, creds, default_namespace=namespace, no_verification=True) #Issue the request to EnumerateInstances on the defined class INSTANCES = CONN.EnumerateInstances(classname) #Display of characteristics of the result object print('instances type=%s len=%s' % (type(INSTANCES), len(INSTANCES))) #display the mof output for inst in INSTANCES: print('path=%s\n' % inst.path) print(inst.tomof()) # handle any exception except Error as err: # If CIMError, display CIMError attributes if isinstance(err, CIMError): print('Operation Failed: CIMError: code=%s, Description=%s' % \ (err.status_code_name, err.status_description)) else: print ("Operation failed: %s" % err) sys.exit(1)
def test_no_recorder(self): # pylint: disable=no-self-use """Test creation of wbem connection with specific parameters""" creds = ('myname', 'mypw') x509 = {'cert_file': 'mycertfile.crt', 'key_file': 'mykeyfile.key'} conn = WBEMConnection('http://localhost', creds, default_namespace='root/blah', x509=x509, use_pull_operations=True, stats_enabled=True) assert conn.url == 'http://localhost' assert conn.creds == creds assert conn.default_namespace == 'root/blah' assert conn.x509 == x509 assert conn.stats_enabled is True assert conn.use_pull_operations is True
def test_attrs_readonly(self, attr_name, value): """ Test that certain attributes that were previously public are now read-only and that the original value has not changed when trying to modify them. """ conn = WBEMConnection('http://localhost') value1 = getattr(conn, attr_name) with pytest.raises(AttributeError): # The code to be tested setattr(conn, attr_name, value) value2 = getattr(conn, attr_name) assert value2 == value1
def test_add_operation_recorders(self): # pylint: disable=no-self-use """Test addition of multiple operation recorders""" conn = WBEMConnection('http://localhost') conn.add_operation_recorder(LogOperationRecorder('fake_conn_id')) tcr_fn = 'blah.yaml' tcr_file = MyTestClientRecorder.open_file(tcr_fn, 'a') conn.add_operation_recorder(MyTestClientRecorder(tcr_file)) # pylint: disable=protected-access assert len(conn._operation_recorders) == 2 tcr_file.close() os.remove(tcr_fn)