Ejemplo n.º 1
0
    def run(self, context):
        """
        Runs the test step

        :type context: TestStepContext
        :param context: test case context
        """
        TestStepBase.run(self, context)

        self._http_downloader_obj = HttpDownloaderUtil(
            url=self._pars.url,
            destination=self._pars.destination,
            proxy=self._pars.http_proxy,
            creds=self._pars.credential,
            http_timeout=self._pars.http_timeout,
            override=self._pars.override_file,
            download_timeout=self._pars.transfer_timeout,
            logger=self._logger)
        try:
            response = self._http_downloader_obj.init()
        except AcsConfigException:
            raise

        if not response:
            error_msg = "Cannot get response from server"
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   error_msg)

        verdict, output, _ = self._http_downloader_obj.download(response)
        if verdict != Global.SUCCESS:
            raise AcsToolException(AcsToolException.OPERATION_FAILED, output)
        else:
            self.ts_verdict_msg = output
Ejemplo n.º 2
0
    def _run(self):
        """
        Run stop acquisition
        """
        if self._patlib is None:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Cannot do acquisition, PatLib has not been initialized")
        acquisition_status = self._context.get_info("AcquisitionStatus")

        if self._pars.action.lower() == "start":
            # check acquisition status
            if acquisition_status and acquisition_status != "Stopped":
                raise AcsToolException(
                    AcsToolException.PROHIBITIVE_BEHAVIOR,
                    "Cannot start acquisition, wrong acquisition status : %s" %
                    acquisition_status)
                # acquisition status is correct, start it!
            self._patlib.start_acquisition(True)
            # store in context a variable about acquisition status
            self._context.set_info("AcquisitionStatus", "Started")
        elif self._pars.action.lower() == "stop":
            # check acquisition status
            if not acquisition_status:
                raise AcsToolException(
                    AcsToolException.PROHIBITIVE_BEHAVIOR,
                    "Cannot stop, no acquisition previously started!")
            elif acquisition_status.lower() != "started":
                raise AcsToolException(
                    AcsToolException.PROHIBITIVE_BEHAVIOR,
                    "Cannot stop acquisition, wrong initial acquisition status : %s"
                    % acquisition_status)
            # acquisition status is correct, stop it!
            self._patlib.stop_acquisition()
            self._context.set_info("AcquisitionStatus", "Stopped")
Ejemplo n.º 3
0
    def _run(self):
        """
        Compute power verdict according to targets
        """
        if self._patlib is None:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Cannot report acquisition, PatLib has not been initialized")

        pnp_results = self._context.get_info(self._pars.stored_pnp_result)
        if not pnp_results:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Context key '{0}' does not content initialized PnpResult object"
                .format(self._pars.stored_pnp_result))

        pnp_results.update({"verdict_rail": str(self._patlib_util.power_rail)})
        # initialize store data to false
        self._context.set_info(self._pars.store_raw_data, "False")

        verdict_name = "POWER_MEASURE({0})"
        # retrieve measure information
        measures = pnp_results.retrieve_power_measures(
            self._patlib_util.power_rail)
        if not measures:
            raise AcsToolException(AcsToolException.PROHIBITIVE_BEHAVIOR,
                                   "Cannot retrieve measure information")

        measure = None
        verdict_msg = ""

        for rail in measures:
            output_measure = ""
            for value_type, value in measures[rail][-1].items():
                if value_type == "average":
                    measure = value
                output_measure += "{0}={1};".format(value_type, value)
            self.update_report(Global.SUCCESS, verdict_name.format(rail),
                               output_measure)
            if verdict_msg:
                verdict_msg += " | "
            verdict_msg += verdict_name.format(rail) + ":" + output_measure

        if verdict_msg:
            pnp_results.update({"power_msg": verdict_msg})

        if measure is None:
            raise AcsToolException(AcsToolException.PROHIBITIVE_BEHAVIOR,
                                   "Cannot retrieve average power measure")

        if pnp_results.check_rail_verdict(measure) == Global.FAILURE:
            self._context.set_info(self._pars.store_raw_data, "True")
Ejemplo n.º 4
0
    def _run(self):
        """
        Compute power verdict according to targets
        """
        if self._patlib is None:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Cannot report acquisition, PatLib has not been initialized")

        pnp_results = self._context.get_info(self._pars.stored_pnp_result)
        if not pnp_results:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Context key '{0}' does not content initialized PnpResult object"
                .format(self._pars.stored_pnp_result))

        pnp_results.update({"verdict_rail": str(self._patlib_util.power_rail)})

        verdict_name = "{0}#".format(self._pars.operation)
        verdict_name += "POWER_MEASURE({0})"
        # retrieve measure information
        measures = pnp_results.retrieve_power_measures(
            self._patlib_util.power_rail)
        if not measures:
            raise AcsToolException(AcsToolException.PROHIBITIVE_BEHAVIOR,
                                   "Cannot retrieve measure information")

        rail_to_report = self._patlib_util.power_rail
        # compute the score
        measure = self._compute_score(measures, rail_to_report)

        code = pnp_results.check_rail_verdict(float(measure))

        self.update_report(code, verdict_name.format(rail_to_report), measure)

        if code == Global.FAILURE:
            verdict_value = "FAIL"
        else:
            verdict_value = "PASS"

        pnp_results.update({"power_verdict": verdict_value})

        if not self._pars.verdict_criteria or "both" in str(
                self._pars.verdict_criteria).lower():
            if "fail" not in pnp_results.get_value("verdict").lower():
                pnp_results.update({"verdict": verdict_value})
        elif "power" in str(self._pars.verdict_criteria).lower():
            pnp_results.update({"verdict": verdict_value})
Ejemplo n.º 5
0
    def start_auto_logger_on_reboot(self,
                                    polling_delay,
                                    logger_type="sequenced"):
        """
        Internal method that start an autolog sequenced function to poll every x seconds
        only after next reboot

        :type  polling_delay: int
        :param polling_delay: delay in seconds between 2 logs.

        :type  logger_type: str
        :param logger_type: logger type to start, support only 'sequenced'.
        """
        if logger_type == "sequenced":
            function = "startSequenceLoggerOnReboot"
        else:
            txt = "not supported logger type" % logger_type
            self._logger.error(txt)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, txt)

        params = "--ei pollingDelay %s" % (polling_delay)
        self._internal_exec_v2(self.__autolog_module,
                               function,
                               params,
                               is_system=True)
Ejemplo n.º 6
0
    def __get_mms_box(self):
        """
        Returns the message box number of the message described by the thread
        id and message id passed as parameters.

        :rtype: str
        :return: the name of the box the message is in.

        :raise AcsToolException: If the output is missing one of the expected
            keys.
        """
        # Defining keys for input and output of the embedded UE command.
        thread_id_key = "thread_id"
        message_id_key = "msg_id"
        message_box_key = "msg_box_number"
        # Defined the function name used on the embedded side.
        function = "getMmsBoxFromId"
        # Building the command to send to the embedded part.

        # Launch the command and retreive the result.
        output = self._internal_exec_v2(self._mms_module,
                                        function,
                                        "--es %s %s --es %s %s" %
                                        (thread_id_key, self.sent_thread_id,
                                         message_id_key, self.sent_msg_id),
                                        is_system=True)

        # Check the output contains the expected keys.
        if message_box_key not in output:
            raise AcsToolException(
                AcsToolException.INVALID_PARAMETER,
                "output key %s not found: %s" % (message_box_key, output))
            # Return the output.
        return output.get(message_box_key)
Ejemplo n.º 7
0
    def _execute_at_command(self, at_command):
        """
        Executes the given at_command.

        :type at_command: str
        :param at_command: the AT command to execute

        :rtype: tuple
        :return: the verdict and the message in a tuple
        """
        # Check parameter
        if not at_command:
            return (Global.FAILURE, "Invalid input parameter")
        self._logger.debug("Sending AT command: %s " % str(at_command))
        # Escape quotes in AT command
        at_command = at_command.replace('\"', '\\"')
        # Build the adb command
        adb_command = "adb -s %s shell %s %s %s \"%s\"" % (
            self._device.get_serial_number(),
            "teltbox",
            "mdm_acm",
            "/dev/gsmtty20",
            at_command)
        # Execute the AT command
        (status, output) = internal_shell_exec(adb_command, 5)  # pylint: disable=W0212
        # Check the command output
        if "-ERROR-" in output:
            message = "Error during AT command execution: %s" % output
            raise AcsToolException(
                AcsToolException.OPERATION_FAILED,
                message)
        #Sleep arbitrary time
        time.sleep(1)
        # Return a status and a message
        return (status, output)
Ejemplo n.º 8
0
    def is_hdmi_connected(self):
        """
        Check whether HDMI is connected or not by reading dumpsys SurfaceFlinger
        :rtype: boolean
        :return: return True if HDMI exists.
        """

        cmd = 'adb shell "dumpsys SurfaceFlinger | grep External"'
        (return_code, output) = self._device.run_cmd(cmd, timeout=10)

        if return_code != Utils.Global.SUCCESS:
            msg = "uecmd is_hdmi_connected: Error '%s' when trying to check HDMI" % (
                output)
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        re_match = re.match(".*External \((.*)\)", output)
        if re_match and len(re_match.groups()) == 1:
            out_msg = re_match.group(1)
        else:
            return False

        if out_msg == "connected":
            return True
        else:
            return False
Ejemplo n.º 9
0
    def _initialize_new_monkey_instance(self):
        """
        Returns a new C{MonkeyUtilities} instance.

        This method will allow test optimization (with
        usage of mock implementation).

        :rtype: MonkeyUtilities
        :return: a new C{MonkeyUtilities} instance.
        """
        if self.__monkey_port is None:
            raise AcsConfigException(AcsConfigException.PROHIBITIVE_BEHAVIOR,
                                     "Monkey port cannot be <None>")
        if not isinstance(self.__monkey_port, int):
            self.__monkey_port = int(self.__monkey_port)

        oom_protection = self.__device.get_config("enableMonkeyOomProtection",
                                                  True, "str_to_bool")

        monkey_util = MonkeyUtilities(host="localhost",
                                      port=self.__monkey_port,
                                      device=self.get_device(),
                                      protect_from_oom=oom_protection)

        result, status = monkey_util.connect()
        if result == Global.FAILURE:
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   "Cannot start monkey util: %s" % status)
        return monkey_util
Ejemplo n.º 10
0
 def check_rpc_server_running(self):
     """
     Check that a XML RPC server instance is listening for XML
     RPC requests, if not, starts one.
     """
     ping_status = self.ping()
     if not ping_status:
         if self._is_port_used(self._server_port):
             raise AcsToolException(
                 AcsToolException.INVALID_PARAMETER,
                 "%s already in use, select another port" %
                 self._server_port)
         self.get_logger().debug("Starting XML-RPC server on port %s" %
                                 str(self._server_port))
         # Does not work
         # d = multiprocessing.Process(name='EquipementServerXMLRPC', target=start_server, args=(self._server_ip, self._server_port,))
         # d.daemon = True
         # d.start()
         # So, use an uggly way to run the server process
         log_folder = os.path.join(Folders.ACS_CACHE)
         cmd = "python LockManagerServer.py %s %s %s" % (
             self._server_ip, self._server_port, log_folder)
         DEVNULL = open(os.devnull, 'wb')
         subprocess.Popen(format_cmd_args(cmd),
                          shell=False,
                          stdout=DEVNULL,
                          stderr=subprocess.STDOUT,
                          cwd=os.path.abspath(os.path.dirname(__file__)),
                          close_fds=ON_POSIX)
         # Wait some time in order to give a chance
         # to the server to complete its starting procedure
         time.sleep(3)
Ejemplo n.º 11
0
    def _extract_results(self, tag_op_code, message):
        """
        This method is used to extract the result formatted by the ACS Agent
        into a readable dict.

        :type tag_op_code: str
        :param tag_op_code: The Operation Code reference

        :type message: str
        :param message: The input message to extract the I{ACS} results

        :rtype: dict
        :return: The dict builded from input message
        """

        result = AcsDict()

        payload = self._parse_reg.findall(message)
        if payload:
            for pair in re.split(Base.FIELDS_SEPARATOR, payload[0]):
                split_result = pair.split(Base.PARAM_SEPARATOR)
                if len(split_result) >= 2:
                    key = split_result[0].strip()
                    value = split_result[1].strip()
                    result[key] = value

        if not result:
            error_message = "(%s) " % (str(tag_op_code), )
            error_message += "Cannot parse incoming result:" + message
            raise AcsToolException(AcsToolException.PHONE_OUTPUT_ERROR,
                                   error_message)

        return result
Ejemplo n.º 12
0
    def get_bt_tethering_power(self):
        """
        Get Bluetooth Tethering feature state (Enable/disable).

        :rtype: boolean
        :return: True = enable
                 False = disable
        """
        self._logger.info("Get BT Tethering state")

        method = "getBluetoothTethering"

        pan_state = (self._internal_exec_v2(self._BLUETOOTH_MODULE, method, is_system=True)).get("Pan_state")
        if pan_state is None:
            return_msg = "pan_state parameter not found"
            self._logger.error(return_msg)
            raise AcsToolException(AcsToolException.INVALID_PARAMETER, return_msg)

        self._logger.info("BT tethering state: " + pan_state)
        # pylint: disable=E1101
        if pan_state == "ON":
            pan_state = True
        elif pan_state == "OFF":
            pan_state = False
        else:
            return_msg = "Invalid BT tethering state: " + pan_state
            self._logger.error(return_msg)
            raise DeviceException(DeviceException.INVALID_DEVICE_STATE, return_msg)

        return pan_state
Ejemplo n.º 13
0
    def __sign_app(self, app_path, signing_key_folder, signing_key_name):
        """
        Sign the given application with the given Signing key.

        :param app_path: The application path to be signed
        :type app_path: str

        :param signing_key_folder: The folder where are stored Signing keys.
        :type signing_key_folder: str

        :param signing_key_name: The key name to look up into passed folder.
        :type signing_key_name: str

        :raise AcsToolException: Raised when an error occurs while signing the Application.

        :return: The path of the signed application.
        :rtype: str

        """
        signing_tmp_folder = tempfile.mkdtemp()

        signed_app = path.join(signing_tmp_folder, path.basename(app_path))
        status, status_msg = self._app_api.sign_device_app(
            app_path, signing_key_folder, signing_key_name, signed_app, 5)
        if status != Global.SUCCESS:
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   status_msg)
        else:
            return signed_app
Ejemplo n.º 14
0
    def set_file_owner(self, file_name, owner, owner_group=None):
        """
        Set the file owner and groupe.

        :type file_name: str
        :param file_name: name of the file (the absolute pat of the file)
        :type owner: str
        :param owner: the owner to set
        :type owner_group: str
        :param owner_group: the owner group

        :rtype: tuple (str,str)
        :return: (owner, owner_group), these value can be equal to None if failed to be found
        """
        if owner_group is None:
            cmd = "adb shell chown %s %s" % (owner, file_name)
        else:
            cmd = "adb shell chown %s:%s %s" % (owner, owner_group, file_name)
        # Sending the command.
        output = self._exec(cmd, force_execution=True).strip()

        if not self.is_shell_output_ok(output):
            msg = "error when try to change file owner :" + output
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)
Ejemplo n.º 15
0
    def _build_list_from_dict(self, input_dict, input_string):
        """
        Returns a list built from the given dict and given str key.
        The input str's expected format shall be a python-like
        list description.

        :type input_dict: dictionary list
        :param input_dict: the dictionnary list to parse

        :type input_string: str
        :param input_string: the str key to extract

        :raise AcsToolException: if the provided parameter is not valid
        :rtype: list
        :return: a list of str built from the provided dict and str parameter
        """
        try:
            output_list = []
            for input_dict_elt in input_dict:
                if input_string in input_dict_elt:
                    output_list.append(input_dict_elt[input_string])

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            raise AcsToolException(
                AcsToolException.INVALID_PARAMETER,
                "Invalid input dict retrieved: %s" % (str(input_dict)))

        return output_list
Ejemplo n.º 16
0
 def _extract_cts_results_summary(self, cts_result_file_path):
     """
     Extract summary report data from CTS XML report:
     <Summary failed="0" notExecuted="0" timeout="0" pass="******" />
     :return:
     """
     verdict = Global.SUCCESS
     msg = ""
     try:
         tree = et.parse(cts_result_file_path)
         self._logger.debug("CTS - Parsing of the CTS report XML file completed")
     except et.XMLSyntaxError:
         error_msg = "CTS report file: " + str(cts_result_file_path) + \
                     "- parsing-reading issue (exception= " + str(Utils.format_exception_info()) + ")"
         raise AcsToolException(AcsToolException.XML_PARSING_ERROR, error_msg)
     summary = tree.find('Summary')
     if summary is not None:
         failed_t = int(summary.get("failed"))
         not_executed_t = int(summary.get("notExecuted"))
         timeout_t = int(summary.get("timeout"))
         passed_t = int(summary.get("pass"))
         msg = "CTS results Summary: failed=%s notExecuted=%s timeout=%s pass=%s"\
               %(failed_t, not_executed_t, timeout_t, passed_t)
         if (failed_t + not_executed_t + timeout_t) > 0:
             verdict = Global.FAILURE
     else:
         verdict = Global.FAILURE
         msg = "Summary section was not found in CTS result XML file: %s" %cts_result_file_path
     return verdict, msg
Ejemplo n.º 17
0
    def unzip(self, file_name):
        """
        Unzip a file on the DUT.
        :type file_name: str
        :param file_name: name of the file (the absolute path of the file on DUT)

        :rtype: str
        :return: return path+name of unzipped file if successful.  Throws AcsToolException.OPERATION_FAILED if there's an error.
        """

        # Find out size of the file to use as a basis for calculating a timeout for the unzip command.  ls -l should put that in column 4.
        cmd = "adb shell stat -c %%s %s " % file_name
        (return_code, output) = self._device.run_cmd(cmd, timeout=10)
        if return_code != Utils.Global.SUCCESS:
            msg = "uecmd unzip: Error '%s' when trying to list the file '%s'" % (
                output, file_name)
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        # Trusting that 'ls -l' provided file size in column 4.  If this does not have a number, then 'int' will throw an exception.
        file_size = int(output)
        timeout = int(file_size / 4096)
        if timeout < 100000:
            # Set a 100s minimum unzip timeout for small files
            timeout = 100000

        simple_filename = os.path.basename(file_name)
        device_path = os.path.dirname(file_name)
        cmd = "adb shell cd " + device_path + "; gunzip -f " + simple_filename

        if simple_filename[-4:].lower() == ".tgz":
            unzipped_name = file_name[:-4] + ".tar"
        elif simple_filename[-3:].lower() == ".gz":
            unzipped_name = file_name[:-3]
        else:
            msg = "uecmd unzip: unsupported filename extension in '%s'.  Expected a .gz or .tgz file." % simple_filename
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        (return_code, output_msg) = self._device.run_cmd(cmd, timeout=timeout)
        if return_code != Utils.Global.SUCCESS:
            msg = "uecmd unzip: Error '%s' when running '%s'" % (output_msg,
                                                                 cmd)
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        return unzipped_name
Ejemplo n.º 18
0
 def __build_list_from_zip(self, flash_file):
     # Check
     if self.__check_zip_file_integrity(flash_file):
         return self.__unzip_file_get_list(flash_file)
     else:
         err_msg = "FTE2: Unable to treat %s zip flash file" % str(
             self._flash_file)
         raise AcsToolException(AcsToolException.CRITICAL_FAILURE, err_msg)
Ejemplo n.º 19
0
    def run(self, context):
        """
        Runs the test step

        :type context: TestStepContext
        :param context: test case context
        """

        TestStepBase.run(self, context)

        self._logger.info(
            "Saves input value (%s) into context using variable name (%s)...",
            self._pars.input_1, self._pars.ctx_data_1)
        context.set_info(self._pars.ctx_data_1, self._pars.input_1)

        self._logger.info(
            "Saves input values (%s and %s) into context bundle using variable name (%s)...",
            self._pars.input_1, self._pars.input_2, self._pars.ctx_data_2)
        context.set_nested_info([self._pars.ctx_data_2, "INPUT_1"],
                                self._pars.input_1)
        context.set_nested_info([self._pars.ctx_data_2, "INPUT_2"],
                                self._pars.input_2)

        self._logger.info("Generates return code (%s), with comment (%s)...",
                          self._pars.return_code, self._pars.comment)
        self.ts_verdict_msg = self._pars.comment

        if self._pars.return_code == "SUCCESS":
            pass
        elif self._pars.return_code == "FAILURE":
            raise DeviceException(DeviceException.OPERATION_FAILED,
                                  self._pars.comment)
        elif self._pars.return_code == "BLOCKED":
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   self._pars.comment)
        elif self._pars.return_code == "ACS_EXCEPTION":
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   self._pars.comment)
        elif self._pars.return_code == "DEVICE_EXCEPTION":
            raise DeviceException(DeviceException.OPERATION_FAILED,
                                  self._pars.comment)
        elif self._pars.return_code == "UNKNOWN_EXCEPTION":
            raise ValueError(self._pars.comment)
        else:
            raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                   self._pars.comment)
Ejemplo n.º 20
0
 def _extract_cts_results_for_bulk_tcr_upload(self, cts_result_file_path):
     """
     This function will extract CTS results from default XML into acceptable
     TCR for bulk results upload
     :return:
      payload - results structure to be uploaded into TCR as bulk update
     """
     verdict = Global.SUCCESS
     msg = ""
     payload = []
     rt = {}
     try:
         tree = et.parse(cts_result_file_path)
         self._logger.debug("CTS - Parsing of the CTS report XML file completed")
     except et.XMLSyntaxError:
         error_msg = "CTS report file: " + str(cts_result_file_path) + \
                     "- parsing-reading issue (exception= " + str(Utils.format_exception_info()) + ")"
         raise AcsToolException(AcsToolException.XML_PARSING_ERROR, error_msg)
     package_list = tree.getroot().xpath("//TestPackage")
     for package in package_list:
         self._logger.debug("CTS - Packages results processing")
         package_name = package.get('appPackageName')
         if package_name is not None:
             rt['useCase'] = package_name
         test_case = ""
         element = package.find("TestSuite")
         while element is not None:
             test_case += '.' + element.get('name')
             element = element.find("TestSuite")
         tcs = package.xpath(".//TestCase")
         for tc_node in tcs:
             tc_name = tc_node.get('name')
             if tc_name is not None:
                 tests = tc_node.xpath(".//Test")
                 for test_node in tests:
                     test_name = test_node.get('name')
                     if test_name is not None:
                         test_name = '.' + tc_name + '.' + test_name
                         result = test_node.get('result')
                         if result == "pass":
                             result = Verdict.PASS
                         elif result == "fail":
                             result = Verdict.FAIL
                         elif result == "timeout":
                             result = Verdict.INTERRUPTED
                         elif result == "notExecuted":
                             result = "NA"
                         rt['verdict'] = result
                         rt['testCase'] = package_name + test_case + test_name
                         payload.append(copy.deepcopy(rt))
     nr_elem = len(payload)
     if nr_elem == 0:
         msg = "Calculated CTS bulk upload payload is empty. Was this an empty CTS test plan execution?"
         verdict = Global.FAILURE
     else:
         msg = "calculated CTS bulk upload payload contains %s elements"% nr_elem
         LiveReporting.instance().create_bulk_tc(payload)
     return verdict, msg
Ejemplo n.º 21
0
    def run(self, context):
        """
        Create a random file

        :type context: TestStepContext
        :param context: test case context
        """
        TestStepBase.run(self, context)

        destination_path = self._pars.destination_path  # Destination path
        if destination_path == '[TEMP]':
            destination_path = tempfile.mkdtemp()
        if self._pars.rand_file_size_min is not None:
            if self._pars.rand_file_size_min >= self._pars.rand_file_size:
                self._logger.error(
                    "{0}:  RAND_FILE_SIZE_MIN of {1} cannot be <= to RAND_FILE_SIZE, which is = {2}"
                    .format(self._pars.id, self._pars.rand_file_size_min,
                            self._pars.rand_file_size))
                msg = "{0}:  RAND_FILE_SIZE_MIN of {1} cannot be <= to RAND_FILE_SIZE, which is = {2}".format(
                    self._pars.id, self._pars.rand_file_size_min,
                    self._pars.rand_file_size)
                raise AcsBaseException(AcsBaseException.INVALID_PARAMETER, msg)
            else:
                rand_file_size_min = self._pars.rand_file_size_min
        else:
            rand_file_size_min = 0
        if rand_file_size_min > 0:
            rand_file_size = int(
                random.randrange(rand_file_size_min,
                                 self._pars.rand_file_size + 1))
        else:
            rand_file_size = self._pars.rand_file_size
        rand_file_seed = self._pars.rand_file_seed
        rand_file_name = self._pars.rand_file_name

        self._logger.debug(
            "%s:  rand_file_size = %d, rand_file_seed = %d, rand_file_name = %s "
            % (self._pars.id, rand_file_size, rand_file_seed, rand_file_name))

        file_path = os.path.join(destination_path, rand_file_name)

        try:
            # Create the file
            self.create_rand_bin_file(file_path=file_path,
                                      file_size_mb=rand_file_size,
                                      seed=rand_file_seed)
        except Exception as e:
            raise AcsToolException(AcsToolException.DEFAULT_ERROR_CODE, str(e))

        # Check the file was created
        if os.path.exists(file_path):
            self._logger.info("{0}:  Created {1} to {2}".format(
                self._pars.id, rand_file_name, destination_path))
            context.set_info(self._pars.ctx_destination_path, file_path)
        else:
            msg = "{0}:  Failed to create {1} to {2}".format(
                self._pars.id, rand_file_name, destination_path)
            raise DeviceException(DeviceException.OPERATION_FAILED, msg)
Ejemplo n.º 22
0
    def _do_folder_operation(self, folder_level, folder_name_length, src_path):
        """
        Do the file operation with parameters.

        :type folder_level: int
        :param folder_level: The folder level.
        :type folder_sub_number: int
        :param folder_sub_number: The sub folder number in each folder.
        :type folder_name_length: int
        :param folder_name_length: The folder name length, name will generate randomly.
        :type src_path: str
        :param src_path: The path of file or folder will be created.

        :rtype: list
        :return: operation status & output log
        """
        # FOLDER CREATION TEST eg toto file on EMMC
        # The path of file or folder will be created, emmc|mnt_sdcard|mnt_sdcard_ext
        status = False

        # Generate file name(s)
        folder_name = binascii.b2a_hex(os.urandom(folder_name_length / 2))
        folder_name = src_path + folder_name

        # Check if sdcard requested, if requested, mount it
        self._auto_mount_external_drive(folder_name)

        # create folder(s)
        self._logger.info("Create folder %s ..." % folder_name)
        self.create_folder(folder_name)

        self._logger.info("Check folder creation ...")
        status, output = self.exist(folder_name)
        if not status:
            msg = "Folder %s does not exists !" % folder_name
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        # delete folder
        self.delete(folder_name)

        if not status:
            raise AcsToolException(AcsToolException.OPERATION_FAILED, output)

        # If operations succeed, return True
        return status
Ejemplo n.º 23
0
    def untar(self, file_name, destination=None, unzip=False):
        """
        Untar a file on the DUT.  Throws AcsToolException.OPERATION_FAILED if there's an error.
        :type file_name: str
        :param file_name: name of the file (the absolute path of the file on DUT)
        :type destination: str
        :param destination: folder where to unzip the file (the absolute path of the folder on DUT).
        :type unzip: boolean
        :param unzip: if True archive will be unzipped before being extracted
        """

        # Find out size of the file to use as a basis for calculating a timeout for the unzip command.  ls -l should put that in column 4.
        cmd = "adb shell stat -c %%s %s" % file_name
        (return_code, output) = self._device.run_cmd(cmd, timeout=10)
        if return_code != Utils.Global.SUCCESS:
            msg = "uecmd untar: Error '%s' when trying to list the file '%s'" % (
                output, file_name)
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        # Trusting that 'ls -l' provided file size in column 4.  If this does not have a number, then 'int' will throw an exception.
        file_size = int(output)
        timeout = int(file_size / 4096)
        if timeout < 100000:
            # Set a 100s minimum unzip timeout for small files
            timeout = 100000

        device_path = os.path.dirname(file_name)
        options = "-xzf" if unzip else "-xf"
        cmd = "adb shell cd " + device_path + "; tar " + options + " " + file_name
        if destination:
            # add option to command
            cmd += " -C " + destination
            # create output folder if needed
            _, dest_exists = self.exist(destination)
            if not dest_exists:
                self._exec("adb shell mkdir -p " + destination, 1)

        (return_code, output_msg) = self._device.run_cmd(cmd, timeout=timeout)
        if return_code != Utils.Global.SUCCESS:
            msg = "uecmd untar: Error '%s' when running '%s'" % (output_msg,
                                                                 cmd)
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)
Ejemplo n.º 24
0
    def _perform_ims_deregistration(self):
        """
        Perform IMS de-registration using AT command / IMS config

        :return: the verdict and its corresponding message
        :rtype: int, str

        :raise AcsToolException OPERATION_FAILED: if an error occurred during the
            AT command execution.
        """
        # Initialize local variables
        verdict = Global.SUCCESS
        message = "No error"

        # AT Command for un register fails if the DUT is not registered to IMS
        registration_status = self._get_registration_status()
        self._logger.info("Registration status: %s (expected %s)." % (
            str(registration_status),
            str(ImsRegistrationStatus.in_service())))
        state = (registration_status != ImsRegistrationStatus.in_service())
        self._logger.debug("Comparison status: %s" % str(state))
        if registration_status != ImsRegistrationStatus.in_service():
            self._logger.info("DUT is not registered to IMS, nothing to do.")
            return (Global.SUCCESS, "Nothing to do.")

        if self._ims_configure_modem_procedure == "IMS_ANDROID":
            # Turn off IMS
            self._modem_api.turn_ims("OFF")
            # Wait 5 seconds
            time.sleep(5)
        else:
            # Execute at+xireg=0 command
            (status, message) = self._execute_at_command("at+xireg=0")
            if status != Global.SUCCESS:
                message = "%s (%s)." % (
                    "An error occured during IMS de-registration",
                    message)
                raise AcsToolException(
                    AcsToolException.OPERATION_FAILED,
                    message)
            # Wait 15 seconds
            time.sleep(15)

        # Check the registration status for IMS, should be "OUT_OF_SERVICE"
        ims_service_status = ImsRegistrationStatus.out_of_service()
        # Log the latest IMS registration status
        registration_status = self._get_registration_status()
        self._logger.info("Registration status: %s (%d)" % (
            str(registration_status),
            registration_status.as_int()))

        if registration_status != ims_service_status:
            verdict = Global.FAILURE
            message = "IMS is still registered after registration OFF."

        return (verdict, message)
Ejemplo n.º 25
0
 def _run(self):
     """
     Run stop acquisition
     """
     if self._patlib is None:
         raise AcsToolException(
             AcsToolException.PROHIBITIVE_BEHAVIOR,
             "Cannot report acquisition, PatLib has not been initialized")
     report = self._patlib.report(self._pars.do_power_calculation)
     self._context.set_info(self._pars.save_as, report)
Ejemplo n.º 26
0
    def _run(self):
        """
        Run stop acquisition
        """
        if self._patlib is None:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Cannot do acquisition, PatLib has not been initialized")
        acquisition_status = self._context.get_info("AcquisitionStatus")

        if acquisition_status == "Stopped":
            # retrieve all measurements of previous acquisition
            measures = self._patlib.get_measurements()
            if not measures:
                raise AcsToolException(AcsToolException.OPERATION_FAILED,
                                       "Cannot retrieve any measure")
            # retrieve all measures according to rail name
            measures = [
                measure for measure in measures
                if measure.get("name") == self._pars.measure_name
            ]
            if not measures:
                raise AcsToolException(
                    AcsToolException.OPERATION_FAILED,
                    "Cannot retrieve measure for {0}".format(
                        self._pars.measure_name))
            # retrieve all measures according to measure type (average or max or min)
            measures = [
                measure[self._pars.measure_type] for measure in measures
                if measure.get(self._pars.measure_type) is not None
            ]
            if not measures:
                raise AcsToolException(
                    AcsToolException.OPERATION_FAILED,
                    "Cannot retrieve measure {0} for {1}".format(
                        self._pars.measure_type, self._pars.measure_name))
            self._context.set_info(self._pars.save_as, measures[-1])
        else:
            raise AcsToolException(
                AcsToolException.PROHIBITIVE_BEHAVIOR,
                "Cannot get acquisition: Status %s instead of Stopped " %
                acquisition_status)
Ejemplo n.º 27
0
 def _compute_score(self, measures, rail):
     """
     Compute result according to specified operation
     """
     functor = get_math_function(self._pars.operation)
     raw_results = []
     if not rail in measures:
         raise AcsToolException(
             AcsToolException.PROHIBITIVE_BEHAVIOR,
             "Measure does not contains '{0}' residency information".format(
                 rail))
     for measure in measures[rail]:
         value = measure.get("average")
         if value is None:
             raise AcsToolException(
                 AcsToolException.PROHIBITIVE_BEHAVIOR,
                 "Cannot retrieve residency {0}".format(rail))
         raw_results.append(value)
     computed_result = str(functor(raw_results))
     return computed_result
Ejemplo n.º 28
0
    def is_equal(self, file1, file2):
        """
        compare the checksum of 2 files to see is they are equals

        :type file1: str
        :param file1: first file to compare from

        :type file2: str
        :param file2: second file to compare with

        :rtype: tuple
        :return: (boolean operation success, error msg)
        """
        self._logger.info("comparing if file %s is equal to %s" %
                          (file1, file2))

        cmd = "adb shell md5 %s" % file1
        output = self._exec(cmd).strip()
        if self.is_shell_output_ok(output):
            sum1 = output.split(" ")[0].strip()
        else:
            msg = "error when generating md5sum value :" + output
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        cmd = "adb shell md5 %s" % file2
        output = self._exec(cmd).strip()
        if self.is_shell_output_ok(output):
            sum2 = output.split(" ")[0].strip()
        else:
            msg = "error when generating md5sum value :" + output
            self._logger.error(msg)
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        if sum1 == sum2:
            msg = "Files %s and %s are identical" % (file1, file2)
        else:
            msg = "Files %s and %s are different" % (file1, file2)

        return sum1 == sum2, msg
Ejemplo n.º 29
0
    def _download2cache(self, resp, a_name):
        """

        :param resp: :class:`requests.Response <requests.Response>` (:mod:`requests`)
        :type resp: HTTPResponse

        :param a_name: Artifact's name
        :type a_name: str

        :return: A Cached Artifact instance
        :rtype: Cache.CachedArtifact

        :raises: AcsBaseException.OPERATION_FAILED
                 AcsToolException.HOST_OPERATION_TIMEOUT,
                 AcsConfigException.INVALID_PARAMETER,
                 ArtifactoryCacheManager.Error,
                 IOError,
                 OSError,
                 WindowsError (if windows platform)

        """
        cache_exc = self.__cache_engine.Error
        try:
            _, _, local_path = self.__http_downloader.download(resp)
            if not path.isfile(local_path):
                raise AcsToolException(
                    AcsToolException.OPERATION_FAILED,
                    "Downloaded Artifact {0} with path: "
                    "{1} is not VALID!".format(a_name, local_path))
            art = self.__cache_engine.add(a_name, local_path)
        except (SysErrors, cache_exc):
            # We ensure that if any exception occur, we wrapped it into more detailed one properly
            msg = ("Exception occurred while Downloading "
                   "to Cache remote Artifact {0} - "
                   "Detailed exception below:\n{1}".format(
                       a_name, traceback.format_exc()))
            raise AcsToolException(AcsToolException.OPERATION_FAILED, msg)

        return art
Ejemplo n.º 30
0
    def __is_mms_sent(self, time_out):
        """
        Method that will wait for the MMS to be send.
        It will wait for the MMS to be send until the timeout has been reached.

        :type time_out: int
        :param time_out: time to wait for the MMS to be send.

        :rtype: str
        :return: the time when the message has been sent.

        :raise AcsToolException: if the output is missing one of the expected keys.
        :raise DeviceException: if the message takes more time than the timeout to be sent.
        """
        # Defining task id key for passing parameters to embedded.
        message_id_key = "msg_id"
        thread_id_key = "thread_id"
        sent_time_key = "sent_time"
        # Defining functions name.
        function = "isMmsSent"
        is_mms_sent = False
        start_time = time.time()

        while (time.time() - start_time) < time_out and is_mms_sent == False:
            output = self._internal_exec_v2(
                self._mms_module,
                function,
                "--es %s %s --es %s %s" % (message_id_key, self.sent_msg_id,
                                           thread_id_key, self.sent_thread_id),
                is_system=True)

            if sent_time_key not in output:
                raise AcsToolException(
                    AcsToolException.INVALID_PARAMETER,
                    "output key %s not found: %s" % (message_id_key, output))
            if output.get(sent_time_key) != "-1":
                is_mms_sent = True
            else:
                time.sleep(5)
        if is_mms_sent:
            msg = "Send Command was succesfull. Message found with id: %s in conversation: %s" \
                  % (self.sent_msg_id, self.sent_thread_id)
            self._logger.info(msg)
            return output.get(sent_time_key)
        else:
            message_box_name = self.__get_mms_box()
            raise DeviceException(
                DeviceException.TIMEOUT_REACHED,
                "The Mms was not send in time (waited %s seconds). It is in the %s box "
                % (time_out, message_box_name))