예제 #1
0
def before_scenario(context, scenario):

    testrun = RUNNER_CONFIG.get('TESTRUN') or 'testrun'
    context.log_starttime = strftime("%Y-%m-%dT%H:%M:%SZ", localtime())
    start_time = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
    hostname = PlatformHelper.get_hostname()
    ip = PlatformHelper.get_ip_address()

    product = RUNNER_CONFIG.get("PRODUCT")
    build = RUNNER_CONFIG.get('BUILD')
    context.senddb = RUNNER_CONFIG.get('DATABASE_ENABLED')
    context.env = RUNNER_CONFIG.get('ENVIRONMENT')

    logger_path = os.path.join(ConfigAdapter.get_log_path(), testrun)
    tc_prefix = ConfigAdapter.get_testlink_prefix(product)

    match = filter(lambda x: x.find(tc_prefix) >= 0, scenario.tags)

    if len(match)>0:
        # differentiate scenarios in scenario outline
        if hasattr(context, 'active_outline') and type(context.active_outline) == behave.model.Row:
            suffix = match.pop()
            for example_key in context.active_outline:
                suffix += ".%s" % (example_key)
            tc_id = testrun + "_" + suffix
        else:
            tc_id = testrun + "_" + match.pop()
    else:
        #no test link project id foud
        tc_id = hashlib.md5(testrun + "_" + scenario.name.encode()).hexdigest()

    if not FileHelper.dir_exist(logger_path):
        FileHelper.create_directory(logger_path)
    logger_filename = "%s.log" % (tc_id)
    logfile = os.path.join(logger_path, logger_filename)

    client_ip = PlatformHelper.get_ip_address()

    LogHelper.create_logger(logfile, fmt=client_ip+" %(asctime)s %(levelname)s " + product+" | %(message)s |")

    tc = TestCase(testrun=testrun, start_time=start_time, hostname=hostname, product=product,
                  ip=ip, summary=scenario.name, feature=scenario.filename, tags=scenario.tags, logfile=logfile, _id=tc_id, build=build)
    context.tc = tc

    LogHelper.info("test start: " + scenario.name)
    def download_fb(
        cls,
        product=None,
        dry_run=False,
    ):

        current_platform = PlatformHelper.get_system()
        fb_site = "https://artifacts.elastic.co/downloads/beats/filebeat/"
        package_name = ""

        if current_platform == "Linux" and PlatformHelper.get_arch(
        ) == "deb-64":
            package_name = 'filebeat-5.2.0-amd64.deb'

        if current_platform == "Linux" and PlatformHelper.get_arch(
        ) == "deb-32":
            package_name = 'filebeat-5.2.0-i386.deb'

        if current_platform == "Windows":
            package_name = 'filebeat-5.2.0-windows-x86_64.zip'

        if current_platform == "Darwin":
            package_name = 'filebeat-5.2.0-darwin-x86_64.tar.gz'

        installer_dir = ConfigAdapter.get_installer_path(product)

        cls.package_name = package_name
        installer_path = os.path.join(installer_dir, package_name)
        url = fb_site + package_name
        LogHelper.info("installer_path is " + installer_path)
        LogHelper.info("package url is " + url)

        if not FileHelper.dir_exist(installer_dir):
            FileHelper.create_directory(installer_dir)

        if FileHelper.file_exist(installer_path):
            FileHelper.delete_file(installer_path)

        if not dry_run:
            downloaded_package = urllib2.urlopen(url)
            LogHelper.info("download result is %s" % downloaded_package)
            with open(installer_path, 'wb') as output:
                output.write(downloaded_package.read())

        return installer_path
예제 #3
0
    def create_logger(cls,
                      path,
                      level="DEBUG",
                      fmt="%(asctime)s %(levelname)s %(message)s",
                      fmt_date='%Y-%m-%dT%H:%M:%S',
                      gmtime=True,
                      remove_newline=True):

        cls.remove_newline = remove_newline
        log_level = cls.__resolve_log_level(level)
        log_name = os.path.basename(path)
        cls.logger = logging.getLogger(log_name)
        cls.logger.setLevel(log_level)

        cls.logger.handlers = [
            h for h in cls.logger.handlers
            if not isinstance(h, logging.StreamHandler)
        ]
        cls.logger.removeHandler(cls.logger.handlers)

        # create a file handler

        if not FileHelper.dir_exist(FileHelper.get_dir(path)):
            FileHelper.create_directory(FileHelper.get_dir(path))

        handler = logging.FileHandler(path, mode='a', delay=False)

        handler.setLevel(log_level)

        # add the handlers to the logger
        cls.logger.addHandler(handler)

        cls.logger = logging.getLogger(log_name)

        cls.fmt_option["fmt"] = fmt
        cls.fmt_option['fmt_date'] = fmt_date
        cls.fmt_option['gmtime'] = gmtime
        cls.set_format(
            "%s %s" % (cls.fmt_option['fmt'], cls.__get_call_back()),
            cls.fmt_option['fmt_date'], cls.fmt_option['gmtime'])

        return cls.logger
예제 #4
0
def decrypt_tar(context, dest):
    source_root = ConfigAdapter.get_installer_path('LINUX')
    source_full_path = source_root
    #    for file in os.listdir(source_root):
    #	print(file)
    #        if re.match(r'.*\.tar$', file):
    #             source_full_path = os.path.join(source_root, file)
    tars = FileHelper.find_file(source_root, "*.tar")
    LogHelper.info(tars[-1])
    for file in tars:
        LogHelper.info(file)
        source_full_path = os.path.join(source_root, file)

#    source_full_path = os.path.join(source_root,source)
    LogHelper.info("Decrypt src: {source}".format(source=source_full_path))
    dest_root = ConfigAdapter.get_output_path('LINUX')
    dest_full_path = os.path.join(dest_root, dest)
    FileHelper.create_directory(dest_full_path, True)
    output = LinuxGUIClient.decrypt_cmd.decrypt(source_full_path,
                                                dest_full_path)
    LogHelper.info("Decrypt output {output}".format(output=output))
def step_impl(context, number):
    LogHelper.info("start to judge whether to create files")
    testdata_config = ConfigAdapter.get_testdata_pros()
    testdata_root = ConfigAdapter.get_testdata_path()
    testdata_dir = testdata_root
    file_size = 0
    for row in context.table:
        if "file_folder" in row.headings:
            testdata_dir = os.path.join(testdata_root, row.get('file_folder'))
        elif "file_dir" in row.headings:
            testdata_dir = os.path.join(testdata_root, row.get('file_dir'))

    if not FileHelper.dir_exist(testdata_dir):
        FileHelper.create_directory(testdata_dir)

    if not FileHelper.get_file_count_in_dir(testdata_dir) == int(number):
        FileHelper.delete_file(testdata_dir)
        for row in context.table:
            for i in range(0, int(number)):
                file_prefix = row.get("file_prefix") or testdata_config.get(
                    "FILE_PREFIX") or "td"
                file_txt = row.get("file_ext") or testdata_config.get(
                    "FILE_EXT") or "txt"
                name = row.get('file_name') or testdata_config.get(
                    "FILE_NAME") or None
                if name:
                    file_name = "%s_%s_%s.%s" % (file_prefix, name, i,
                                                 file_txt)
                else:
                    file_name = "%s_%s.%s" % (file_prefix, i, file_txt)
                file_size = row.get("file_size") or testdata_config.get(
                    "FILE_SIZE") or 0

                DataHelper.create_testfile(file_name, testdata_dir,
                                           int(file_size))

        context.file_size = file_size

    else:
        for row in context.table:
            length = row.get('length') or testdata_config.get(
                "FILE_SIZE") or 10
            length = int(length)
            size = row.get('file_size') or testdata_config.get("FILE_SIZE")
            pattern = row.get('content') or 'random'

            testdatas = FileHelper.find_file(testdata_dir, '*')
            patch_method = row.get('patch_method')
            if patch_method == "append":
                for testdata in testdatas:
                    LogHelper.info("Patch test files with %s %s %d %s" %
                                   (patch_method, testdata, length, pattern))
                    FileHelper.append_file_content(testdata, length, pattern)
            elif patch_method == "truncate":
                for testdata in testdatas:
                    LogHelper.info("Patch test files with %s %s %d %s" %
                                   (patch_method, testdata, length, pattern))
                    FileHelper.truncate_file(testdata, length)
            elif patch_method == "insert":
                for testdata in testdatas:
                    LogHelper.info("Patch test files with %s %s %d %s" %
                                   (patch_method, testdata, length, pattern))
                    size_offset = random.randrange(1, size)
                    FileHelper.insert_file_content(testdata, size_offset,
                                                   length, pattern)
    def run_mzd_restore(cls, dest, personal_key=None, index=-1):
        """
        select mzd reuqest to restore files
        :param dest:  restore file destination, dertermine to root config and dest
        :param personal_key: personal key, if not None, input personal key during restore process
        :param index: mzd list
        :return: Boolean. if restore complete, true. otherwise false
        """

        output_path = ConfigAdapter.get_output_path()
        output_path = os.path.join(output_path, dest)
        if FileHelper.dir_exist(output_path):
            FileHelper.delete_directory(output_path)
        FileHelper.create_directory(output_path)
        cmd = MacFryR_Controller.prefix_for_sudo() + 'sudo -S chmod -R 777 "{path}"'.format(path=output_path)
        CmdHelper.run(cmd)

        LogHelper.info('Select %s to generate mzd request' % output_path)

        try:
            LogHelper.info("Multiple restore jobs found, automation will select the latest job to do the restore.")
            MacFryrElement({'AXRole': 'AXRow'}, index, 10).left_click()
            MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click()
        except:
            LogHelper.info("Only one restore job found, automation will do restore with the default job.")

        MacFryrElement({'AXRole': 'AXRadioButton', 'AXDescription': 'selectNewLocationRadio'}, wait_time=5).click()
        time.sleep(2)
        root = MacUIUtils.get_root_volume_name()
        pop_menu = MacFryrElement({'AXRole': 'AXPopUpButton'}, 0, 10).element

        app = pop_menu.getApplication()

        MacUIUtils.click_popmenu_item_by_value(pop_menu, root)
        browser_window = MacUIUtils.wait_element(app, AXRole='AXWindow', AXTitle='Open')
        browser_handle = MacUIUtils.wait_element(browser_window, AXRole='AXBrowser')
        MacUIUtils.select_nodes(browser_handle, output_path, node_matcher='AXTextField')
        # MacFryrElement({'AXTitle': 'New Folder'}).click()
        # MacFryrElement({'AXIdentifier': '_NS:43'}, 0, 5).send_keys(dest)
        # MacFryrElement({'AXIdentifier': '_NS:53'}).click()
        btn_open = MacUIUtils.wait_element(browser_window, AXRole='AXButton', AXTitle='Open')
        MacUIUtils.click_button(btn_open)
        MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click()

        if personal_key:
            LogHelper.info('input personal key %s' % personal_key)
            el = MacUIUtils.wait_element(app, timeout=120, AXRole='AXTextField', AXDescription='privateKeyField')
            MacUIUtils.input_text(el, personal_key)
            LogHelper.info('click next button')
            btn_next = MacFryrElement({'AXRole': 'AXButton', 'AXTitle': 'Next'})
            btn_next.click()

        MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click()
        time.sleep(3)

        from apps.mac.mac_gui_installer.mac_gui_installer import AppUIElement
        try:
            textbox_psd = AppUIElement.from_bundle('com.apple.SecurityAgent',
                                               {'AXRole': 'AXTextField', 'AXSubrole': 'AXSecureTextField'}, 0, 10)
        except ValueError:
            LogHelper.info("Security Agent is not found")
            textbox_psd = None

        if textbox_psd and textbox_psd.element:
            password = MAC_CONFIG.get("LOCAL_ADMIN_PASSWORD")
            textbox_psd.send_keys(password)
            time.sleep(1)
            btn_ok = AppUIElement.from_bundle('com.apple.SecurityAgent', {'AXRole': 'AXButton', 'AXTitle': 'OK'})
            btn_ok.left_click()
            time.sleep(1)

        cls.wait_restore_finished()
예제 #7
0
 def testCreateDir(self):
     testdir = "%s/subdir1/subdir2" %TestFileHelper.testdatadir
     FileHelper.create_directory(testdir)
     self.assertTrue(testdir)