Best Python code snippet using slash
test_webrtc_peer_connection.py
Source:test_webrtc_peer_connection.py  
...85        self.tab.Navigate(cr.browser.platform.http_server.UrlOf(86                os.path.join(self.bindir, html_file.name)))87        self.tab.WaitForDocumentReadyStateToBeComplete()88        if self.before_start_hook is not None:89            self.before_start_hook(self.tab)90        self.tab.EvaluateJavaScript(91                "startTest(%d, %d, %d)" % (92                        self.test_runtime_seconds,93                        self.num_peer_connections,94                        self.iteration_delay_millis))95    def _test_done(self):96        """97        Determines if the test is done or not.98        Does so by querying status of the JavaScript test runner.99        @return True if the test is done, false if it is still in progress.100        @raise TestFail if the status check returns a failure status.101        """102        status = self.tab.EvaluateJavaScript('getStatus()')103        if status.startswith('failure'):104            raise error.TestFail(105                    'Test status starts with failure, status is: ' + status)106        logging.debug(status)107        return status == 'ok-done'108    def wait_test_completed(self, timeout_secs):109        """110        Waits until the test is done.111        @param timeout_secs Max time to wait in seconds.112        @raises TestError on timeout, or javascript eval fails, or113                error status from the getStatus() JS method.114        """115        start_secs = time.time()116        while not self._test_done():117            spent_time = time.time() - start_secs118            if spent_time > timeout_secs:119                raise utils.TimeoutError(120                        'Test timed out after {} seconds'.format(spent_time))121            self.do_in_wait_loop()122    def do_in_wait_loop(self):123        """124        Called repeatedly in a loop while the test waits for completion.125        Subclasses can override and provide specific behavior.126        """127        time.sleep(1)128    @helper_logger.video_log_wrapper129    def run_test(self):130        """131        Starts the test and waits until it is completed.132        """133        with chrome.Chrome(extra_browser_args = EXTRA_BROWSER_ARGS + \134                           [helper_logger.chrome_vmodule_flag()],135                           init_network_controller = True) as cr:136            own_script_path = os.path.join(137                    self.bindir, self.own_script)138            common_script_path = webrtc_utils.get_common_script_path(139                    self.common_script)140            # Create the URLs to the JS scripts to include in the html file.141            # Normally we would use the http_server.UrlOf method. However,142            # that requires starting the server first. The server reads143            # all file contents on startup, meaning we must completely144            # create the html file first. Hence we create the url145            # paths relative to the common prefix, which will be used as the146            # base of the server.147            base_dir = os.path.commonprefix(148                    [own_script_path, common_script_path])149            base_dir = base_dir.rstrip('/')150            own_script_url = own_script_path[len(base_dir):]151            common_script_url = common_script_path[len(base_dir):]152            html_file = webrtc_utils.create_temp_html_file(153                    self.title,154                    self.tmpdir,155                    own_script_url,156                    common_script_url)157            # Don't bother deleting the html file, the autotest tmp dir will be158            # cleaned up by the autotest framework.159            try:160                cr.browser.platform.SetHTTPServerDirectories(161                    [own_script_path, html_file.name, common_script_path])162                self.start_test(cr, html_file)163                self.wait_test_completed(self.timeout)164                self.verify_status_ok()165            finally:166                # Ensure we always have a screenshot, both when succesful and167                # when failed - useful for debugging.168                self.take_screenshots()169    def verify_status_ok(self):170        """171        Verifies that the status of the test is 'ok-done'.172        @raises TestError the status is different from 'ok-done'.173        """174        status = self.tab.EvaluateJavaScript('getStatus()')175        if status != 'ok-done':176            raise error.TestFail('Failed: %s' % status)177    def take_screenshots(self):178        """179        Takes screenshots using two different mechanisms.180        Takes one screenshot using graphics_utils which is a really low level181        api that works between the kernel and userspace. The advantage is that182        this captures the entire screen regardless of Chrome state. Disadvantage183        is that it does not always work.184        Takes one screenshot of the current tab using Telemetry.185        Saves the screenshot in the results directory.186        """187        # Replace spaces with _ and lowercase the screenshot name for easier188        # tab completion in terminals.189        screenshot_name = self.title.replace(' ', '-').lower() + '-screenshot'190        self.take_graphics_utils_screenshot(screenshot_name)191        self.take_browser_tab_screenshot(screenshot_name)192    def take_graphics_utils_screenshot(self, screenshot_name):193        """194        Takes a screenshot of what is currently displayed.195        Uses the low level graphics_utils API.196        @param screenshot_name: Name of the screenshot.197        """198        try:199            full_filename = screenshot_name + '_graphics_utils'200            graphics_utils.take_screenshot(self.debugdir, full_filename)201        except StandardError as e:202            logging.warn('Screenshot using graphics_utils failed', exc_info = e)203    def take_browser_tab_screenshot(self, screenshot_name):204        """205        Takes a screenshot of the current browser tab.206        @param screenshot_name: Name of the screenshot.207        """208        if self.tab is not None and self.tab.screenshot_supported:209            try:210                screenshot = self.tab.Screenshot(timeout = 10)211                full_filename = os.path.join(212                        self.debugdir, screenshot_name + '_browser_tab.png')213                image_util.WritePngFile(screenshot, full_filename)214            except exceptions.Error as e:215                # This can for example occur if Chrome crashes. It will216                # cause the Screenshot call to timeout.217                logging.warn(218                        'Screenshot using telemetry tab.Screenshot failed',219                        exc_info = e)220        else:221            logging.warn(222                    'Screenshot using telemetry tab.Screenshot() not supported')223class WebRtcPeerConnectionPerformanceTest(WebRtcPeerConnectionTest):224    """225    Runs a WebRTC performance test.226    """227    def __init__(228            self,229            title,230            own_script,231            common_script,232            bindir,233            tmpdir,234            debugdir,235            timeout = 70,236            test_runtime_seconds = 60,237            num_peer_connections = 5,238            iteration_delay_millis = 500,239            before_start_hook = None):240          def perf_before_start_hook(tab):241              """242              Before start hook to disable cpu overuse detection.243              """244              if before_start_hook:245                  before_start_hook(tab)246              tab.EvaluateJavaScript('cpuOveruseDetection = false')247          super(WebRtcPeerConnectionPerformanceTest, self).__init__(248                  title,249                  own_script,250                  common_script,251                  bindir,252                  tmpdir,253                  debugdir,254                  timeout,255                  test_runtime_seconds,256                  num_peer_connections,257                  iteration_delay_millis,258                  perf_before_start_hook)259          self.collector = system_metrics_collector.SystemMetricsCollector(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
