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

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

        DeviceTestStepBase.run(self, context)

        self._logger.debug("START OF INITIATE_VOICE_CALL_LOOP")
        phone_number = self._pars.phone_number_to_call
        test_duration = self._pars.test_duration * 60
        call_interval = self._pars.call_interval
        disconnection_allowance = self._pars.disconnection_allowance
        if self._pars.call_duration is not None:
            call_duration = self._pars.call_duration
        else:
            call_duration = 0
        if self._pars.calls_made is not None:
            verification = True
        else:
            verification = False
        number_of_initiated_calls = 0
        num_consecutive_disconnect = 0
        total_disconnect = 0
        # Timeout value to use that determines amount of time to wait on gui focus lock file to be removed.
        self.gui_lock_wait_time = self._pars.gui_lock_wait_time
        # App signature to use with gui focus lock file
        appSignature = 'initiate_voice_call'
        try:
            # Delete any focus-lock file that may not have been released during the previous test run.
            osbv_utils.cleanup_focus_lock(appSignature)
        except:
            raise DeviceException(
                DeviceException.OPERATION_FAILED, self._pars.id +
                ": Issue trying to remove previous focus lock file.")

        # Get UECmdLayer
        voice_call_api = self._device.get_uecmd("VoiceCall")
        self._logger.debug(
            "Test duration for INITIATE_VOICE_CALL_LOOP is set to {0} minutes".
            format(str(self._pars.test_duration)))
        start_time = time.time()

        # Release any previous call
        try:
            voice_call_api.release()
        except:
            self.ts_verdict_msg = "INITIATE_VOICE_CALL_LOOP failed to release previous call on {0} device.".format(
                str(self._config.device_name))
            raise DeviceException(
                DeviceException.OPERATION_FAILED,
                "INITIATE_VOICE_CALL_LOOP:  Failed to release previous call")
        verdict = Global.SUCCESS
        # Start Voice call loop
        while time.time() - start_time < test_duration:
            try:
                self._logger.debug(
                    "INITIATE_VOICE_CALL_LOOP:  Calling from {0} device.".
                    format(str(self._config.device_name)))
                if not osbv_utils.set_focus_lock(
                        appSignature, timeout_sec=self.gui_lock_wait_time):
                    # Could not set the focus-lock
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        self._pars.id + ": Failed to set focus lock.")
                voice_call_api.dial(phone_number)
                self._logger.debug(
                    "INITIATE_VOICE_CALL_LOOP:  Sleep for call duration of {0} seconds."
                    .format(str(call_duration)))
                # Call duration of 0 would let us just make calls and not worry about being answered.  When forked with voice_call_answer, call duration should account for time
                # it takes from when call is ACTIVE on caller until time call can be recognized as INCOMING (ringing) on the other device.
                time.sleep(call_duration)
                # Hang up on caller side should release this call and if in forked with voice_call_answer, should release that call as well.
                voice_call_api.release()
                if not osbv_utils.release_focus_lock(appSignature):
                    # Could not release the focus-lock
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        self._pars.id + ": Failed to release focus lock.")
                self._logger.debug(
                    "INITIATE_VOICE_CALL_LOOP:  Call was released on {0} device."
                    .format(str(self._config.device_name)))
            except DeviceException as de:
                # Increase number of consecutive disconnects.
                num_consecutive_disconnect += 1
                total_disconnect += 1
                self._logger.debug(
                    "INITIATE_VOICE_CALL_LOOP:  DeviceException while initiating phone call: {0}"
                    .format(de.get_error_message()))
                self._logger.debug(
                    "INITIATE_VOICE_CALL_LOOP:  {0} consecutive Device Exception occurred ({1} allowed) trying to initiate a call."
                    .format(num_consecutive_disconnect,
                            disconnection_allowance))
            except:
                import traceback
                self._logger.error(
                    "INITIATE_VOICE_CALL_LOOP:  Unexpected Exception being raised."
                )
                self.ts_verdict_msg = "INITIATE_VOICE_CALL_LOOP: Unexpected Exception being raised."
                self._logger.error(traceback.format_exc())
                raise
            else:
                num_consecutive_disconnect = 0
                number_of_initiated_calls += 1
            finally:
                # Check if focus lock still exists with appSignature and remove if so.
                if appSignature == osbv_utils.get_lock_signature():
                    if not osbv_utils.release_focus_lock(appSignature):
                        # Unable to release the focus-lock
                        raise DeviceException(
                            DeviceException.OPERATION_FAILED,
                            self._pars.id + ": Failed to release focus lock.")
                # Exit loop to finish the test step if too many disconnections.
                if num_consecutive_disconnect > disconnection_allowance:
                    self._logger.error(
                        "INITIATE_VOICE_CALL_LOOP failed due to excessive consecutive disconnections"
                    )
                    self.ts_verdict_msg = "INITIATE_VOICE_CALL_LOOP failed due to {0} excessive consecutive disconnections on {1} device.".format(
                        num_consecutive_disconnect,
                        str(self._config.device_name))
                    verdict = Global.FAILURE
                    break
            self._logger.debug(
                "INITIATE_VOICE_CALL_LOOP:  Sleeping for {0} seconds before next call is initiated."
                .format(str(call_interval)))
            time.sleep(call_interval)

        self._logger.debug(
            "INITIATE_VOICE_CALL_LOOP initiated {0} calls.  There were {1} total disconnects."
            .format(str(number_of_initiated_calls), str(total_disconnect)))
        self._logger.debug("END of INITIATE_VOICE_CALL_LOOP")
        if (verdict != Global.SUCCESS):
            raise DeviceException(DeviceException.OPERATION_FAILED,
                                  "INITIATE_VOICE_CALL_LOOP TestStep failed.")
        else:
            if (verification):
                context.set_info(self._pars.calls_made,
                                 str(number_of_initiated_calls))
Ejemplo n.º 2
0
    def run(self, context):
        """
        Runs the test step

        @type context: TestStepContext
        @param context: test case context
        """
        DeviceTestStepBase.run(self, context)
        self._logger.info(self._pars.id + ": Test step starting.")
        # App signature to use with gui focus lock file
        appSignature = 'record_video_loop'
        try:
            # Delete any focus-lock file that may not have been released during the previous test run.
            osbv_utils.cleanup_focus_lock(appSignature)
        except:
            raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Issue trying to remove previous focus lock file.")
        loop_count = 1
        # variable for the different resolution video recording.
        loop_cnt =0
        self.videos_saved = 0
        self.total_videos_saved = 0
        error_counts = {}
        self.video_file_type = "mp4"
        # Timeout value to use that determines amount of time to wait on gui focus lock file to be removed.
        self.gui_lock_wait_time = self._pars.gui_lock_wait_time
        self._dut_os = self._device.get_device_os_path()
        # Set report path
        self._device_manager = DeviceManager()
        # Create folder under report path to put files into when there is an issue.
        self.report_path = self._device_manager.get_global_config().campaignConfig.get("campaignReportTree").create_subfolder('record_video_loop')
        # Following call creates directory to store files created from TS that will generally not be needed unless an error is hit.
        self.temp_dir = osbv_utils.test_step_temp_dir(self)
        # Create folder under temp_dir to put videos from device into.
        self.host_save_folder = os.path.join(self.temp_dir, 'saved_videos')
        if not os.path.exists(self.host_save_folder):
            os.makedirs(self.host_save_folder)
        # Get UECmdLayer
        self._camera_api = self._device.get_uecmd("Camera")
        self._keyevent_api = self._device.get_uecmd("KeyEvent")
        self._file_api = self._device.get_uecmd("File")
        self._phone_system_api = self._device.get_uecmd("PhoneSystem")
        self._camera_app = self._camera_api.get_camera_version(self._pars.camera_app)
        if self._camera_app == "Android_Intel_Camera_v2.2" or self._camera_app == "Android_Google_Camera_v2.0":
            self._camera_api.camera_app_setup(self._camera_app, 'video')
        else:
            error_msg = self._pars.id + ":  Selected camera app: {0} is not supported".format(self._camera_app)
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, error_msg)

        start_time = float(time.time())
        end_time = start_time + (float(self._pars.duration)) * 60
        try:
            # Following calls will remove all files in the save directory(ies).
            for directory in self._camera_api.device_save_directory:
                try:
                    self._phone_system_api.delete(directory + self._dut_os.sep + '*.*')
                except DeviceException:
                    self._logger.info(self._pars.id + ":  Directory {0} was already empty.".format(directory))
            while (time.time() < end_time): # Primary Test Loop
                # The following actions are executed in every loop:
                #  1. Open the camera app
                #  2. Start video capture
                #  3. Wait a random time period defined by user params
                #  4. Stop video capture
                #  5. Verify video file was created
                #  6. Move the video to our save directory.
                #  7. If loop%self._pars.video_upload_modulus==0, pull save directory to the PC and delete them from the device
                return_code = 0
                video_duration = random.randint(self._pars.video_interval_min, self._pars.video_interval_max)
                self._logger.info(self._pars.id + ":  Loop %d."%(loop_count))
                loop_start_time = datetime.datetime.now()
                # Lock the GUI focus before starting video_capture so that video capture doesn't conflict with other apps.
                if not osbv_utils.set_focus_lock(appSignature, timeout_sec=self._pars.gui_lock_wait_time):
                    # Could not set the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ":  Video Capture failed to set the focus-lock!")
                self._logger.debug(self._pars.id + ":  Starting camera application")

                # Prepare video capture by making sure it is correctly launched and in gui focus.
                (return_code, reset_loop) = self._camera_api.prepare_video_capture(error_counts = error_counts, restart_app = self._pars.restart_app, checkTriglogMsg = True)

                if return_code == -1:
                    # Test has failed
                    #[12/19/14: Jong ] After failure, there does not exist a directory to clean out
                    #self.cleanup_test(error_counts)
                    self.ts_verdict_msg = self._pars.id + ":  Test has failed after trying to capture video!"
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Test has failed after trying to capture video!")

                if reset_loop:
                    # Check if focus lock still exists with video capture's appSignature and remove if so.
                    if appSignature == osbv_utils.get_lock_signature():
                        if not osbv_utils.release_focus_lock(appSignature):
                            # Unable to release the focus-lock
                            raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ":  Video_Capture failed to release the focus-lock!")
                    continue
                # Recording videos of different resolution.
                if self._pars.record_type == 'DIFFRES':
                    device_orient=self._camera_api.device_orientation()
                    # Check camera in use.  We want "BACK" (world facing) camera.
                    stat = self._camera_api.get_camera_in_use()
                    if stat == "FRONT":
                        # Change from "FRONT" to "BACK".
                        self._camera_api.change_camera("back")
                        # Verify whether the camera is changed or not.
                        check_f = self._camera_api.get_camera_in_use()
                        if check_f == "BACK":
                            self._logger.debug("{0}:  'BACK' camera is now selected.".format(self._pars.id))
                        else:
                            self._logger.error("{0}:  Camera is not changed to 'BACK'".format(self._pars.id))
                            raise DeviceException(DeviceException.INVALID_DEVICE_STATE, "{0}: Camera in use should be 'BACK' but is still {1}.".format(self._pars.id, check_f))
                    elif stat == "BACK":
                        self._logger.debug("{0}:  Back camera is selected.".format(self._pars.id))
                    else:
                        self._logger.error("{0}:  Camera is not properly selected.".format(self._pars.id))
                        raise DeviceException(DeviceException.INVALID_DEVICE_STATE, self._pars.id + ":  Camera is not properly selected.")
                    self._camera_api.select_camera_settings()
                    # Switch between different resolution options:  SD, HD, HD(HS), Full HD, Full HD(HS)
                    if device_orient== 'portrait' :
                        keyevent_list= ["DPAD_RIGHT","DPAD_RIGHT","DPAD_RIGHT","ENTER"]
                        for i in range(0,loop_cnt%5) :
                            keyevent_list.append("DPAD_RIGHT")

                    elif device_orient== 'landscape' :
                        keyevent_list= ["DPAD_DOWN","DPAD_DOWN","DPAD_DOWN","ENTER"]
                        for i in range(0,loop_cnt%5) :
                            keyevent_list.append("DPAD_DOWN")
                    else:
                        self._logger.error(self._pars.id + ":  " + device_orient + " is not a proper orientation. ")
                        raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ":  " + device_orient + " is not a proper orientation.")
                    keyevent_list.append("ENTER")
                    self._keyevent_api.scenario(keyevent_list,1)
                    time.sleep(2)
                    loop_cnt+=1
                self._logger.debug(self._pars.id + ":  Recording started. Waiting %d seconds until stopping."%video_duration)
                self._camera_api.camera_application_start_stop_recording(video_duration)
                self._logger.info(self._pars.id + ":  Video recording done.")
                # Release the GUI focus lock so that other apps can take focus
                if not osbv_utils.release_focus_lock(appSignature):
                    # Unable to release the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ":  Video Capture failed to release the focus-lock!")
                # Verify that the video was captured in SD card or eMMC.
                self._logger.info(self._pars.id + ':  Checking for video files in save directory(ies).')
                (video_found, reset_loop, self.videos_saved) = self._camera_api.verify_video_creation(error_counts = error_counts, videos_saved = self.videos_saved)
                if reset_loop:
                    # We must have hit a known issue.  Try to stop app to see if it helps and retry this iteration of the loop.
                    self._camera_api.stop_system_camera_application()
                    continue
                if not video_found:
                    # No video file was found and no known issues were hit. Video capture failed and now exiting thread.
                    self.cleanup_test(error_counts)
                    self.ts_verdict_msg = self._pars.id + ":  No video file was found and no known issues were hit, test has failed."
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to execute correctly.")
                if loop_count%self._pars.video_upload_modulus == 0:
                    # Pull the video files to the PC
                    self._logger.info(self._pars.id + ':  Pulling video files from device to the PC log directory')
                    self._camera_api.upload_output_files(False, self.host_save_folder)
                    self.total_videos_saved += self.videos_saved
                    self.videos_saved = 0
                loop_time_delta = datetime.datetime.now() - loop_start_time
                loop_time_delta_hours = loop_time_delta.seconds/(60*60)
                loop_time_delta_minutes = (loop_time_delta.seconds-(loop_time_delta_hours*(60*60)))/60
                loop_time_delta_seconds = loop_time_delta.seconds-(loop_time_delta_hours*(60*60))-(loop_time_delta_minutes*60)
                self._logger.info(self._pars.id + ":  Loop %d duration: %02d:%02d:%02d"%(loop_count, loop_time_delta_hours, loop_time_delta_minutes, loop_time_delta_seconds))
                loop_count += 1
            self._logger.info(self._pars.id + ':  Test complete successfully. {0} videos recorded'.format(self.total_videos_saved))
            self.cleanup_test(error_counts)
            # Kill the camera app
            self._camera_api.stop_system_camera_application()
        except OSError as e:
            self._logger.error(self._pars.id + ":  OS Error({0}):  {1}".format(e.errno, e.strerror))
            raise
        except:
            import traceback
            self._logger.error(self._pars.id + ":  Unexpected exception -> " + str(sys.exc_info()[0]))
            self._logger.error(traceback.format_exc())
            self.ts_verdict_msg = self._pars.id + ":  Unexpected exception being raised"
            raise
        finally:
            # Check if focus lock still exists with video capture's appSignature and remove if so.
            if appSignature == osbv_utils.get_lock_signature():
                if not osbv_utils.release_focus_lock(appSignature):
                    # Unable to release the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ":  Video_Capture failed to release the focus-lock!")
        self._logger.info(self._pars.id + ": Test step finished.")
    def run(self, context):
        """
        Runs the test step

        :type context: TestStepContext
        :param context: test case context
        """
        self._logger.info(self._pars.id + ": Test step starting.")
        EquipmentTestStepBase.run(self, context)
        # Timeout value to use that determines amount of time to wait on gui focus lock file to be removed.
        # We don't need the GUI, but we are using this mechanism to coordinate with test steps that might generate USB traffic.
        # We do not want them to try using USB while it is disconnected.
        self.usb_lock_wait_time = self._pars.usb_lock_wait_time
        self.appSignature = 'mcci_loop_usb_connect_disconnect'
        self.mcciappPath = self._pars.scripts_path + " -dev 1"

        self.local_computer = self._equipment_manager.get_computer(
            self._pars.eqt)

        try:
            # Delete any focus-lock file that may not have been released during the previous test run.
            osbv_utils.cleanup_focus_lock(self.appSignature)
        except:
            raise AcsBaseException(
                AcsBaseException.OPERATION_FAILED, self._pars.id +
                ": Issue trying to remove previous focus lock file.")

        # Let's try to set the usb speed to be used during test and stop test if hardware is improperly set up or bad self._pars.usb_speed option supplied.
        if self._pars.usb_speed == 1:
            ret = self.USB_HS_On()
            if ret == -1:
                raise TestEquipmentException(
                    TestEquipmentException.SPECIFIC_EQT_ERROR, self._pars.id +
                    ": Issue using MCCI USB Connection Exerciser.  Try checking whether the hardware is correctly set up."
                )
        elif self._pars.usb_speed == 2:
            ret = self.USB_SS_On()
            if ret == -1:
                raise TestEquipmentException(
                    TestEquipmentException.SPECIFIC_EQT_ERROR, self._pars.id +
                    ": Issue using MCCI USB Connection Exerciser.  Try checking whether the hardware is correctly set up."
                )

        try:
            self.plug_unplug()
        except:
            import traceback
            self._logger.error(self._pars.id + ":  Unexpected exception -> " +
                               str(sys.exc_info()[0]))
            self._logger.error(traceback.format_exc())
            self.ts_verdict_msg = self._pars.id + ":  Unexpected exception being raised"
            raise
        finally:
            # Check if focus lock still exists with self.appSignature and remove if so.
            if self.appSignature == osbv_utils.get_lock_signature():
                if not osbv_utils.release_focus_lock(self.appSignature):
                    # Unable to release the focus-lock
                    raise AcsBaseException(
                        AcsBaseException.OPERATION_FAILED,
                        self._pars.id + ": Failed to release focus lock.")
            # Try to leave USB connection on after test.
            self.USB_On(self._pars.usb_speed)
        self._logger.info(self._pars.id + ": Test step finished.")
 def plug_unplug(self):
     start_time = time.time()
     self._logger.info(
         self._pars.id +
         ": ============================================================================"
     )
     self._logger.info(
         self._pars.id +
         ":                          MCCI USB Plug/Unplug test start")
     self._logger.info(
         self._pars.id +
         ": ============================================================================"
     )
     iteration_count = 0
     pass_count = 0
     verdict = True
     self._logger.debug(self._pars.id + ":  test duration (minutes) - " +
                        str(self._pars.duration))
     #We need to end thread earlier than self._pars.duration by at least the time it will take for one pass of this while loop.
     #That way, (start of last unplug/plug loop + length of time for one loop) should be < self._pars.duration and we can finish loop gracefully.
     #This should be ok, as we generally run our tests for 2 hours or more and worse case, we won't unplug/plug USB the last ~5 minutes.
     timeTest = (float(self._pars.duration) *
                 60) - (float(self._pars.time_unplug_duration) * 60 +
                        float(self._pars.time_between_unplug) * 60 + 60)
     #give it an extra 60 seconds for reconnecting and any other necessary calls that are happening.
     while time.time() - start_time < timeTest:
         iteration_count += 1
         self._logger.info("{0}: [Iteration {1}] ".format(
             self._pars.id, iteration_count))
         num_dev = self.check_device_list()
         if not osbv_utils.set_focus_lock(
                 self.appSignature, timeout_sec=self.usb_lock_wait_time):
             # Could not set the focus-lock
             raise AcsBaseException(
                 AcsBaseException.OPERATION_FAILED,
                 self._pars.id + ": Failed to set focus lock.")
         self.USB_Off()
         self._logger.info(
             "{0}: [Iteration {1}] USB cable is unplugged".format(
                 self._pars.id, iteration_count))
         time.sleep(float(self._pars.time_unplug_duration) * 60)
         if self.check_device_list() != (num_dev - 1):
             self._logger.error(
                 "{0}: [Iteration {1}] No device seems to have detached after disconnecting USB.  The test step has failed."
                 .format(self._pars.id, iteration_count))
             verdict = False
         self.USB_On(self._pars.usb_speed)
         if not osbv_utils.release_focus_lock(self.appSignature):
             # Could not release the focus-lock
             raise AcsBaseException(
                 AcsBaseException.OPERATION_FAILED,
                 self._pars.id + ": Failed to release focus lock.")
         self._logger.info(
             "{0}: [Iteration {1}] USB cable is plugged in".format(
                 self._pars.id, iteration_count))
         # Give a little time before checking USB connected state.
         time.sleep(6)
         if self.check_device_list() != num_dev:
             self._logger.error(
                 "{0}: [Iteration {1}] No device seems to have attached after connecting USB.  The test step has failed."
                 .format(self._pars.id, iteration_count))
             verdict = False
         if not verdict:
             self.ts_verdict_msg = self._pars.id + ":  Failed to connect/disconnect USB!"
             raise TestEquipmentException(
                 TestEquipmentException.VERDICT_ERROR,
                 self._pars.id + ": Failed to execute correctly.")
         else:
             pass_count += 1
         time.sleep(float(self._pars.time_between_unplug) * 60)
     self._logger.info("{0}: [Reference] Test finished at {1}".format(
         self._pars.id,
         time.strftime("%m\\%d\\%Y %H:%M:%S", time.localtime())))
     self._logger.info("{0}: [Reference] Total PASS count : {1}".format(
         self._pars.id, pass_count))
     self._logger.info(
         self._pars.id +
         ": ============================================================================"
     )
     self._logger.info(
         self._pars.id +
         ": ============================================================================"
     )
     self._logger.info(
         self._pars.id +
         ":                          MCCI USB Plug/Unplug test end")
     self._logger.info(
         self._pars.id +
         ": ============================================================================"
     )
Ejemplo n.º 5
0
    def run(self, context):
        """
        Runs the test step

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

        self._logger.info(self._pars.id + ': Run')

        verdict = Global.SUCCESS

        src_file = self._pars.resource_files_path
        duration = self._pars.duration
        execution_seconds = duration * 60
        # Timeout value to use that determines amount of time to wait on gui focus lock file to be removed.
        # We don't need the GUI, but we are using this mechanism to coordinate with test steps that might disconnect USB.
        # We do not want to try push/pull while USB is disconnected.
        self.usb_lock_wait_time = self._pars.usb_lock_wait_time
        appSignature = 'usb_adb_pushpull'
        try:
            # Delete any focus-lock file that may not have been released during the previous test run.
            osbv_utils.cleanup_focus_lock(appSignature)
        except:
            raise DeviceException(
                DeviceException.OPERATION_FAILED, self._pars.id +
                ": Issue trying to remove previous focus lock file.")

        self._logger.info(self._pars.id + ':  SRC is ' + src_file)

        test_files_root = os.path.dirname(self._pars.resource_files_path)

        test_start_time = time.time()
        test_end_time = test_start_time + float(execution_seconds)
        self._logger.info(
            self._pars.id +
            ':  ============================================================================'
        )
        self._logger.info(self._pars.id +
                          ':                           ADB Push/Pull test')
        self._logger.info(
            self._pars.id +
            ':  ============================================================================'
        )
        md5_reference = hashlib.md5(open(src_file, 'rb').read()).hexdigest()
        self._logger.info(self._pars.id +
                          ':  [Reference] ADB transfer root path is ' +
                          test_files_root)
        self._logger.info(
            self._pars.id + ':  [Reference] Test started at {0}'.format(
                time.strftime('%m\\%d\\%Y %H:%M:%S', time.localtime())))
        self._logger.info(
            self._pars.id +
            ':  [Reference] MD5 Check_SUM = {0}'.format(str(md5_reference)))
        self._logger.info(
            self._pars.id +
            ':  ============================================================================'
        )

        iteration_count = 0
        pass_count = 0
        fail_count = 0
        while (time.time() < test_end_time):
            try:
                iteration_count += 1

                if not osbv_utils.set_focus_lock(
                        appSignature, timeout_sec=self.usb_lock_wait_time):
                    # Could not set the focus-lock
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        self._pars.id + ": Failed to set focus lock.")

                iteration_start_time = time.localtime()
                self._logger.info(
                    self._pars.id + ':  [Iteration {0}] Started at {1}'.format(
                        str(iteration_count),
                        time.strftime('%H:%M:%S', iteration_start_time)))

                self._logger.info(
                    self._pars.id +
                    ':  [Iteration {0}] Remove files in the host folder'.
                    format(str(iteration_count)))
                if os.path.exists(os.path.join(test_files_root,
                                               'adb_test.bin')):
                    os.remove(os.path.join(test_files_root, 'adb_test.bin'))
                time.sleep(3)

                self._logger.info(
                    self._pars.id +
                    ':  [Iteration {0}] Remove files in the device'.format(
                        str(iteration_count)))
                adb_command = 'adb shell "if [ -f /storage/sdcard0/adb_test.bin ]; then rm -r /storage/sdcard0/adb_test.bin; fi;"'
                self._device.run_cmd(cmd=adb_command, timeout=20)
                time.sleep(3)

                self._logger.info(
                    self._pars.id +
                    ':  [Iteration {0}] Push files from the source folder to the device'
                    .format(str(iteration_count)))
                adb_command = 'adb push {0} /storage/sdcard0/adb_test.bin'.format(
                    os.path.join(test_files_root, src_file))
                self._device.run_cmd(cmd=adb_command, timeout=20)
                time.sleep(3)

                self._logger.info(
                    self._pars.id +
                    ':  [Iteration {0}] Pull files from the device to the destination folder'
                    .format(str(iteration_count)))
                adb_command = 'adb pull /storage/sdcard0/adb_test.bin {0}'.format(
                    os.path.join(test_files_root, 'adb_test.bin'))
                self._device.run_cmd(cmd=adb_command, timeout=20)
                time.sleep(3)

                if not osbv_utils.release_focus_lock(appSignature):
                    # Could not release the focus-lock
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        self._pars.id + ": Failed to release focus lock.")

                iteration_end_time = time.localtime()
                self._logger.info(
                    self._pars.id +
                    ':  [Iteration {0}] finished at {1}'.format(
                        str(iteration_count),
                        time.strftime('%H:%M:%S', iteration_end_time)))

                # Check and make sure our file exists
                if not os.path.exists(
                        os.path.join(test_files_root, 'adb_test.bin')):
                    fail_count += 1
                    break

                md5_result = hashlib.md5(
                    open(os.path.join(test_files_root, 'adb_test.bin'),
                         'rb').read()).hexdigest()

                if md5_result == md5_reference and md5_reference != 0:
                    self._logger.info(
                        self._pars.id +
                        ':  [Iteration {0}] PASS : MD5 Check_SUM = {1}'.format(
                            str(iteration_count), str(md5_result)))
                    pass_count += 1
                else:
                    self._logger.info(
                        self._pars.id +
                        ':  [Iteration {0}] FAIL : MD5 Check_SUM = {1} does not match'
                        .format(str(iteration_count), str(md5_result)))
                    fail_count += 1
                self._logger.info(
                    self._pars.id +
                    ':  ============================================================================'
                )

                if fail_count > 0:
                    break
            except:
                import traceback
                self._logger.error(self._pars.id +
                                   ":  Unexpected Exception being raised.")
                self.ts_verdict_msg = self._pars.id + ": Unexpected Exception being raised."
                self._logger.error(traceback.format_exc())
                raise
            finally:
                # Check if focus lock still exists with appSignature and remove if so.
                if appSignature == osbv_utils.get_lock_signature():
                    if not osbv_utils.release_focus_lock(appSignature):
                        # Unable to release the focus-lock
                        raise DeviceException(
                            DeviceException.OPERATION_FAILED,
                            self._pars.id + ": Failed to release focus lock.")
                #shutil.rmtree(src_file)

        self._logger.info(
            self._pars.id + ':  [Reference] Test finished at {0}'.format(
                time.strftime('%m\\%d\\%Y %H:%M:%S', time.localtime())))
        self._logger.info(
            self._pars.id +
            ':  [Reference] Total PASS count : {0}'.format(pass_count))
        self._logger.info(
            self._pars.id +
            ':  [Reference] Total FAIL count : {0}'.format(fail_count))
        self._logger.info(
            self._pars.id +
            ':  ============================================================================'
        )

        if (fail_count > 0):
            msg = 'USB ADB Push/PUll FAILED'
            self.ts_verdict_msg = msg
            raise DeviceException(DeviceException.OPERATION_FAILED, msg)

        self._logger.info(self._pars.id + ': PASSED')
Ejemplo n.º 6
0
    def run(self, context):
        """
        Runs the test step

        @type context: TestStepContext
        @param context: test case context
        """
        DeviceTestStepBase.run(self, context)
        self._logger.info(self._pars.id + ": Test step starting.")
        # App signature to use with gui focus lock file
        appSignature = 'take_pictures_loop'
        try:
            # Delete any focus-lock file that may not have been released during the previous test run.
            osbv_utils.cleanup_focus_lock(appSignature)
        except:
            raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Issue trying to remove previous focus lock file.")
        loop = 1
        numPicsTaken = 0
        num_pics_to_take = 2
        # Number of consecutive retries in loop before it would fail due to too many.
        max_retries = 50
        retry = max_retries
        self.pic_file_type = "jpg"
        self._dut_os = self._device.get_device_os_path()
        # Set report path
        self._device_manager = DeviceManager()
        self.report_path = self._device_manager.get_global_config().campaignConfig.get("campaignReportTree").create_subfolder('take_pictures_loop')
        # Following call creates directory to store files created from TS that will generally not be needed unless an error is hit.
        self.temp_dir = osbv_utils.test_step_temp_dir(self)
        # Create folder under temp_dir to put pictures from device into.
        self.host_save_folder = os.path.join(self.temp_dir, 'saved_pics')
        # Timeout value to use that determines amount of time to wait on gui focus lock file to be removed.
        self.gui_lock_wait_time = self._pars.gui_lock_wait_time
        if not os.path.exists(self.host_save_folder):
            os.makedirs(self.host_save_folder)
        # Get UECmdLayer
        self._camera_api = self._device.get_uecmd("Camera")
        self._file_api = self._device.get_uecmd("File")
        self._camera_app = self._camera_api.get_camera_version(self._pars.camera_app)
        # Set camera application to image capture mode
        self._camera_api.camera_app_setup(self._camera_app, 'camera')

        start_time = float(time.time())
        end_time = start_time + (float(self._pars.duration)) * 60

        errorCount = {
                'camConnectionErr':0,
                'camStopped'      :0,
                'camNotResponding':0,
                'unclassifiedFail':0
                    }

        try:
            # Following calls will remove all files in the save directory(ies).
            for directory in self._camera_api.device_save_directory:
                try:
                    self._device.get_uecmd("PhoneSystem").delete(directory + self._dut_os.sep + '*.*')
                except DeviceException:
                    self._logger.info(self._pars.id + ":  Directory {0} was already empty.".format(directory))
            # Verify which camera app is used and run the below commands only if Intel camera is used.
            if self._camera_app in ("Android_Intel_Camera_v2.2", "Android_Intel_Refcam2_v0.9", "Android_Google_Camera_v2.4", "Android_Intel_RefCam_v1.0"):
                #Open the camera app to check the initial camera used(Front or Back)
                self._camera_api.launch_system_camera_application(checkTriglogMsg = True, reset = True)

                # Wait for 4 second to load the camera app. the first launch takes longer due to driver initialization
                time.sleep(4)

                # Check camera in use and if it is not what user has chosen to be used, change it.
                stat = self._camera_api.get_camera_in_use()
                if stat != self._pars.camera_to_use:
                    # We need to switch the camera in use.
                    if stat == "BACK":
                        self._camera_api.change_camera("front")
                    elif stat == "FRONT":
                        self._camera_api.change_camera("back")
                    else:
                        raise DeviceException(DeviceException.INVALID_DEVICE_STATE, self._pars.id + ": Camera used is " + stat + ", failing test.")

                    # Wait for 2 second to switch camera
                    time.sleep(2)

                    # Verify whether the camera is changed or not.
                    check_f = self._camera_api.get_camera_in_use()
                    if self._pars.camera_to_use == check_f:
                        self._logger.info("{0}:  {1} camera is now selected.".format(self._pars.id, self._pars.camera_to_use))
                    else:
                        self._logger.error("{0}:  Camera is not changed".format(self._pars.id))
                        raise DeviceException(DeviceException.INVALID_DEVICE_STATE, "{0}: Camera in use should be {1} but is still {2}.".format(self._pars.id, self._pars.camera_to_use, check_f))

            while (time.time() < end_time):
                self._logger.info(self._pars.id + ":  Starting loop {0}".format(loop))
                time_start1 = float(time.time())
                self._logger.info(self._pars.id + ":  Start image capturing:")
                if not osbv_utils.set_focus_lock(appSignature, timeout_sec=self.gui_lock_wait_time):
                    # Could not set the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to set focus lock.")
                if self._pars.restart_app:
                    # Stops and starts app.
                    self._camera_api.launch_system_camera_application(checkTriglogMsg = True, reset = True)
                else:
                    # Displays app if not started.
                    self._camera_api.launch_system_camera_application(checkTriglogMsg = True)

                # Wait for 1 second to re-load the camera app
                time.sleep(1)

                if self._camera_app in ("Android_Intel_Refcam2_v0.9", "Android_Intel_RefCam_v1.0"):
                    # take picture
                    if self._pars.camera_mode == "BURST":
                        #Settings for selecting burst mode
                        self._camera_api.toggle_burst_mode()
                        self._camera_api.camera_refcam_take_picture(1)
                    else:
                        self._camera_api.camera_refcam_take_picture(num_pics_to_take)
                else :
                    # Sleeps default of 5 seconds between each picture for a non-burst mode.
                    self._camera_api.camera_application_take_picture(num_pics_to_take)

                if not osbv_utils.release_focus_lock(appSignature):
                    # Could not release the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to release focus lock.")
                retVal = int(self._camera_api.move_files_to_backup_dir(self._camera_api.device_save_directory))
                if (retVal - numPicsTaken) == 0:
                    # Check the error type and increment errorCount appropriately
                    errorCode = self._camera_api.check_for_camera_issues(errorCount)
                    # Reset the retry counter if this is a known issue
                    if errorCode != 'unclassifiedFail':
                        retry = max_retries
                    if retry < 1:
                        # The test failed
                        self.fail_test_cleanup(numPicsTaken, errorCount)
                        self.ts_verdict_msg = self._pars.id + ":  Too many loop retries, test has failed."
                        raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to execute correctly.")
                    self._logger.info(self._pars.id + ":  This iteration of image capture failed.  Allowing %d more attempts..."%(retry-1))
                    retry -= 1
                    continue
                elif retry < max_retries:
                    # image_capture recovered, so reset the retry counter
                    retry = max_retries
                numPicsTaken = retVal
                # Count iteration time
                self.delta(time_start1,1, loop)
                loop += 1
                if ((loop % 20) == 0):
                    self._logger.info(self._pars.id + ':  Copy newly captured images to host dir: {0}'.format(self.host_save_folder))
                    time_start2 = float(time.time())
                    #Pull pics to host every 20 iterations of loop.
                    self._camera_api.upload_output_files(False, self.host_save_folder)
                    self.delta(time_start2, 2, loop)
                # Sleep at random interval between min and max before moving towards next loop iteration.
                time.sleep(random.randint(self._pars.picture_interval_min, self._pars.picture_interval_max))
                self._logger.info(self._pars.id + ":  Number of pictures taken = %d"%numPicsTaken)
            # Times up! The test passed if it made it this far without encountering a failure and we've taken pictures.
            time_start2= float(time.time())
            self.delta(time_start2,2, loop)
            # The test passed unless 0 pictures were taken.
            if numPicsTaken < 1:
                self._logger.info(self._pars.id + ' is at the end of the test but has {0} pictures were taken... faling test.'.format(numPicsTaken))
                self.fail_test_cleanup(numPicsTaken, errorCount)
                self.ts_verdict_msg = self._pars.id + ":  Finished loop without any pictures taken!"
                raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to execute correctly.")
            else:
                self.pass_test_cleanup(numPicsTaken, errorCount)
        except OSError as e:
            self._logger.error(self._pars.id + ":  OS Error({0}):  {1}".format(e.errno, e.strerror))
            raise
        except:
            import traceback
            self._logger.error(self._pars.id + ":  Unexpected exception -> " + str(sys.exc_info()[0]))
            self._logger.error(traceback.format_exc())
            self.ts_verdict_msg = self._pars.id + ":  Unexpected exception being raised"
            raise
        finally:
            # Check if focus lock still exists with video capture's appSignature and remove if so.
            if appSignature == osbv_utils.get_lock_signature():
                if not osbv_utils.release_focus_lock(appSignature):
                    # Unable to release the focus-lock
                    raise DeviceException(DeviceException.OPERATION_FAILED, self._pars.id + ": Failed to release focus lock.")
        self._logger.info(self._pars.id + ": Test step finished.")
        #Close the camera after the test is completed.
        self._camera_api.stop_system_camera_application()