def _execute_cmd(self): """ Run the executable, and log its detailed execution. """ try: test_params = dict([(str(key), str(val)) for _, key, val in self.params.iteritems()]) # pylint: disable=W1620 input_encoding = self._config.get('core.input_encoding') result = process.run(self._command, verbose=True, env=test_params, encoding=input_encoding) self._log_detailed_cmd_info(result) except process.CmdError as details: self._log_detailed_cmd_info(details.result) test_failure = self._cmd_error_to_test_failure(details) raise exceptions.TestFail(test_failure) warn_regex = self._config.get('simpletests.status.warn_regex') warn_location = self._config.get('simpletests.status.warn_location') skip_regex = self._config.get('simpletests.status.skip_regex') skip_location = self._config.get('simpletests.status.skip_location') # Keeping compatibility with 'avocado_warn' libexec for regex in [warn_regex, r'^\d\d:\d\d:\d\d WARN \|']: warn_msg = ("Test passed but there were warnings on %s during " "execution. Check the log for details.") if regex is not None: re_warn = re.compile(regex, re.MULTILINE) if warn_location in ['all', 'stdout']: if re_warn.search(result.stdout_text): raise exceptions.TestWarn(warn_msg % 'stdout') if warn_location in ['all', 'stderr']: if re_warn.search(result.stderr_text): raise exceptions.TestWarn(warn_msg % 'stderr') if skip_regex is not None: re_skip = re.compile(skip_regex, re.MULTILINE) skip_msg = ("Test passed but %s indicates test was skipped. " "Check the log for details.") if skip_location in ['all', 'stdout']: if re_skip.search(result.stdout_text): raise exceptions.TestSkipError(skip_msg % 'stdout') if skip_location in ['all', 'stderr']: if re_skip.search(result.stderr_text): raise exceptions.TestSkipError(skip_msg % 'stderr')
def test_create(self): """ Execute the test of creating a Server """ # if there is not enough resource to create server, skip it if not (self.body.get('servername') and self.body.get('publicip') and self.body.get('clusterip') and self.body.get('username') and self.body.get('password')): raise exceptions.TestSkipError("There is not enough resource" " to create server!") if not self.body.get('parent_bucket'): group_id, parent_id = \ test_utils.get_available_group_bucket(self.params) self.body.update({'parent_bucket': parent_id}) resp_body = self.client.create(**self.body) body = resp_body.body if not resp_body and utils.verify_response(self.body, resp_body): raise exceptions.TestFail("Create server failed: %s" % self.body) status = test_utils.wait_for_server_in_status( 'servername', self.body['servername'], self.client, 'added', 1, int(self.params.get('add_host_timeout', 600))) if not status: raise exceptions.TestFail("Failed to add server %s" % self.body['servername']) LOG.info('Create server %s successfully!' % body['properties'].get('name')) self.env['server_name'] = body['properties'].get('name') self._query_servers()
def runTest(self): env_lang = os.environ.get('LANG') os.environ['LANG'] = 'C' try: self._runTest() except exceptions.TestNotFoundError, details: raise exceptions.TestSkipError(details)
def wrapper(obj, *args, **kwargs): # pylint: disable=W0613 if negate: if callable(condition): if not condition(obj): raise core_exceptions.TestSkipError(message) else: if not condition: raise core_exceptions.TestSkipError(message) else: if callable(condition): if condition(obj): raise core_exceptions.TestSkipError(message) else: if condition: raise core_exceptions.TestSkipError(message) return function(obj, *args, **kwargs)
def setup_or_cleanup_gluster(is_setup, vol_name, brick_path="", pool_name="", file_path="/etc/glusterfs/glusterd.vol", **kwargs): """ Set up or clean up glusterfs environment on localhost or remote :param is_setup: Boolean value, true for setup, false for cleanup :param vol_name: gluster created volume name :param brick_path: Dir for create glusterfs :param kwargs: Other parameters that need to set for gluster :return: ip_addr or nothing """ try: utils_path.find_command("gluster") except utils_path.CmdNotFoundError: raise exceptions.TestSkipError("Missing command 'gluster'") if not brick_path: tmpdir = data_dir.get_tmp_dir() brick_path = os.path.join(tmpdir, pool_name) # Check gluster server apply or not ip_addr = kwargs.get("gluster_server_ip", "") session = None if ip_addr != "": remote_user = kwargs.get("gluster_server_user") remote_pwd = kwargs.get("gluster_server_pwd") remote_identity_file = kwargs.get("gluster_identity_file") session = remote.remote_login("ssh", ip_addr, "22", remote_user, remote_pwd, "#", identity_file=remote_identity_file) if is_setup: if ip_addr == "": ip_addr = utils_net.get_host_ip_address() add_rpc_insecure(file_path) glusterd_start() logging.debug("finish start gluster") logging.debug("The contents of %s: \n%s", file_path, open(file_path).read()) gluster_vol_create(vol_name, ip_addr, brick_path, True, session) gluster_allow_insecure(vol_name, session) gluster_nfs_disable(vol_name, session) logging.debug("finish vol create in gluster") if session: session.close() return ip_addr else: gluster_vol_stop(vol_name, True, session) gluster_vol_delete(vol_name, session) gluster_brick_delete(brick_path, session) if session: session.close() return ""
def test(self): if self.fault_type in "hard_fault" and not self.ipmi_ip: raise exceptions.TestSkipError( "This case need compute node support" " ipmi and must set ipmitool, " "please check!") host_list = self.compute_utils.get_all_hypervisors() if len(host_list) < 2: raise exceptions.TestFail('No enough compute node for test!') extra_spec = {"hw:auto_recovery": "enabled"} self.flavor = self.compute_utils.create_flavor(extra_spec=extra_spec) host_for_ping = host_list[0] host_for_panic = host_list[1] host_name_for_ping = host_for_ping.hypervisor_hostname host_name_for_panic = host_for_panic.hypervisor_hostname # compute node ip of vm for panic self.host_ip_for_panic = host_for_panic.host_ip self.vm_for_ping, self.ip_for_ping = \ self.create_vm_and_bind_ip(host_name_for_ping) self.vm_for_panic, self.ip_for_panic = \ self.create_vm_and_bind_ip(host_name_for_panic) self.__run_multi_thread() test_utils.check_ping_msg(vm=self.vm_for_panic, msg=self.ping_msg, ping_count=self.ping_recovery_time)
def __init__(self, disk): try: import guestfs except ImportError: install_cmd = "yum -y install python-libguestfs" try: process.run(install_cmd) import guestfs except Exception: raise exceptions.TestSkipError('We need python-libguestfs (or ' 'the equivalent for your ' 'distro) for this particular ' 'feature (modifying guest ' 'files with libguestfs)') self.g = guestfs.GuestFS() self.disk = disk self.g.add_drive(disk) libvirtd = SpecificServiceManager("libvirtd") libvirtd_status = libvirtd.status() if libvirtd_status is None: raise exceptions.TestError('libvirtd: service not found') if (not libvirtd_status) and (not libvirtd.start()): raise exceptions.TestError('libvirtd: failed to start') logging.debug("Launch the disk %s, wait..." % self.disk) self.g.launch()
def setUp(self): """ Avocado-vt uses custom setUp/test/tearDown handling and unlike Avocado it allows skipping tests from any phase. To convince Avocado to allow skips let's say our tests run during setUp phase and report the status in test. """ env_lang = os.environ.get('LANG') os.environ['LANG'] = 'C' try: self._runTest() self.__status = "PASS" # This trick will give better reporting of virt tests being executed # into avocado (skips, warns and errors will display correctly) except exceptions.TestSkipError: raise # This one has to be raised in setUp except: # nopep8 Old-style exceptions are not inherited from Exception() details = sys.exc_info()[1] self.__status = details if not hasattr(self, "cancel"): # Old Avocado, skip here if isinstance(self.__status, error.TestNAError): raise exceptions.TestSkipError(self.__status) finally: if env_lang: os.environ['LANG'] = env_lang else: del os.environ['LANG']
def setup_nfs_disk(disk_name, disk_type, disk_format="raw"): """ Setup nfs disk. """ mount_src = os.path.join(test.tmpdir, "nfs-export") if not os.path.exists(mount_src): os.mkdir(mount_src) mount_dir = os.path.join(test.tmpdir, "nfs-mount") if disk_type in ["file", "floppy", "iso"]: disk_path = "%s/%s" % (mount_src, disk_name) device_source = libvirt.create_local_disk(disk_type, disk_path, "2", disk_format=disk_format) #Format the disk. if disk_type in ["file", "floppy"]: cmd = ("mkfs.ext3 -F %s && setsebool virt_use_nfs true" % device_source) if process.system(cmd, ignore_status=True, shell=True): raise exceptions.TestSkipError("Format disk failed") nfs_params = {"nfs_mount_dir": mount_dir, "nfs_mount_options": "ro", "nfs_mount_src": mount_src, "setup_local_nfs": "yes", "export_options": "rw,no_root_squash"} nfs_obj = nfs.Nfs(nfs_params) nfs_obj.setup() if not nfs_obj.mount(): return None disk = {"disk_dev": nfs_obj, "format": "nfs", "source": "%s/%s" % (mount_dir, os.path.split(device_source)[-1])} return disk
def test_set_ec_pool_cache(self): """ Set up cache for EC pool """ pool_id = self.env.get('pool_tmp_id') vgroup_id = self.env.get('vgroup_id', 1) cache_pool = test_utils.create_pool(self.params, flag=True, vgroup_id=vgroup_id) self.env['cache_pool_id'] = cache_pool.get('pool_id') self.env['cache_pool_name'] = cache_pool.get('name') if self.params.get('NO_EC', "true") == "true": raise exceptions.TestSkipError("There is not EC pool") else: set_cache = { 'cache_pool_id': cache_pool.get('pool_id'), 'cache_pool_name': cache_pool.get('name'), 'cache_size': 107374182400, 'target_dirty_radio': 30, 'target_full_radio': 70, 'option': 'set_cache', 'caching_mode': 'writeback', } resp = self.client.set_cache(pool_id, **set_cache) LOG.info('Rest Response: %s' % resp) if not resp and utils.verify_response(self.body, resp): raise exceptions.TestFail("Set up EC pool cache failed: %s" % self.body)
def run(test, params, env): """ Test for virt-top, it is a top like tool for virtual machine. """ # Install virt-top package if missing. software_mgr = software_manager.SoftwareManager() if not software_mgr.check_installed('virt-top'): logging.info('Installing virt-top package:') software_mgr.install('virt-top') # Get the full path of virt-top command. try: VIRT_TOP = path.find_command("virt-top") except path.CmdNotFoundError as info: raise exceptions.TestSkipError("No virt-top command found - %s" % info) vm_name = params.get("main_vm", "avocado-vt-vm1") output = params.get("output_file", "output") output_path = os.path.join(data_dir.get_tmp_dir(), output) status_error = ("yes" == params.get("status_error", "no")) options = params.get("options", "") id_result = virsh.domid(vm_name) if id_result.exit_status: raise exceptions.TestError("Get domid failed.") domid = id_result.stdout.strip() if "--stream" in options: cmd = "%s %s 1>%s" % (VIRT_TOP, options, output_path) else: cmd = "%s %s" % (VIRT_TOP, options) # Add a timeout command to end it automatically. cmd = "timeout 10 %s" % cmd cmd_result = process.run(cmd, ignore_status=True, shell=True) if not status_error: # Read and analyse the output of virt-top. success = False with open(output_path) as output_file: lines = output_file.readlines() for line in lines: if line.count(vm_name): sub_string = line.split() if domid == sub_string[0].strip(): success = True break else: continue else: continue if not success: raise exceptions.TestFail("Command virt-top exit successfully, but" "domid is expected") else: if cmd_result.exit_status != 2: raise exceptions.TestFail("Command virt-top exit successfully with" "invalid option:%s" % cmd_result.stdout_text)
def _run_test(self): """ Auxiliary method to run setup and test method. """ self._tag_start() testMethod = getattr(self, self._testMethodName) skip_test_condition = getattr(testMethod, '__skip_test_condition__', False) skip_test_condition_negate = getattr(testMethod, '__skip_test_condition_negate__', False) if skip_test_condition: if callable(skip_test_condition): if skip_test_condition_negate: self.__skip_test = not bool(skip_test_condition(self)) else: self.__skip_test = bool(skip_test_condition(self)) else: if skip_test_condition_negate: self.__skip_test = not bool(skip_test_condition) else: self.__skip_test = bool(skip_test_condition) else: self.__skip_test = bool(skip_test_condition) try: if self.__skip_test is False: self.__phase = 'SETUP' self.setUp() except exceptions.TestSkipError as details: self.__skip_test = True stacktrace.log_exc_info(sys.exc_info(), logger=LOG_JOB) raise exceptions.TestSkipError(details) except exceptions.TestCancel: stacktrace.log_exc_info(sys.exc_info(), logger=LOG_JOB) raise except: # Old-style exceptions are not inherited from Exception() stacktrace.log_exc_info(sys.exc_info(), logger=LOG_JOB) details = sys.exc_info()[1] raise exceptions.TestSetupFail(details) else: try: self.__phase = 'TEST' if inspect.iscoroutinefunction(testMethod): loop = asyncio.get_event_loop() loop.run_until_complete(testMethod()) else: testMethod() except exceptions.TestCancel: stacktrace.log_exc_info(sys.exc_info(), logger=LOG_JOB) raise except: # Old-style exceptions are not inherited from Exception() pylint: disable=W0702 stacktrace.log_exc_info(sys.exc_info(), logger=LOG_JOB) details = sys.exc_info()[1] if not isinstance(details, Exception): # Avoid passing nasty exc details = exceptions.TestError(f"{details!r}: {details}") self.log.debug("Local variables:") local_vars = inspect.trace()[1][0].f_locals for key, value in local_vars.items(): self.log.debug(' -> %s %s: %s', key, type(value), value) raise details self.__status = 'PASS'
def get_primary_disk_fs_type(self): """ Get primary disk filesystem type """ result = lgf.virt_filesystems(self.oldvm.name, long_format=True) if result.exit_status: raise exceptions.TestSkipError("Cannot get primary disk" " filesystem information!") fs_info = result.stdout.strip().splitlines() if len(fs_info) <= 1: raise exceptions.TestSkipError("No disk filesystem information!") try: primary_disk_info = fs_info[1] fs_type = primary_disk_info.split()[2] return fs_type except (KeyError, ValueError) as detail: raise exceptions.TestFail(str(detail))
def run(test, params, env): """ Test command: virsh find-storage-pool-sources 1. Prepare env to provide source storage if use localhost: 1). For 'netfs' source type, setup nfs server 2). For 'iscsi' source type, setup iscsi server 3). For 'logical' type pool, setup iscsi storage to create vg 4). Prepare srcSpec xml file if not given 2. Find the pool sources by running virsh cmd """ source_type = params.get("source_type", "") source_host = params.get("source_host", "127.0.0.1") srcSpec = params.get("source_Spec", "") vg_name = params.get("vg_name", "virttest_vg_0") ro_flag = "yes" == params.get("readonly_mode", "no") status_error = "yes" == params.get("status_error", "no") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': raise exceptions.TestSkipError("API acl test not supported in " "current libvirt version.") if not source_type: raise exceptions.TestFail("Command requires <type> value") cleanup_nfs = False cleanup_iscsi = False cleanup_logical = False # Prepare source storage if source_host == "127.0.0.1": if source_type == "netfs": # Set up nfs res = utils_test.libvirt.setup_or_cleanup_nfs(True) selinux_bak = res["selinux_status_bak"] cleanup_nfs = True if source_type in ["iscsi", "logical"]: # Set up iscsi iscsi_device = utils_test.libvirt.setup_or_cleanup_iscsi(True) # If we got nothing, force failure if not iscsi_device: raise exceptions.TestFail("Did not setup an iscsi device") cleanup_iscsi = True if source_type == "logical": # Create vg by using iscsi device try: lv_utils.vg_create(vg_name, iscsi_device) except Exception, detail: utils_test.libvirt.setup_or_cleanup_iscsi(False) raise exceptions.TestFail("vg_create failed: %s" % detail) cleanup_logical = True
def result(self): if self.expected_test_fail and "install" in self.expected_test_dict[ "shortname"]: raise exceptions.TestFail("God wanted this test to fail") elif self.expected_test_fail and self.current_test_dict.get( "abort_on_error", "no") == "yes": raise exceptions.TestSkipError("God wanted this test to abort") else: return not self.expected_test_fail
def runTest(self): env_lang = os.environ.get('LANG') os.environ['LANG'] = 'C' try: self._runTest() # This trick will give better reporting of cloud tests being executed # into avocado (skips, warns and errors will display correctly) except exceptions.TestNotFoundError, details: raise exceptions.TestSkipError(details)
def unset_state(run_params, env): """ Remove a state with previous changes. :param run_params: configuration parameters :type run_params: {str, str} :param env: test environment :type env: Env object :raises: :py:class:`exceptions.TestSkipError` if missing snapshot in passive mode (abort) :raises: :py:class:`exceptions.TestError` if invalid policy was used """ for vm_name in run_params.objects("vms"): vm = env.get_vm(vm_name) vm_params = run_params.object_params(vm_name) if not vm_params.get("unset_state"): # if the snapshot is not defined skip (leaf tests that are no setup) continue vm_params["unset_type"] = vm_params.get("unset_type", "any") vm_params["unset_mode"] = vm_params.get("unset_mode", "fi") vm_params["vms"] = vm_name vm_params["check_type"] = vm_params["unset_type"] vm_params["check_state"] = vm_params["unset_state"] vm_params["check_opts"] = "print_pos=no print_neg=yes" state_exists = check_state(vm_params, env) # if too many or no matches default to most performant type vm_params["unset_type"] = vm_params["found_type_%s" % vm_name] # NOTE: no custom handling needed here action_if_exists = vm_params["unset_mode"][0] action_if_doesnt_exist = vm_params["unset_mode"][1] if not state_exists and "a" == action_if_doesnt_exist: logging.info( "Aborting because of missing snapshot for final cleanup") raise exceptions.TestSkipError( "Snapshot '%s' of %s doesn't exist. Aborting " "due to passive mode." % (vm_params["unset_state"], vm_name)) elif not state_exists and "i" == action_if_doesnt_exist: logging.warning( "Ignoring missing snapshot for final cleanup (will not be removed)" ) elif not state_exists: raise exceptions.TestError( "Invalid policy %s: The unset action on missing state can be " "either of 'abort', 'ignore'." % vm_params["unset_mode"]) elif state_exists and "r" == action_if_exists: logging.info("Preserving state '%s' of %s for later test runs", vm_params["unset_state"], vm_name) elif state_exists and "f" == action_if_exists: enforce_unset(vm_params, vm) elif state_exists: raise exceptions.TestError( "Invalid policy %s: The unset action on present state can be " "either of 'reuse', 'force'." % vm_params["unset_mode"])
def run(test, params, env): """ Main test run. :param test: test object :type test: :py:class:`avocado_vt.test.VirtTest` :param params: extended dictionary of parameters :type params: :py:class:`virttest.utils_params.Params` :param env: environment object :type env: :py:class:`virttest.utils_env.Env` """ logging.info("Running GUI tutorial test.") # Get the VM Network object for this test vmnet = env.get_vmnet() vmnet.start_all_sessions() vms = vmnet.get_vms() server_vm = vms.server client_vm = vms.client vmnet.ping_all() logging.info("Starting a minimal GUI test on two vms (screens)") if not BOT_AVAILABLE: raise exceptions.TestSkipError("No virtual user backend found") image_root = get_image_root(params["suite_path"]) set_logging(params.get("vu_logging_level", 20), test.logdir) set_shared_configuration(params.get("smooth_mouse_motion", "no") == "yes") server_screen = initiate_vm_screen(server_vm, 'vncdotool') client_screen = initiate_vm_screen(client_vm, 'vncdotool') # click on a button on the server if available bot = GuiBot(dc=server_screen) bot.add_path(image_root) if bot.exists('centos-kickstart-finish'): bot.click('centos-kickstart-finish') else: bot.type_text('Anyone there?') # click on a button on the client if available if params["set_state_vm2"] == "guisetup.clicked": bot.dc_backend = client_screen if bot.exists('win10-start-button'): bot.click('win10-start-button') else: bot.type_text('Anyone here?') elif params["set_state_vm2"] == "guisetup.noop": logging.info("The virtual user will do nothing on the client screen") else: raise exceptions.TestError( "Invalid option for Windows client GUI setup " "operation %s" % params["set_state_vm2"]) logging.info("Running done.") logging.info("\nFor more details check https://guibot.org")
def check_migration_result(migration_res): """ Check the migration result. :param migration_res: the CmdResult of migration :raise: exceptions.TestSkipError when some known messages found """ logging.debug("Migration result:\n%s" % migration_res) if migration_res.stderr.find("error: unsupported configuration:") >= 0: raise exceptions.TestSkipError(migration_res.stderr)
def test_delete(self): """ Test that deletion of specified server """ server_id = self.env.get('tmp_server_id') if not server_id: raise exceptions.TestSkipError("There is not enough server " "can be deleted!") self.client.delete_server(server_id) del self.env['tmp_server_id']
def grub_serial_terminal(**kwargs): """ Edit the serial and terminal lines of grub.conf """ session = kwargs['session'] vm = kwargs['vm'] grub_file = vm.get_grub_file(session) if 'grub2' in grub_file: raise exceptions.TestSkipError('Skip this case on grub2') cmd = "sed -i '1iserial -unit=0 -speed=115200\\n" cmd += "terminal -timeout=10 serial console' %s" % grub_file session.cmd(cmd)
def test_led(self): body_query = self.client.query_phydisks(self.cluster_id, self.server_id) if len(body_query) > 0: i = random.randint(0, len(body_query) - 1) if body_query[i].get('location_led') == -1: raise exceptions.TestSkipError('This case not supported on vm') self.body['controllerID'] = body_query[i].get('controllerID') self.body['enclosureID'] = body_query[i].get('enclosureID') self.body['slotID'] = body_query[i].get('slotID') self.body['location_led'] = self.params.get('location_led') else: raise exceptions.TestFail("No phydisks found") self.client.led(self.cluster_id, self.server_id, **self.body)
def _run_avocado(self): testMethod = getattr(self, self._testMethodName) self._start_logging() self.sysinfo_logger.start_test_hook() test_exception = None cleanup_exception = None stdout_check_exception = None stderr_check_exception = None try: self.setUp() except exceptions.TestSkipError, details: stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test') raise exceptions.TestSkipError(details)
def _execute_cmd(self): try: test_params = { str(key): str(val) for _, key, val in self.params.iteritems() # pylint: disable=W1620 } input_encoding = self._config.get('core.input_encoding') result = process.run(self._command, verbose=True, env=test_params, encoding=input_encoding) self._log_detailed_cmd_info(result) except process.CmdError as details: self._log_detailed_cmd_info(details.result) raise exceptions.TestFail(details) if result.exit_status != 0: self.fail('TAP Test execution returned a ' 'non-0 exit code (%s)' % result) parser = tapparser.TapParser(io.StringIO(result.stdout_text)) fail = 0 count = 0 bad_errormsg = 'there were test failures' for event in parser.parse(): if isinstance(event, tapparser.TapParser.Error): self.error('TAP parsing error: ' + event.message) continue if isinstance(event, tapparser.TapParser.Bailout): self.error(event.message) continue if isinstance(event, tapparser.TapParser.Test): bad = event.result in (tapparser.TestResult.XPASS, tapparser.TestResult.FAIL) if event.result != tapparser.TestResult.SKIP: count += 1 if bad: self.log.error('%s %s %s', event.result.name, event.number, event.name) fail += 1 if event.result == tapparser.TestResult.XPASS: bad_errormsg = 'there were test failures or unexpected passes' else: self.log.info('%s %s %s', event.result.name, event.number, event.name) if not count: raise exceptions.TestSkipError('no tests were run') if fail: self.fail(bad_errormsg)
def prepare_disk(path, disk_format): """ Prepare the disk for a given disk format. """ disk = {} # Check if we test with a non-existed disk. if os.path.split(path)[-1].startswith("notexist."): disk.update({"format": disk_format, "source": path}) elif disk_format == "scsi": scsi_option = params.get("virt_disk_device_scsi_option", "") disk_source = libvirt.create_scsi_disk(scsi_option) if disk_source: disk.update({"format": "scsi", "source": disk_source}) else: raise exceptions.TestSkipError("Get scsi disk failed") elif disk_format in ["iso", "floppy"]: disk_path = libvirt.create_local_disk(disk_format, path) disk.update({"format": disk_format, "source": disk_path}) elif disk_format == "nfs": nfs_disk_type = params.get("nfs_disk_type", None) disk.update(setup_nfs_disk(os.path.split(path)[-1], nfs_disk_type)) elif disk_format == "iscsi": # Create iscsi device if needed. image_size = params.get("image_size", "2G") device_source = libvirt.setup_or_cleanup_iscsi( is_setup=True, is_login=True, image_size=image_size) logging.debug("iscsi dev name: %s", device_source) # Format the disk and make file system. libvirt.mk_label(device_source) libvirt.mk_part(device_source) # Run partprobe to make the change take effect. process.run("partprobe", ignore_status=True, shell=True) libvirt.mkfs("%s1" % device_source, "ext3") device_source += "1" disk.update({"format": disk_format, "source": device_source}) elif disk_format in ["raw", "qcow2"]: disk_size = params.get("virt_disk_device_size", "1") device_source = libvirt.create_local_disk( "file", path, disk_size, disk_format=disk_format) disk.update({"format": disk_format, "source": device_source}) return disk
def setUp(self): """ Avocado-vt uses custom setUp/test/tearDown handling and unlike Avocado it allows skipping tests from any phase. To convince Avocado to allow skips let's say our tests run during setUp phase and don't do anything during runTest/tearDown. """ env_lang = os.environ.get('LANG') os.environ['LANG'] = 'C' try: self._runTest() # This trick will give better reporting of virt tests being executed # into avocado (skips, warns and errors will display correctly) except error.TestNAError, details: raise exceptions.TestSkipError(details)
def runTest(self): env_lang = os.environ.get('LANG') os.environ['LANG'] = 'C' params = self.params if params.get("dependency_failed") == 'yes': raise exceptions.TestNotFoundError("Test dependency failed") try: if params.get("security_type") == "bandit": self._banditTest() else: self._syntribosTest() # This trick will give better reporting of cloud tests being executed # into avocado (skips, warns and errors will display correctly) except exceptions.TestNotFoundError, details: raise exceptions.TestSkipError(details)
def run(test, params, env): """ Test for virt-top, it is a top like tool for virtual machine. """ # Install virt-top package if missing. software_mgr = software_manager.SoftwareManager() if not software_mgr.check_installed('virt-top'): logging.info('Installing virt-top package:') software_mgr.install('virt-top') # Get the full path of virt-top command. try: VIRT_TOP = path.find_command("virt-top") except path.CmdNotFoundError, info: raise exceptions.TestSkipError("No virt-top command found - %s" % info)
def setup(self): self.vm_1_name = 'cloudtest_' + utils_misc.generate_random_string(6) self.vm_2_name = 'cloudtest_' + utils_misc.generate_random_string(6) LOG.info("Try to get two compute nodes") hyors = self.compute_utils.novaclient.hypervisors.list() if len(hyors) < 2: raise exceptions.TestSetupFail( "Failed to get enough compute nodes") hyors_index = self.get_randomindex(len(hyors), 2) LOG.info("Try to get compute node ip.") computenode_ip = self.get_computenode_ip( hyors[hyors_index[0]]._info["service"]["host"]) LOG.info("Got compute node ip :%s" % computenode_ip) self.session_computenode = self.get_session_computenode(computenode_ip, usekey=True) LOG.info("To check if it supports nic bonding") self.nicbonding = self.get_nic_bonding(self.session_computenode) if self.nicbonding is None: raise exceptions.TestSkipError("Did not find bonding nic, " "skip the test") else: LOG.info("Got a bonding nic %s" % self.nicbonding) self.vm1 = self.create_vm_with_az( self.vm_1_name, hyors[hyors_index[0]]._info["service"]["host"]) self.register_cleanup(self.vm1) self.vm2 = self.create_vm_with_az( self.vm_2_name, hyors[hyors_index[1]]._info["service"]["host"]) self.register_cleanup(self.vm2) self.compute_utils.assign_floating_ip_to_vm(self.vm1) self.compute_utils.assign_floating_ip_to_vm(self.vm2) self.ipaddr_1 = self.compute_utils.get_vm_ipaddr(self.vm_1_name) self.ipaddr_2 = self.compute_utils.get_vm_ipaddr(self.vm_2_name) time.sleep(10) self.session_vm = test_utils.get_host_session( self.params, 'instance', self.ipaddr_1["floating"]) checkpath = "/etc/sysconfig/network-scripts" self.nics = self.get_eths_forbonded(self.session_computenode, checkpath, self.nicbonding) if len(self.nics) == 0: raise exceptions.TestSetupFail("Failed to get bonded nic") LOG.info("%s bonded to be %s" % (self.nics, self.nicbonding))
def __init__(self, disk): try: import guestfs except ImportError: install_cmd = "yum -y install python-libguestfs" try: process.run(install_cmd) import guestfs except Exception: raise exceptions.TestSkipError('We need python-libguestfs (or ' 'the equivalent for your ' 'distro) for this particular ' 'feature (modifying guest ' 'files with libguestfs)') self.g = guestfs.GuestFS() self.disk = disk self.g.add_drive(disk) logging.debug("Launch the disk %s, wait..." % self.disk) self.g.launch()