Example #1
0
 def wait_until_page_contains_element(self, locator, timeout):
     """
     Waits until `element` appears on current page or `timeout` expires.
     """
     try:
         self._wait_until_keyword_returns_true(timeout, timestr_to_secs(timeout)/10, "is_element_present", locator)               
     except Exception, err:
         if not 'did not become true' in str(err):
             raise
         timestr = secs_to_timestr(timestr_to_secs(timeout))
         raise AssertionError("Element '%s' did not appear in '%s'" 
                               % (locator, timestr))
Example #2
0
 def wait_until_element_visible(self, locator, timeout):
     """
     Waits until the element is visble. Can be used to wait for ajax calls. 
     """
     try:
         self._wait_until_keyword_returns_true(timeout, timestr_to_secs(timeout)/10, "is_visible", locator)               
     except Exception, err:
         if not 'did not become true' in str(err):
             raise
         timestr = secs_to_timestr(timestr_to_secs(timeout))
         raise AssertionError("Element '%s' did not appear in '%s'" 
                               % (locator, timestr))
Example #3
0
 def wait_until_page_contains(self, text, timeout):
     """Waits until `text` appears on current page or `timeout` expires.
     Over-rided the Robot Framework built-in keyword to make it work with IE.
     """
     try:
         #if not('*iexplore' in self._selenium.browserStartCommand or '*iehta' in self._selenium.browserStartCommand):
         #    JavaScript.wait_until_page_contains(self, text, timeout)
         #else:
         self._wait_until_keyword_returns_true(timeout, timestr_to_secs(timeout)/10, "is_text_present", text)               
     except Exception, err:
         if not 'did not become true' in str(err):
             raise
         timestr = secs_to_timestr(timestr_to_secs(timeout))
         raise AssertionError("Text '%s' did not appear in '%s'" 
                               % (text, timestr))
 def application_started(self, alias, timeout='60 seconds', rmi_url=None):
     if self._rmi_client:
         raise RuntimeError("Application already connected")
     self.alias = alias
     timeout = timestr_to_secs(timeout or '60 seconds')
     self._rmi_client = self._connect_to_base_rmi_service(alias, timeout, rmi_url)
     print "*INFO* Connected to remote service at '%s'" % self.rmi_url
Example #5
0
 def _convert_time_to_seconds(self, time):
     if isinstance(time, timedelta):
         # timedelta.total_seconds() is new in Python 2.7
         return (time.days * 24 * 60 * 60 +
                 time.seconds +
                 time.microseconds / 1e6)
     return timestr_to_secs(time, round_to=None)
 def _wait_until_page_ready(self, timeout=None):
     """Semi blocking API that incorporated different strategies for cross-browser support."""
     if self._block_until_page_ready:
         delay = self._browser_breath_delay
         if delay < 1:
             delay *= 10
         # let the browser take a deep breath...
         sleep(delay)
         timeout = self._implicit_wait_in_secs \
             if timeout is None else utils.timestr_to_secs(timeout)
         browser = self._current_browser()
         try:
             WebDriverWait(None, timeout, self._poll_frequency).\
                 until_not(staleness_of(browser.find_element_by_tag_name('html')), '')
         except:
             # instead of halting the process because document is not ready
             # in <TIMEOUT>, we try our luck...
             self._debug(exc_info()[0])
         try:
             WebDriverWait(browser, timeout, self._poll_frequency).\
                 until(lambda driver: driver.
                       execute_async_script(self._page_ready_bootstrap), '')
         except:
             # instead of halting the process because document is not ready
             # in <TIMEOUT>, we try our luck...
             self._debug(exc_info()[0])
         for keyword in self._page_ready_keyword_list:
             self._builtin.run_keyword(keyword)
    def start_watchdog_timer(self, value, action="Hard Reset",
            timer_use="SMS OS"):
        """Sets and starts IPMI watchdog timer.

        The watchdog is set to `value` and after that it is started.

        The maximum value is 6553 seconds. `value` is given in Robot
        Framework's time format (e.g. 1 minute 20 seconds) that is explained in
        the User Guide.

        `action` can be:
            No Action, Hard Reset, Power Down, Power Cycle
        `timer_use` can be:
            OEM, SMS OS, OS Load, BIOS Post, BIOS Frb2
        """

        timer_use = find_watchdog_timer_use(timer_use)
        config = pyipmi.bmc.Watchdog()
        config.timer_use = timer_use
        config.dont_stop = 1
        config.dont_log = 0
        config.pre_timeout_interval = 0
        config.pre_timeout_interrupt = 0
        config.timer_use_expiration_flags = 0xff
        # convert to 100ms
        config.initial_countdown = int(utils.timestr_to_secs(value) * 10)
        if (config.initial_countdown > 0xffff):
            raise RuntimeError('Watchdog value out of range')
        config.timeout_action = find_watchdog_action(action)
        # set watchdog
        self._ipmi.set_watchdog_timer(config)
        # start watchdog
        self._ipmi.reset_watchdog_timer()
    def wait_for_current_java_application_to_close(self, timeout="3 Minutes"):
        """Waits for the currently connected Java application to shut down.\n\n
        *Arguments*\n
        _timeout_\n
        (optional) maximum wait time (default: 3 Minutes).\n\n
        *Return value*\n
        None\n\n
        *Precondition*\n
        None\n\n
        *Example*
        | Wait for current Java Application to Close |  |
        | Wait for current Java Application to Close  | timeout=5 Minutes |
        """
        start_time = datetime.datetime.now()
        timeout_in_seconds = utils.timestr_to_secs(timeout)
        has_timed_out = False
        while self._check_java_application_is_available_on_port(self._port) and not has_timed_out:
            if (datetime.datetime.now() - start_time).seconds > timeout_in_seconds:
                has_timed_out = True
            else:
                time.sleep(3)

        if has_timed_out:
            raise RuntimeError("Timeout waiting for Java application to close.")
        for alias, port in self._all_gateway_ports.items():
            if port==self._port:
                del self._all_gateway_ports[alias]
        self._port = None
        self._all_gateway_ports.sync()
Example #9
0
    def select_window_when_visible(self, win_name, timeout=30, delay=5):
        """
        This keyword will try to select a given window based on the
        title, name, or url that you give it.  it will try to do so
        for as long as your timeout argument.  If you don't specify,
        it will use 30 sec.

        :param win_name: name of the window
        :type win_name: str
        :param timeout: the time to wait for current page should be(defaults to 30)
        :type timeout: int
        :param delay: the time to sleep between each loop (defaults to 5)
        :type delay: int
        :return: current Page
        :rtype: Page
        """

        timeout = utils.timestr_to_secs(timeout)
        maxtime = time.time() + timeout
        visible = False
        while not visible:
            try:
                self.register_keyword_to_run_on_failure("Nothing")
                self.select_window(win_name)
                visible = True
            except:
                if time.time() > maxtime:
                    self.register_keyword_to_run_on_failure("Capture Page Screenshot")
                    raise Exception('Window, %s, did not appear' % win_name)
                else:
                    time.sleep(delay)
        self.register_keyword_to_run_on_failure("Capture Page Screenshot")
        return self
Example #10
0
 def wait_for_page_to_load(self,timeout):
     """
     Waits for a new page to load.
     Over-rided the Robot Framework built-in keyword to fix the timing issues.
     """
     timeout = timestr_to_secs(timeout)
     self._selenium.wait_for_page_to_load(timeout*1000)
    def wait_for_async_condition(self, condition, timeout=None, error=None):
        """Waits until the given asynchronous ``condition`` is true or ``timeout`` expires.

        Arguments:
        - ``condition``: The ``condition`` can be arbitrary JavaScript expression but
                         must explicitly signal when they are finished by invoking
                         the provided callback at the end. See `Execute Async Javascript`
                         for information about executing asynchronous JavaScript.
        - ``timeout``: The maximum value to wait for ``condition`` to come back true.
                       See `introduction` for more information about ``timeout`` and
                       its default value.
        - ``error``: The value that would be use to override the default error message.

        See also `Wait For Condition`, `Wait Until Page Contains`, `Wait Until Page Contains
        Element`, `Wait Until Element Is Visible` and
        BuiltIn keyword `Wait Until Keyword Succeeds`.

        Examples:
        | Wait For Async Condition | arguments[arguments.length-1](true) | 15s |
        """
        timeout = self._timeout_in_secs if timeout is None else utils.timestr_to_secs(timeout)
        if not error:
            error = "Condition '%s' did not become true in %s" % \
                (condition, self._format_timeout(timeout))
        WebDriverWait(self._current_browser(), timeout, self._poll_frequency).\
            until(lambda driver: driver.execute_async_script(condition), error)
Example #12
0
 def _wait_until_keyword_returns_true(self, timeout, retry_interval, name, *args):
     """Helper method for wait_until_page_contains"""
     timeout = timestr_to_secs(timeout)
     retry_interval = timestr_to_secs(retry_interval)
     starttime = time.time()
     while time.time() - starttime < timeout:
         try:
             self._info("Waiting %s for condition '%s' to be true." 
                 % (secs_to_timestr(timestr_to_secs(retry_interval)), args[0]))  
             if not BuiltIn.run_keyword(BuiltIn(), name, *args):
                 time.sleep(retry_interval)
             else:
                 self._info("Return True in '%s' " % (secs_to_timestr(time.time() - timestr_to_secs(starttime))))
                 return True              
         except Exception:
             time.sleep(retry_interval)
     raise AssertionError("did not become true")
Example #13
0
 def _get_timeout(self, timeout):
     try:
         tout = utils.secs_to_timestr(utils.timestr_to_secs(timeout.string))
     except ValueError:
         tout = timeout.string
     if timeout.message:
         tout += ' :: ' + timeout.message
     return tout
Example #14
0
 def sleep(self,time_,reason=None):
     seconds = utils.timestr_to_secs(time_)
     if seconds <0:
         seconds =0
     self._sleep_in_parts(seconds)
     self.log('Slept %s' %utils.secs_to_timestr(seconds))
     if reason:
         self.log(reason)
 def wait_until_element_is_visible(self, locator, timeout=None, error=None):
     timeout = self._implicit_wait_in_secs if timeout is None else utils.timestr_to_secs(timeout)
     if not error:
         error = "Element '%s' was not visible in %s" % (locator, self._format_timeout(timeout))
     element = self._element_find(locator, True, True)
     if element is None:
         raise AssertionError("Element '%s' not found." % locator)
     WebDriverWait(None, timeout, self._poll_frequency).until(visibility_of(element), error)
 def _application_started(self, alias, timeout=60, name_contains=None, accept_old=True):
     self.TIMEOUT = timestr_to_secs(timeout)
     url = self._get_agent_address(name_contains, accept_old)
     logger.info('connecting to started application at %s' % url)
     self._initialize_remote_libraries(alias, url)
     RemoteSwingLibrary.CURRENT = alias
     logger.debug('modifying robot framework namespace')
     self.ROBOT_NAMESPACE_BRIDGE.re_import_remoteswinglibrary()
     logger.info('connected to started application at %s' % url)
    def wait_for_angular(self, timeout=None, error=None):

        # Determine timeout and error
        timeout = timeout or self._s2l.get_selenium_timeout()
        timeout = timestr_to_secs(timeout)
        error = error or 'Ext was not loaded before the specified timeout'

        WebDriverWait(self._s2l._current_browser(), timeout, 0.2)\
            .until(lambda x: self._s2l._current_browser().execute_script(js_wait_for_angular))
Example #18
0
 def _wait_until_no_error(self, timeout, wait_func, *args):
     timeout = timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
     maxtime = time.time() + timeout
     while True:
         timeout_error = wait_func(*args)
         if not timeout_error: return
         if time.time() > maxtime:
             raise AssertionError(timeout_error)
         time.sleep(0.2)
Example #19
0
    def wait_for_process(self, handle=None, timeout=None, on_timeout='continue'):
        """Waits for the process to complete or to reach the given timeout.

        The process to wait for must have been started earlier with
        `Start Process`. If `handle` is not given, uses the current
        `active process`.

        `timeout` defines the maximum time to wait for the process. It is
        interpreted according to Robot Framework User Guide Appendix
        `Time Format`, for example, '42', '42 s', or '1 minute 30 seconds'.

        `on_timeout` defines what to do if the timeout occurs. Possible values
        and corresponding actions are explained in the table below. Notice
        that reaching the timeout never fails the test.

        |  = Value =  |               = Action =               |
        | `continue`  | The process is left running (default). |
        | `terminate` | The process is gracefully terminated.  |
        | `kill`      | The process is forcefully stopped.     |

        See `Terminate Process` keyword for more details how processes are
        terminated and killed.

        If the process ends before the timeout or it is terminated or killed,
        this keyword returns a `result object` containing information about
        the execution. If the process is left running, Python `None` is
        returned instead.

        Examples:
        | # Process ends cleanly      |                  |                  |
        | ${result} =                 | Wait For Process | example          |
        | Process Should Be Stopped   | example          |                  |
        | Should Be Equal As Integers | ${result.rc}     | 0                |
        | # Process does not end      |                  |                  |
        | ${result} =                 | Wait For Process | timeout=42 secs  |
        | Process Should Be Running   |                  |                  |
        | Should Be Equal             | ${result}        | ${NONE}          |
        | # Kill non-ending process   |                  |                  |
        | ${result} =                 | Wait For Process | timeout=1min 30s | on_timeout=kill |
        | Process Should Be Stopped   |                  |                  |
        | Should Be Equal As Integers | ${result.rc}     | -9               |

        `timeout` and `on_timeout` are new in Robot Framework 2.8.2.
        """
        process = self._processes[handle]
        result = self._results[process]
        logger.info('Waiting for process to complete.')
        if timeout:
            timeout = timestr_to_secs(timeout)
            if not self._process_is_stopped(process, timeout):
                logger.info('Process did not complete in %s.'
                            % secs_to_timestr(timeout))
                return self._manage_process_timeout(handle, on_timeout.lower())
        result.rc = process.wait() or 0
        logger.info('Process completed.')
        return result
Example #20
0
    def set_timeout(self, timeout):
        """Sets the timeout used in read operations to given value represented as timestr, e.g. "120 sec".

        The read operations will for this time before starting to read from
        the output. To run operations that take a long time to generate their
        complete output, this timeout must be set accordingly.
        """
        old = utils.secs_to_timestr(self._timeout)
        self._timeout = float(utils.timestr_to_secs(timeout))
        return old
Example #21
0
    def set_pause(self, pause):
        """Sets the timeout used in read socket response, e.g. "120 sec".

        The read operations will for this time before starting to read from
        the output. To run operations that take a long time to generate their
        complete output, this timeout must be set accordingly.
        """
        old = utils.secs_to_timestr(self._pause)
        self._pause = float(utils.timestr_to_secs(pause))
        return old
Example #22
0
 def _get_timeout(self, timeout):
     if timeout is None:
         return ''
     try:
         tout = utils.secs_to_timestr(utils.timestr_to_secs(timeout.value))
     except ValueError:
         tout = timeout.value
     if timeout.message:
         tout += ' :: ' + timeout.message
     return tout
Example #23
0
    def wait_for_process(self, handle=None, timeout=None, on_timeout='continue'):
        """Waits for the process to complete or to reach the given timeout.

        The process to wait for must have been started earlier with
        `Start Process`. If ``handle`` is not given, uses the current
        `active process`.

        ``timeout`` defines the maximum time to wait for the process. It can be
        given in
        [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|
        various time formats] supported by Robot Framework, for example, ``42``,
        ``42 s``, or ``1 minute 30 seconds``.

        ``on_timeout`` defines what to do if the timeout occurs. Possible values
        and corresponding actions are explained in the table below. Notice
        that reaching the timeout never fails the test.

        | = Value = |               = Action =               |
        | continue  | The process is left running (default). |
        | terminate | The process is gracefully terminated.  |
        | kill      | The process is forcefully stopped.     |

        See `Terminate Process` keyword for more details how processes are
        terminated and killed.

        If the process ends before the timeout or it is terminated or killed,
        this keyword returns a `result object` containing information about
        the execution. If the process is left running, Python ``None`` is
        returned instead.

        Examples:
        | # Process ends cleanly      |                  |                  |
        | ${result} =                 | Wait For Process | example          |
        | Process Should Be Stopped   | example          |                  |
        | Should Be Equal As Integers | ${result.rc}     | 0                |
        | # Process does not end      |                  |                  |
        | ${result} =                 | Wait For Process | timeout=42 secs  |
        | Process Should Be Running   |                  |                  |
        | Should Be Equal             | ${result}        | ${NONE}          |
        | # Kill non-ending process   |                  |                  |
        | ${result} =                 | Wait For Process | timeout=1min 30s | on_timeout=kill |
        | Process Should Be Stopped   |                  |                  |
        | Should Be Equal As Integers | ${result.rc}     | -9               |

        ``timeout`` and ``on_timeout`` are new in Robot Framework 2.8.2.
        """
        process = self._processes[handle]
        logger.info('Waiting for process to complete.')
        if timeout:
            timeout = timestr_to_secs(timeout)
            if not self._process_is_stopped(process, timeout):
                logger.info('Process did not complete in %s.'
                            % secs_to_timestr(timeout))
                return self._manage_process_timeout(handle, on_timeout.lower())
        return self._wait(process)
 def open_connection(self):
     start_time = time.time()
     timeout = timestr_to_secs(self.timeout)
     while time.time() - start_time < timeout:
         try:
             self.remote_lib = RobotRemoteLibrary(self.uri)
             return
         except (BeanCreationException, RemoteConnectFailureException):
             time.sleep(2)
     message = "Could not get connection to '%s' in '%s'!" 
     raise RuntimeError(message %(self.uri, self.timeout))
 def replace_variables(self, variables):
     try:
         self.string = variables.replace_string(self.string)
         if not self.string or self.string.upper() == 'NONE':
             return
         self.secs = utils.timestr_to_secs(self.string)
         self.string = utils.secs_to_timestr(self.secs)
         self.message = variables.replace_string(self.message)
     except (DataError, ValueError), err:
         self.secs = 0.000001 # to make timeout active
         self.error = 'Setting %s failed: %s' % (self.type.lower(), unicode(err))
 def replace_variables(self, variables):
     try:
         self.string = variables.replace_string(self.string)
         if not self:
             return
         self.secs = timestr_to_secs(self.string)
         self.string = secs_to_timestr(self.secs)
         self.message = variables.replace_string(self.message)
     except (DataError, ValueError) as err:
         self.secs = 0.000001  # to make timeout active
         self.error = (u'Setting %s timeout failed: %s'
                       % (self.type.lower(), err))
    def __init__(self, application, timeout='60 seconds'):
        """ApplicationLauncher takes one mandatory and one optional argument.

        `application` is a required argument, it is the name of the main
        class or the class that has the main method.

        `timeout` is the timeout used to wait for importing a remote library.
        """
        self.application = application
        self.timeout = timestr_to_secs(timeout)
        self.builtin = BuiltIn()
        self.operating_system = OperatingSystem()
        self.rmi_url = None
    def wait_until_ext_is_ready(self, timeout=None, error=None):

        # Determine timeout and error
        timeout = timeout or self._selenium().get_selenium_timeout()
        timeout = timestr_to_secs(timeout)
        error = error or 'Ext was not loaded before the specified timeout'

        # Wait for Ext to be ready
        maxtime = time.time() + timeout
        while not self._exec_js("return window.Ext ? true : false"):
            if time.time() > maxtime:
                raise AssertionError(error)
            time.sleep(0.2)
 def _application_started(self, alias, timeout=60, name_contains="",
                          remote_port=0, remote_host="127.0.0.1", accept_old=True):
     RemoteSwingLibrary.TIMEOUT = timestr_to_secs(timeout)
     if remote_port:
         url = '%s:%s' % (remote_host, remote_port)
         REMOTE_AGENTS_LIST.remove(url)
     else:
         url = self._get_agent_address(name_contains, accept_old)
     logger.info('connecting to started application at %s' % url)
     self._initialize_remote_libraries(alias, url)
     RemoteSwingLibrary.CURRENT = alias
     self._wait_for_api(url)
     logger.info('connected to started application at %s' % url)
     self._remove_policy_file()
    def set_selenium_speed(self, seconds):
        """Sets the delay that is waited after each Selenium command.

        This is useful mainly in slowing down the test execution to be able to
        view the execution.  `seconds` may be given in Robot Framework time
        format.  Returns the previous speed value.

        Example:
        | Set Selenium Speed | 2 seconds |
        """
        old = self._selenium.get_speed()
        seconds = str(int(utils.timestr_to_secs(seconds)*1000))
        self._selenium.set_speed(seconds)
        return utils.secs_to_timestr(float(old)/1000)
Example #31
0
    def login(self,
              username,
              password,
              login_prompt='login: '******'Password: '******''
        matched = False
        time.sleep(self._pausetime)
        while time.time() - start_time < int(self._timeout):
            if self.channel.recv_ready():
                c = self.channel.recv(128)
                if c == "":
                    break
                login_ret += c

                login_ret = SshCommon._colorpattern.sub("", login_ret)
                matching_pattern = [
                    pattern for pattern in self._prompt
                    if pattern.search(login_ret[-80:])
                ]
                if len(matching_pattern) > 0:
                    pattern = matching_pattern[0].pattern
                    matched = True
                    break

                continue
            else:
                time.sleep(0.00005)  # wait for CPU.
                # break
        self._log(login_ret, self._loglevel)
        if not matched:
            raise AssertionError(
                'No match found for prompt "%s" in %ssec, detail info: "%s"' %
                (seq2str([x.pattern for x in self._prompt], lastsep=' or '),
                 timestr_to_secs(self._timeout), login_ret))
        self._log("Select pattern '%s' as default pattern" % pattern)
        self.set_prompt(pattern)
        return login_ret
 def sleep_without_logging(self, timestr):
     seconds = utils.timestr_to_secs(timestr)
     self._sleep(seconds)
Example #33
0
 def __init__(self, plugin_id, **kwargs):
     self._data_unit_class = kwargs.pop('data_unit')
     Parser.__init__(self, **kwargs)
     self.id = plugin_id
     self._ts_cache = tools.CacheList(
         int(600 / timestr_to_secs(kwargs.get('interval', '1x'))))
Example #34
0
 def convert_timeout(self, timeout: Union[timedelta, float]) -> float:
     if isinstance(timeout, timedelta):
         return timeout.total_seconds() * 1000
     return timestr_to_secs(timeout) * 1000
Example #35
0
def timestr_to_millisecs(time_str: str) -> int:
    return timestr_to_secs(time_str) * 1000
Example #36
0
 def _get_timeout(self, timeout):
     if (is_string(timeout) and timeout.upper() == 'NONE') or not timeout:
         return -1
     return timestr_to_secs(timeout)
Example #37
0
    def wait_until_salesforce_is_ready(self,
                                       locator=None,
                                       timeout=None,
                                       interval=5):
        """Waits until we are able to render the initial salesforce landing page

        It will continue to refresh the page until we land on a
        lightning page or until a timeout has been reached. The
        timeout can be specified in any time string supported by robot
        (eg: number of seconds, "3 minutes", etc.). If not specified,
        the default selenium timeout will be used.

        This keyword will wait a few seconds between each refresh, as
        well as wait after each refresh for the page to fully render
        (ie: it calls wait_for_aura())

        """

        # Note: we can't just ask selenium to wait for an element,
        # because the org might not be availble due to infrastructure
        # issues (eg: the domain not being propagated). In such a case
        # the element will never come. Instead, what we need to do is
        # repeatedly refresh the page until the org responds.
        #
        # This assumes that any lightning page is a valid stopping
        # point.  If salesforce starts rendering error pages with
        # lightning, or an org's default home page is not a lightning
        # page, we may have to rethink that strategy.

        interval = 5  # seconds between each refresh.
        timeout = timeout if timeout else self.selenium.get_selenium_timeout()
        timeout_seconds = timestr_to_secs(timeout)
        start_time = time.time()
        login_url = self.cumulusci.login_url()
        locator = lex_locators["body"] if locator is None else locator

        while True:
            try:
                self.selenium.wait_for_condition(
                    "return (document.readyState == 'complete')")
                self.wait_for_aura()
                # If the following doesn't throw an error, we're good to go.
                self.selenium.get_webelement(locator)
                break

            except Exception as e:
                self.builtin.log(
                    "caught exception while waiting: {}".format(str(e)),
                    "DEBUG")
                if time.time() - start_time > timeout_seconds:
                    self.selenium.log_location()
                    self.selenium.capture_page_screenshot()
                    raise Exception("Timed out waiting for a lightning page")

            self.builtin.log("waiting for a refresh...", "DEBUG")
            self.selenium.capture_page_screenshot()
            time.sleep(interval)
            location = self.selenium.get_location()
            if ("//test.salesforce.com" in location
                    or "//login.salesforce.com" in location):
                # Sometimes we get redirected to a login URL rather
                # than being logged in, and we've yet to figure out
                # precisely why that happens. Experimentation shows
                # that authentication has already happened, so in
                # this case we'll try going back to the instance url
                # rather than the front door servlet.
                #
                # Admittedly, this is a bit of a hack, but it's better
                # than never getting past this redirect.
                login_url = self.cumulusci.org.config["instance_url"]
                self.builtin.log(
                    f"setting login_url temporarily to {login_url}", "DEBUG")
            self.selenium.go_to(login_url)
 def _format_timeout(self, timeout):
     timeout = timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
     return secs_to_timestr(timeout)
Example #39
0
    def wait_until_angular_ready(self, timeout=None, error=None):
        """Waits until [https://goo.gl/Kzz8Y3|AngularJS] is ready to process the next request or
        ``timeout`` expires.

        You generally *do not* need to call this keyword directly,
        below is the list of keywords which already call this keyword internally:

        | `Click Button`                 |
        | `Click Element`                |
        | `Click Element At Coordinates` |
        | `Click Image`                  |
        | `Click Link`                   |
        | `Double Click Element`         |
        | `Input Password`               |
        | `Input Text`                   |
        | `Open Browser`                 |
        | `Select All From List`         |
        | `Select Checkbox`              |
        | `Select From List`             |
        | `Select From List By Index`    |
        | `Select From List By Label`    |
        | `Select From List By Value`    |
        | `Select Radio Button`          |
        | `Submit Form`                  |

        Arguments:
        - ``timeout``: The maximum value to wait for [https://goo.gl/Kzz8Y3|AngularJS]
                       to be ready to process the next request.
                       See `introduction` for more information about ``timeout`` and
                       its default value.
        - ``error``: The value that would be use to override the default error message.

        See also `Wait For Condition`, `Wait Until Page Contains`,
        `Wait Until Page Contains Element`, `Wait Until Element Is Visible`
        and BuiltIn keyword `Wait Until Keyword Succeeds`.

        Examples:
        | Wait Until Angular Ready | 15s |
        """
        timeout = self._implicit_wait_in_secs if timeout is None else utils.timestr_to_secs(
            timeout)
        if not error:
            error = 'AngularJS is not ready in %s' % self._format_timeout(
                timeout)
        # we add more validation here to support transition between AngularJs to non AngularJS page.
        script = self.NG_WRAPPER % {
            'prefix': 'var cb=arguments[arguments.length-1];'
            'if(window.angular){',
            'handler': 'function(){cb(true)}',
            'suffix': '}else{cb(true)}'
        }
        browser = self._current_browser()
        browser.set_script_timeout(timeout)
        try:
            WebDriverWait(browser, timeout, self._poll_frequency).\
                until(lambda driver: driver.execute_async_script(script), error)
        except TimeoutException:
            # prevent double wait
            pass
        except:
            self._debug(exc_info()[0])
            # still inflight, second chance. let the browser take a deep breath...
            sleep(self._browser_breath_delay)
            try:
                WebDriverWait(browser, timeout, self._poll_frequency).\
                    until(lambda driver: driver.execute_async_script(script), error)
            except:
                # instead of halting the process because AngularJS is not ready
                # in <TIMEOUT>, we try our luck...
                self._debug(exc_info()[0])
            finally:
                browser.set_script_timeout(self._timeout_in_secs)
        finally:
            browser.set_script_timeout(self._timeout_in_secs)
Example #40
0
 def _get_timestr_in_milliseconds(time_string):
     return timestr_to_secs(time_string) * 1000
 def _get_timestr_in_milliseconds(self, time_string):  # pylint: disable=no-self-use
     return timestr_to_secs(time_string) * 1000
Example #42
0
 def _wait_completion_ex(self, handle, timeout, handle_timeout):
     timeout_reached = False
     if timeout:
         timeout = timestr_to_secs(timeout)
         timeout_reached = self._is_timeout_reached_ex(handle, timeout)
     return self._handle_process_shutdown_ex(handle, timeout_reached, handle_timeout)
Example #43
0
 def _format_timeout(self, timeout):
     timeout = timestr_to_secs(timeout) if is_truthy(
         timeout) else self.ctx._timeout_in_secs
     return secs_to_timestr(timeout)
Example #44
0
 def __init__(cls, value_str):
     super().__init__(int(timestr_to_secs(value_str)),
                      type=int,
                      units='seconds')
 def timeout(self: "SeleniumTestability", value: str) -> None:
     self.ctx.testability_settings["timeout"] = timestr_to_secs(value)
def _convert_timeout(timeout):
    if isinstance(timeout, timedelta):
        return timeout.total_seconds()
    return timestr_to_secs(timeout)
Example #47
0
 def _verify_login_without_prompt(self, delay, incorrect):
     time.sleep(utils.timestr_to_secs(delay))
     output = self.telnet_read('TRACE')
     success = incorrect not in output
     return success, output
Example #48
0
 def _set_timeout(self, timeout):
     self._timeout = utils.timestr_to_secs(timeout)
Example #49
0
def get_timeout(**kwargs):
    timeout = timestr_to_secs(CONFIG["DefaultTimeout"])
    if 'timeout' in kwargs:
        if timestr_to_secs(kwargs['timeout']) != 0:
            timeout = timestr_to_secs(kwargs['timeout'])
    return timeout
Example #50
0
    def wait_until_salesforce_is_ready(self,
                                       locator=None,
                                       timeout=None,
                                       interval=5):
        """Waits until we are able to render the initial salesforce landing page

        It will continue to refresh the page until we land on a
        lightning page or until a timeout has been reached. The
        timeout can be specified in any time string supported by robot
        (eg: number of seconds, "3 minutes", etc.). If not specified,
        the default selenium timeout will be used.

        This keyword will wait a few seconds between each refresh, as
        well as wait after each refresh for the page to fully render
        (ie: it calls wait_for_aura())

        """

        # Note: we can't just ask selenium to wait for an element,
        # because the org might not be availble due to infrastructure
        # issues (eg: the domain not being propagated). In such a case
        # the element will never come. Instead, what we need to do is
        # repeatedly refresh the page until the org responds.
        #
        # This assumes that any lightning page is a valid stopping
        # point.  If salesforce starts rendering error pages with
        # lightning, or an org's default home page is not a lightning
        # page, we may have to rethink that strategy.

        interval = 5  # seconds between each refresh.
        timeout = timeout if timeout else self.selenium.get_selenium_timeout()
        timeout_seconds = timestr_to_secs(timeout)
        start_time = time.time()
        login_url = self.cumulusci.login_url()
        locator = lex_locators["body"] if locator is None else locator

        while True:
            try:
                self.selenium.wait_for_condition(
                    "return (document.readyState == 'complete')")
                self.wait_for_aura()

                # If the following doesn't throw an error, we're good to go.
                self.selenium.get_webelement(locator)
                break

            except Exception as e:
                self.builtin.log(
                    "caught exception while waiting: {}".format(str(e)),
                    "DEBUG")
                if time.time() - start_time > timeout_seconds:
                    self.selenium.log_location()
                    raise Exception("Timed out waiting for a lightning page")

            # known edge cases that can be worked around
            if self._check_for_login_failure():
                continue
            elif self._check_for_classic():
                continue

            # not a known edge case; take a deep breath and
            # try again.
            time.sleep(interval)
            self.selenium.go_to(login_url)
Example #51
0
 def _get_timeout(self, timeout=None):
     if timeout:
         return utils.timestr_to_secs(timeout)
     return self._timeout
Example #52
0
 def _convert_time_to_seconds(self, time):
     if isinstance(time, timedelta):
         # timedelta.total_seconds() is new in Python 2.7
         return (time.days * 24 * 60 * 60 + time.seconds +
                 time.microseconds / 1e6)
     return timestr_to_secs(time, round_to=None)
 def timestr_to_secs_for_default_timeout(self, timeout):
     if timeout is None or timeout == '':
         timeout = self.library_ctx.timeout
     return timestr_to_secs(timeout)
 def _get_timeout_value(timeout, default):
     """Returns default timeout when timeout is None."""
     return default if timeout is None else utils.timestr_to_secs(timeout)
Example #55
0
def timestr_to_millisecs(timestr):
    return int(timestr_to_secs(timestr) * 1000)
 async def _wait_until(self, condition, error, timeout=None):
     if timeout is None:
         timeout = '30s'
     timeout = timestr_to_secs(timeout)
     await self._wait_until_worker(condition, timeout, error)
Example #57
0
 def try_time_string_to_secs(time_str):
     try:
         return timestr_to_secs(time_str)
     except Exception:
         return -1
Example #58
0
 def _convert_time_to_seconds(self, time):
     if isinstance(time, timedelta):
         return time.total_seconds()
     return timestr_to_secs(time, round_to=None)
Example #59
0
def format_robot_time(timestr):
    secs = utils.timestr_to_secs(timestr)
    return utils.secs_to_timestr(secs)
 def stop(self, timeout=None):
     timeout = timeout or '20s'
     timeout = timestr_to_secs(timeout)
     self._internal_event.set()
     self._thread.join(timeout)
     self._thread = None