def end_and_reboot(self):
     self.end_flow()
     reboot_command()
Exemple #2
0
def start(case_name=case_names[0], **kwargs):
    global user, rdp_server
    wait_time = 30
    time_path = common_function.get_current_dir("time_temp.txt")
    log.info("Start Wait {}".format(wait_time))
    if os.path.exists(time_path):
        with open(time_path, "r") as f:
            now_time = f.read()
    else:
        with open(time_path, "w") as f:
            now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            f.write(now_time)
    current_time = time.time()
    before_time = time.mktime(time.strptime(now_time, "%Y-%m-%d %H:%M:%S"))
    if current_time - before_time > 3600:
        os.remove(time_path)
        common_function.reboot_command()
    common_function.SwitchThinProMode("user")
    query_list = ["xen", 'freerdp', "view", "firefox"]
    shadow_dict = {}
    for i in query_list:
        d = vdi_connection.query_item_id(i)
        shadow_dict.update(d)
    vdi_connection.hide_desktop_icon(id_dict=shadow_dict)
    common_function.cache_collection(3)
    case_name = case_name.lower()
    result_file = os.path.join(common_function.get_current_dir(),
                               r'Test_Report',
                               '{}.yaml'.format(common_function.check_ip_yaml()))
    user_manager = vdi_connection.MultiUserManger()
    performance = Performance.get_system_obj()
    test_data = os.path.join(common_function.get_current_dir(), 'Test_Data')
    # --------------- pre define --------------------------
    log.info('Begin to start test {}'.format(case_name))
    common_function.new_cases_result(result_file, case_name)
    pic_name = generate_pic_name(case_name)
    local_pic_name = generate_local_name(case_name)
    parameters = display_function.analyze_name(case_name)
    parameters = display_function.check_resolution_support(parameters)
    log.info('analyze parameter from case name')
    # display_function.LinuxTools().generate_profile(parameters['layout'], parameters['monitors'])
    display_function.set_display_profile(parameters)
    log.info('generate xml file')
    log.info('set local resolution, Wait 20s for background refresh')
    display_function.LinuxTools().set_local_resolution()
    log.debug("check local resolution set success")
    if not set_resolution_success() and common_function.need_reboot() != -1:
        common_function.change_reboot_status(-1)
        common_function.reboot_command()
    common_function.change_reboot_status(0)
    display_function.set_background()
    log.info('set local background success')
    flag, first_collect_flag = local_start(case_name, result_file, test_data, local_pic_name)
    if not flag:
        return False
    # check fresh rate-----------------------------------------------
    check_fresh_rate(case_name, result_file, parameters)
    # check fresh rate end-------------------------------------------
    user = user_manager.get_a_available_key()
    log.info('get valid user : {}'.format(user))
    remote_collect_flag = False
    try:
        flag, remote_collect_flag = remote_start(case_name, result_file, test_data, pic_name, user_manager, parameters, performance)
    except:
        debug_path = common_function.get_current_dir("Test_Report/debug.log")
        with open(debug_path, "a") as f:
            traceback.print_exc(file=f)
        traceback.print_exc()
        steps = {
            'step_name': 'case exception',
            'result': 'Fail',
            'expect': '',  # can be string or pic path
            'actual': 'img/{}.jpg'.format(case_name),
            'note': traceback.format_exc()}
        common_function.update_cases_result(result_file, case_name, steps)
    finally:
        log.info('try to reset user')
        if user:
            user_manager.reset_key(user)
        if parameters['vdi'].upper() == 'RDP' and rdp_server:
            user_manager.reset_key(rdp_server, key=session.lower())
        if first_collect_flag or remote_collect_flag:
            steps = {
                'step_name': "Cannot find template PIC",
                'result': 'Fail',
                'expect': '',  # can be string or pic path
                'actual': '',
                'note': 'This case has no pic in library'}
            common_function.update_cases_result(result_file, case_name, steps)
        log.debug(gc.garbage)
        gc.collect()
 def reboot(self):
     reboot_command()
Exemple #4
0
def main():
    # show_desktop()
    if os.path.exists(get_current_dir('flag.txt')):
        with open(get_current_dir('flag.txt')) as f:
            test_flag = f.read()
            if 'TEST FINISHED' in test_flag.upper():
                return
    if not os.path.exists('time.txt'):
        with open('time.txt', 'w') as f:
            f.write(time.ctime())
    prepare_for_framework()
    additional_path = get_current_dir('Test_Data', 'additional.yml')
    file_obj = YamlOperator(additional_path)
    content = file_obj.read()
    site = content.get('AutoDash_Site')
    if not site:
        load_data_from_ftp()
        script_name = os.path.basename(__file__).split('.')[0]
        add_linux_script_startup([script_name])
        check_water_mark()
    path = get_current_dir('reboot.txt')
    if not os.path.exists(path):
        with open(path, 'w+') as f:
            f.write("0")
        time.sleep(5)
        if os.path.exists(path):
            SwitchThinProMode("admin")
            os.popen('reboot')
            time.sleep(30)
    if not os.path.exists(get_current_dir('Test_Report')):
        os.mkdir(get_current_dir('Test_Report'))
    test_data_path = os.path.join(get_current_dir(), 'Test_Data')
    with open(get_current_dir('flag.txt'), 'w') as f:
        f.write('testing')
    if not os.path.exists(os.path.join(test_data_path, 'script.yml')):
        log.info('script.yml not exist, please check if no cases planned')
        with open(get_current_dir('flag.txt'), 'w') as f:
            f.write('test finished')
        return
    with open(os.path.join(test_data_path, 'script.yml'), 'r') as f:
        scripts = yaml.safe_load(f)
    with open(os.path.join(test_data_path, 'additional.yml'), 'r') as f:
        additional = yaml.safe_load(f)
    for script in scripts:
        script_name, script_status = list(script.items())[0]
        if script_status.upper() == 'NORUN':
            log.info('Begin to Test case {}'.format(script_name))
            try:
                if need_reboot() == 1:
                    change_reboot_status(0)
                    reboot_command()
                memory_check(limit=MEMORY_LIMIT)
                globals()[script_name.split('__')[0]].start(
                    case_name=script_name.split('__')[1], kwargs=additional)
                script[script_name] = 'Finished'
                with open(os.path.join(test_data_path, 'script.yml'),
                          'w') as f:
                    yaml.safe_dump(scripts, f)
            except MemoryNotSufficient as e:
                log.debug(e)
                log.debug("start reboot")
                reboot_command()
            except:
                with open(get_current_dir('Test_Report', 'debug.log'),
                          'a') as f:
                    f.write(traceback.format_exc())
                capture_screen(
                    get_current_dir(
                        'Test_Report',
                        'img',
                        '{}.jpg'.format(script_name.split('__')[1]),
                    ))
                script[script_name] = 'Finished'
                with open(os.path.join(test_data_path, 'script.yml'),
                          'w') as f:
                    yaml.safe_dump(scripts, f)
                steps = {
                    'step_name': 'case exception',
                    'result': 'Fail',
                    'expect': '',  # can be string or pic path
                    'actual': 'img/{}.jpg'.format(script_name.split('__')[1]),
                    'note': traceback.format_exc()
                }
                base_name = get_report_base_name()
                report_file = get_current_dir('Test_Report', base_name)
                # result_file = get_current_dir(r'Test_Report', '{}.yaml'.format(check_ip_yaml()))
                update_cases_result(report_file,
                                    script_name.split('__')[1], steps)
        else:
            log.info('Test case {} status is Finished, Skip test'.format(
                script_name))
    if os.path.exists(path):
        if need_reboot() == 0:
            change_reboot_status(9)
            log.info("Start Reboot before Report")
            reboot_command()
        else:
            os.remove(path)
    if site:
        share_folder = content.get('share_folder')
        host = share_folder.split('/')[0]
        folder_path = '/'.join(share_folder.split('/')[1:])
        user = content.get('user')
        password = content.get('password')
        flag_path = '/{}/{}.txt'.format(folder_path, site)
        log.info('end_flag: {}'.format(flag_path))

        with open(get_current_dir('{}.txt'.format(site)), 'w') as f:
            f.write('test finished')
        ftp = FTPUtils(host, user, password)
        ftp.ftp.cwd('ThinPro_Automation_Site')
        local_folder = get_current_dir('Test_Report')
        ftp_folder = r'/{}/Test_Report'.format(folder_path)

        num = 0
        while True:
            try:

                ftp = FTPUtils(host, user, password)
                log.info('upload Test_Report folder to ftp')
                log.info(local_folder)
                log.info(ftp_folder)
                ftp.new_dir(ftp_folder)
                local_report = get_current_dir('Test_Report',
                                               '{}.yaml'.format(site))
                ftp_report = '/{}/Test_Report/{}.yaml'.format(
                    folder_path, site)
                ftp.upload_file(local_report, ftp_report)
                ftp.upload_file(get_current_dir(r"{}.txt".format(site)),
                                flag_path)
                break
            except:
                if num > 30:
                    traceback.print_exc()
                    break
                else:
                    num += 5
                    time.sleep(5)
    else:
        with open(get_current_dir('flag.txt'), 'w') as f:
            f.write('test finished')
        with open('time.txt') as f:
            start = f.read()
        end = time.ctime()
        report = email_tool.GenerateReport(start, end)
        report.generate()
        file = email_tool.zip_dir()
        log.info('zipped file name: {}'.format(file_obj))
        additional_email = additional.get('email') if additional.get(
            'email') else ''
        email_tool.send_mail(
            recipient=['*****@*****.**', additional_email],
            subject='Automation Report Linux {}'.format(
                zip_file_name(get_report_number(), get_report_value())),
            attachment=file)
        os.remove(file)
        os.remove('time.txt')
        try:
            collect_report()
        except Exception as e:
            print(e)
            log.error(e)