Esempio n. 1
0
    def _find(self, driver):

        self._driver = driver
        self._wait = Wait(self._driver, self._timeout)

        # waiting for loading elements
        for locator in _LOADING_LOCATORS:
            self._wait.element_disappear(locator)
        self._element = self._wait.element_appear(self._locator, msg="Didn't find element by %s: <%s>" % self._locator)
        return self._element
Esempio n. 2
0
 def test_clicking_a_link_made_up_of_numbers_is_handled_correctly(self):
     test_html = self.marionette.absolute_url("clicks.html")
     self.marionette.navigate(test_html)
     self.marionette.find_element(By.LINK_TEXT, "333333").click()
     Wait(self.marionette, timeout=30, ignored_exceptions=NoSuchElementException).until(
         lambda m: m.find_element(By.ID, 'username'))
     self.assertEqual(self.marionette.title, "XHTML Test Page")
Esempio n. 3
0
 def wait_for_element_attribute_to_be_false(self,
                                            element,
                                            attribute,
                                            timeout=10):
     Wait(self.marionette, timeout) \
         .until(lambda e: element.get_attribute(attribute) == "false",
                message="Timeout out waiting for " + attribute + " to be false")
Esempio n. 4
0
 def test_should_submit_a_form_when_any_element_wihin_that_form_is_submitted(self):
     test_html = self.marionette.absolute_url("formPage.html")
     self.marionette.navigate(test_html)
     self.marionette.find_element(By.XPATH, "//form/p").submit()
     Wait(self.marionette, ignored_exceptions=NoSuchElementException).until(
         lambda m: m.find_element(By.ID, 'email'))
     self.assertEqual(self.marionette.title, "We Arrive Here")
    def testJSWindowCreationAndSwitching(self):
        test_html = self.marionette.absolute_url("test_windows.html")
        self.marionette.navigate(test_html)

        self.current_window = self.marionette.current_window_handle
        link = self.marionette.find_element("link text", "Open new window")
        link.click()

        windows = self.marionette.window_handles
        windows.remove(self.current_window)
        self.marionette.switch_to_window(windows[0])

        title = self.marionette.execute_script("return document.title")
        results_page = self.marionette.absolute_url("resultPage.html")
        self.assertEqual(self.marionette.get_url(), results_page)
        self.assertEqual(title, "We Arrive Here")

        #ensure navigate works in our current window
        other_page = self.marionette.absolute_url("test.html")
        self.marionette.navigate(other_page)
        other_window = self.marionette.current_window_handle

        #try to access its dom
        #since Bug 720714 stops us from checking DOMContentLoaded, we wait a bit
        Wait(self.marionette,
             timeout=30,
             ignored_exceptions=NoSuchElementException).until(
                 lambda m: m.find_element(By.ID, 'mozLink'))

        self.assertEqual(other_window, self.marionette.current_window_handle)
        self.marionette.switch_to_window(self.current_window)
        self.assertEqual(self.current_window,
                         self.marionette.current_window_handle)
Esempio n. 6
0
    def switch_into_test_container(self):
        self.marionette.set_context(self.marionette.CONTEXT_CONTENT)

        frame = Wait(self.marionette, timeout=10, interval=0.2).until(element_present(
            'css selector',
            'iframe[src*="app://test-container.gaiamobile.org/index.html"]'
        ))

        self.marionette.switch_to_frame(frame)
    def _download_report(self):
        """Initiates the download of a report and returns the file path of the download."""
        requested_time = datetime.now() - timedelta(seconds=3)
        self.driver.find_element_by_xpath('//*[@id="form"]/div/div/div/div/div[1]/div/div/button').click()
        Wait().until(self._report_ready, requested_time=requested_time)

        self.driver.find_elements_by_xpath('//*[text()="XLSX"]')[1].click()
        BrowserWait(driver=self.driver).until_angular_loads()

        return BrowserWait(driver=self.driver).until_file_downloaded()
Esempio n. 8
0
    def test_find_anonymous_children(self):
        el = Wait(self.marionette).until(element_present("id", "dia"))
        self.assertEquals(HTMLElement, type(el.find_element("anon", None)))
        self.assertEquals(2, len(el.find_elements("anon", None)))

        el = self.marionette.find_element("id", "framebox")
        with self.assertRaises(NoSuchElementException):
            el.find_element("anon", None)
        self.assertEquals([], el.find_elements("anon", None))
    def test_find_anonymous_element_by_attribute(self):
        el = Wait(self.marionette).until(element_present("id", "dia"))
        self.assertEquals(HTMLElement, type(el.find_element("anon attribute", {"anonid": "buttons"})))
        self.assertEquals(1, len(el.find_elements("anon attribute", {"anonid": "buttons"})))

        with self.assertRaises(NoSuchElementException):
            el.find_element("anon attribute", {"anonid": "nonexistent"})
        self.assertEquals([], el.find_elements("anon attribute", {"anonid": "nonexistent"}))
    def test_find_anonymous_children(self):
        el = Wait(self.marionette).until(element_present("id", "dia"))
        self.assertEquals(HTMLElement, type(el.find_element("anon", None)))
        self.assertEquals(2, len(el.find_elements("anon", None)))

        el = self.marionette.find_element("id", "framebox")
        with self.assertRaises(NoSuchElementException):
            el.find_element("anon", None)
        self.assertEquals([], el.find_elements("anon", None))
Esempio n. 11
0
    def switch_into_test_container(self):
        self.marionette.set_context("content")
        frame = None
        try:
            frame = self.marionette.find_element(
                'css selector',
                'iframe[src*="app://test-container.gaiamobile.org/index.html"]'
            )
        except NoSuchElementException:
            result = self.marionette.execute_async_script("""
if((navigator.mozSettings == undefined) || (navigator.mozSettings == null) || (navigator.mozApps == undefined) || (navigator.mozApps == null)) {
    marionetteScriptFinished(false);
    return;
}
let setReq = navigator.mozSettings.createLock().set({'lockscreen.enabled': false});
setReq.onsuccess = function() {
    let appsReq = navigator.mozApps.mgmt.getAll();
    appsReq.onsuccess = function() {
        let apps = appsReq.result;
        for (let i = 0; i < apps.length; i++) {
            let app = apps[i];
            if (app.manifest.name === 'Test Container') {
                app.launch();
                window.addEventListener('apploadtime', function apploadtime(){
                    window.removeEventListener('apploadtime', apploadtime);
                    marionetteScriptFinished(true);
                });
                return;
            }
        }
        marionetteScriptFinished(false);
    }
    appsReq.onerror = function() {
        marionetteScriptFinished(false);
    }
}
setReq.onerror = function() {
    marionetteScriptFinished(false);
}""",
                                                          script_timeout=60000)

            self.assertTrue(result)
            frame = Wait(self.marionette, timeout=10, interval=0.2).until(
                element_present(
                    'css selector',
                    'iframe[src*="app://test-container.gaiamobile.org/index.html"]'
                ))

        self.marionette.switch_to_frame(frame)
Esempio n. 12
0
    def test_find_anonymous_element_by_attribute(self):
        el = Wait(self.marionette).until(element_present("id", "dia"))
        self.assertEquals(
            HTMLElement,
            type(el.find_element("anon attribute", {"anonid": "buttons"})))
        self.assertEquals(
            1, len(el.find_elements("anon attribute", {"anonid": "buttons"})))

        with self.assertRaises(NoSuchElementException):
            el.find_element("anon attribute", {"anonid": "nonexistent"})
        self.assertEquals([],
                          el.find_elements("anon attribute",
                                           {"anonid": "nonexistent"}))
Esempio n. 13
0
    def test_should_submit_a_form_when_any_input_element_within_that_form_is_submitted(
            self):
        test_html = self.marionette.absolute_url("formPage.html")
        self.marionette.navigate(test_html)
        self.marionette.find_element(By.ID, "checky").submit()

        for x in xrange(1, 10):
            try:
                self.marionette.find_element(By.ID, "checky")
                time.sleep(1)
            except NoSuchElementException:
                break

        Wait(self.marionette, ignored_exceptions=NoSuchElementException).until(
            lambda m: m.find_element(By.ID, 'email'))
        self.assertEqual(self.marionette.title, "We Arrive Here")
Esempio n. 14
0
    def close_test_container(self):
        self.marionette.set_context(self.marionette.CONTEXT_CONTENT)

        result = self.marionette.execute_async_script("""
if((navigator.mozSettings == undefined) || (navigator.mozSettings == null) || (navigator.mozApps == undefined) || (navigator.mozApps == null)) {
    marionetteScriptFinished(false);
    return;
}
let setReq = navigator.mozSettings.createLock().set({'lockscreen.enabled': false});
setReq.onsuccess = function() {
    let appsReq = navigator.mozApps.mgmt.getAll();
    appsReq.onsuccess = function() {
        let apps = appsReq.result;
        for (let i = 0; i < apps.length; i++) {
            let app = apps[i];
            if (app.manifest.name === 'Test Container') {
                let manager = window.wrappedJSObject.appWindowManager || window.wrappedJSObject.AppWindowManager;
                if (!manager) {
                    marionetteScriptFinished(false);
                    return;
                }
                manager.kill(app.origin);
                marionetteScriptFinished(true);
                return;
            }
        }
        marionetteScriptFinished(false);
    }
    appsReq.onerror = function() {
        marionetteScriptFinished(false);
    }
}
setReq.onerror = function() {
    marionetteScriptFinished(false);
}""",
                                                      script_timeout=60000)

        if not result:
            raise Exception('Failed to close Test Container app')

        Wait(self.marionette, timeout=10, interval=0.2).until(
            element_not_present(
                'css selector',
                'iframe[src*="app://test-container.gaiamobile.org/index.html"]'
            ))
Esempio n. 15
0
    def test_should_be_able_to_submit_forms(self):
        test_html = self.marionette.absolute_url("formPage.html")
        self.marionette.navigate(test_html)
        self.marionette.find_element(By.NAME, "login").submit()
        for x in xrange(1, 10):
            try:
                self.marionette.find_element(By.NAME, "login")
                time.sleep(1)
            except NoSuchElementException:
                break

        Wait(self.marionette, timeout=10, ignored_exceptions=NoSuchElementException)\
            .until(lambda m: m.find_element(By.ID, 'email'))
        title = self.marionette.title
        count = 0
        while self.marionette.title == '' and count <= 10:
            time.sleep(1)
            title = self.marionette.title
            count = count + 1
            if title != '':
                break
        self.assertEqual(title, "We Arrive Here")
Esempio n. 16
0
class WaitUntilTest(MarionetteTestCase):
    def setUp(self):
        super(WaitUntilTest, self).setUp()

        self.m = MockMarionette()
        self.clock = TickingClock()
        self.w = Wait(self.m, timeout=10, interval=1, clock=self.clock)

    def test_true(self):
        r = self.w.until(lambda x: x.true())
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_true_within_timeout(self):
        r = self.w.until(lambda x: x.true(wait=5))
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 4)

    def test_timeout(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.true(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_exception_raises_immediately(self):
        with self.assertRaises(Exception):
            self.w.until(lambda x: x.exception())
        self.assertEqual(self.clock.ticks, 0)

    def test_custom_ignored_exception(self):
        self.w.exceptions = self.w.exceptions + (Exception,)
        with self.assertRaises(Exception):
            self.w.until(lambda x: x.exception(e=Exception))

    def test_ignored_exception_after_timeout_is_not_raised(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.exception(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_keyboard_interrupt(self):
        with self.assertRaises(KeyboardInterrupt):
            self.w.until(lambda x: x.exception(e=KeyboardInterrupt))

    def test_system_exit(self):
        with self.assertRaises(SystemExit):
            self.w.until(lambda x: x.exception(SystemExit))

    def test_true_condition_returns_immediately(self):
        r = self.w.until(lambda x: x.true())
        self.assertIsInstance(r, bool)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_value(self):
        r = self.w.until(lambda x: "foo")
        self.assertEqual(r, "foo")
        self.assertEqual(self.clock.ticks, 0)

    def test_custom_predicate(self):
        r = self.w.until(lambda x: x.true(wait=2), is_true=at_third_attempt)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 1)

    def test_custom_predicate_times_out(self):
        with self.assertRaises(errors.TimeoutException):
            self.w.until(lambda x: x.true(wait=4), is_true=at_third_attempt)

        self.assertEqual(self.clock.ticks, 2)
Esempio n. 17
0
    def setUp(self):
        super(WaitUntilTest, self).setUp()

        self.m = MockMarionette()
        self.clock = TickingClock()
        self.w = Wait(self.m, timeout=10, interval=1, clock=self.clock)
Esempio n. 18
0
class WaitUntilTest(MarionetteTestCase):
    def setUp(self):
        super(WaitUntilTest, self).setUp()

        self.m = MockMarionette()
        self.clock = TickingClock()
        self.w = Wait(self.m, timeout=10, interval=1, clock=self.clock)

    def test_true(self):
        r = self.w.until(lambda x: x.true())
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_true_within_timeout(self):
        r = self.w.until(lambda x: x.true(wait=5))
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 4)

    def test_timeout(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.true(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_exception_raises_immediately(self):
        with self.assertRaises(TypeError):
            self.w.until(lambda x: x.exception(e=TypeError))
        self.assertEqual(self.clock.ticks, 0)

    def test_ignored_exception(self):
        self.w.exceptions = (TypeError,)
        with self.assertRaises(errors.TimeoutException):
            self.w.until(lambda x: x.exception(e=TypeError))

    def test_ignored_exception_wrapped_in_timeoutexception(self):
        self.w.exceptions = (TypeError,)

        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError))
        except Exception as e:
            exc = e

        s = str(exc)
        self.assertIsNotNone(exc)
        self.assertIsInstance(exc, errors.TimeoutException)
        self.assertIn(", caused by %r" % TypeError, s)
        self.assertIn("self.w.until(lambda x: x.exception(e=TypeError))", s)

    def test_ignored_exception_after_timeout_is_not_raised(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.exception(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_keyboard_interrupt(self):
        with self.assertRaises(KeyboardInterrupt):
            self.w.until(lambda x: x.exception(e=KeyboardInterrupt))

    def test_system_exit(self):
        with self.assertRaises(SystemExit):
            self.w.until(lambda x: x.exception(SystemExit))

    def test_true_condition_returns_immediately(self):
        r = self.w.until(lambda x: x.true())
        self.assertIsInstance(r, bool)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_value(self):
        r = self.w.until(lambda x: "foo")
        self.assertEqual(r, "foo")
        self.assertEqual(self.clock.ticks, 0)

    def test_custom_predicate(self):
        r = self.w.until(lambda x: x.true(wait=2), is_true=at_third_attempt)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 1)

    def test_custom_predicate_times_out(self):
        with self.assertRaises(errors.TimeoutException):
            self.w.until(lambda x: x.true(wait=4), is_true=at_third_attempt)

        self.assertEqual(self.clock.ticks, 2)

    def test_timeout_elapsed_duration(self):
        with self.assertRaisesRegexp(errors.TimeoutException,
                                     "Timed out after 2 seconds"):
            self.w.until(lambda x: x.true(wait=4), is_true=at_third_attempt)

    def test_message(self):
        self.w.exceptions = (TypeError,)
        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError), message="hooba")
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertIn("seconds with message: hooba, caused by", result)

    def test_no_message(self):
        self.w.exceptions = (TypeError,)
        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError), message="")
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertIn("seconds, caused by", result)

    def test_message_has_none_as_its_value(self):
        self.w.exceptions = (TypeError,)
        exc = None
        try:
            self.w.until(False, None, None)
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertNotIn("with message:", result)
        self.assertNotIn("secondsNone", result)
Esempio n. 19
0
def main():
    # ----- load inputs ----- #
    with open('inputs.json') as f:
        inputs = json.load(f)

    # ----- load single geometry ----- #
    geometry_geojson = inputs['geometry_geojson']
    with open(geometry_geojson) as f:
        extent = geojson.load(f)

    # ----- authentication ----- #
    print('authentication - get JWT')
    username = inputs['username']
    password = inputs['password']
    authorize = Authentication(username, password)
    headers = authorize.get_headers()

    # ----- search imagery with rangar ----- #
    print('search imagery (ragnar)')
    startDatetime = inputs['startDatetime']
    endDatetime = inputs['endDatetime']
    search_ragnar = SearchImagery(headers, extent, startDatetime, endDatetime)
    search_ragnar.init_image()
    resolve_pipeline = Wait(headers, search_ragnar.pipelineId, timeout=100)
    sceneIds = search_ragnar.ret_image()
    sceneIds = sceneIds[:min(len(sceneIds), inputs['max_pictures'])]

    n_cars_all = []
    images_all = []
    date_times = []
    i = 1
    for sceneId in sceneIds:
        # ----- get imagery with rangar ----- #
        print('-----------------------------------')
        print('Process scene no. ' + str(i))
        print('-----------------------------------')
        print('get imagery (ragnar)')
        get_ragnar = GetImagery(headers, extent, sceneId)
        get_ragnar.init_image()
        resolve_pipeline = Wait(headers, get_ragnar.pipelineId,
                                inputs['timeout'])
        if resolve_pipeline.status == 'PROCESSING':
            continue
        url, meta = get_ragnar.ret_image()

        # ----- detect cars with kraken ----- #
        print('detect cars (kraken)')
        map_type = 'cars'
        kraken = Analyses(headers, sceneId, map_type, extent)
        kraken.init_image()
        resolve_pipeline = Wait(headers, kraken.pipelineId, inputs['timeout'])
        if resolve_pipeline.status == 'PROCESSING':
            continue
        map_id, max_zoom, tiles = kraken.ret_image()
        cars = Cars(map_id, tiles)
        n_cars = cars.count_cars()
        mask_cars = cars.combine_tiles()

        # ----- analyze scene with kraken ----- #
        print('analyze imagery (kraken)')
        map_type = 'imagery'
        kraken = Analyses(headers, sceneId, map_type, extent)
        kraken.init_image()
        resolve_pipeline = Wait(headers, kraken.pipelineId, inputs['timeout'])
        if resolve_pipeline.status == 'PROCESSING':
            continue
        map_id, zoom, tiles = kraken.ret_image()
        background = TrueImage(map_id, tiles)
        true_image = background.combine_tiles()
        combined_picture = combine_pictures(mask_cars, true_image)
        n_cars_all.append(n_cars)
        images_all.append(combined_picture)
        date_times.append(meta['datetime'])
        i += 1

    for image, date_time, n_cars in zip(images_all, date_times, n_cars_all):
        file_name = 'scene_' + date_time
        im = Image.fromarray(image)
        im.save("{}.png".format(file_name))
        plt.imshow(image)
        plt.show()
        print('Number of cars on ' + date_time + ': ' + str(n_cars))
Esempio n. 20
0
 def test_duplicate_exceptions(self):
     w = Wait(self.m, ignored_exceptions=[Exception, Exception])
     self.assertIn(Exception, w.exceptions)
     self.assertEqual(len(w.exceptions), 1)
Esempio n. 21
0
 def test_timeout_elapsed_rounding(self):
     wt = Wait(self.m, clock=SequenceClock([1, 0.01, 1]), timeout=0)
     with self.assertRaisesRegexp(errors.TimeoutException,
                                  "Timed out after 1.0 seconds"):
         wt.until(lambda x: x.true(), is_true=now)
Esempio n. 22
0
    def setUp(self):
        super(WaitUntilTest, self).setUp()

        self.m = MockMarionette()
        self.clock = TickingClock()
        self.w = Wait(self.m, timeout=10, interval=1, clock=self.clock)
Esempio n. 23
0
 def test_construction_with_custom_exception(self):
     w = Wait(self.m, ignored_exceptions=Exception)
     self.assertIn(Exception, w.exceptions)
     self.assertEqual(len(w.exceptions), 1)
Esempio n. 24
0
 def wait_for_element_enabled(self, element, timeout=10):
     Wait(self.marionette, timeout) \
         .until(lambda e: element.is_enabled(),
                message="Timed out waiting for element to be enabled")
Esempio n. 25
0
        config = yaml.safe_load(config_file)

    # get the art name from yaml
    file = config["art"]
    feed_ip = config["feed_ip"]
    eat_ip = config["eat_ip"]
    feed_dir = int(config["feed_dir"])

    # put in all of the moves into a database
    sqltrack.create_database()

    logger = configure_logger(get_basepath(), get_hostname())
    # need to set IP by art piece -gary
    motors = initialize_motors(feed_ip=feed_ip, eat_ip=eat_ip, sim=sim)
    if sim == 0:
        waiter = Wait()

    if file in Data.paths.keys():
        ingredients = Data(data_path=Data.paths[file])
    else:
        # Data() uses sea level data by default
        ingredients = Data()

    kitchen = Compute(target_diameter=Compute.diameter_after_half_paper_moved)

    # distribute total_inches_to_move into meals based on how many datapoints we have,
    # and the percentage of their integrals to the total integral of the function.
    # determine how many portions are in a meal based on the total # of movements
    # divided by the # of meals.
    meals = [
        ingredients.percents[i] * kitchen.total_inches_to_move
Esempio n. 26
0
 def test_clock_property(self):
     w = Wait(self.m)
     self.assertIsInstance(w.clock, wait.SystemClock)
Esempio n. 27
0
 def test_marionette_property(self):
     w = Wait(self.m)
     self.assertEqual(w.marionette, self.m)
Esempio n. 28
0
 def test_end_property(self):
     w = Wait(self.m)
     self.assertIsNotNone(w.end)
Esempio n. 29
0
 def test_construction_with_custom_timeout(self):
     w = Wait(self.m, timeout=42)
     self.assertEqual(w.timeout, 42)
Esempio n. 30
0
 def test_construction_with_custom_interval(self):
     w = Wait(self.m, interval=42)
     self.assertEqual(w.interval, 42)
Esempio n. 31
0
 def wait_for_subelement_displayed(self, parent, by, locator, timeout=None):
     Wait(self.marionette, timeout,
          ignored_exceptions=[NoSuchElementException, StaleElementException])\
         .until(lambda m: parent.find_element(by, locator).is_displayed())
     return parent.find_element(by, locator)
Esempio n. 32
0
 def test_construction_with_custom_exception_tuple(self):
     exc = (Exception, ValueError)
     w = Wait(self.m, ignored_exceptions=exc)
     for e in exc:
         self.assertIn(e, w.exceptions)
     self.assertEqual(len(w.exceptions), len(exc))
Esempio n. 33
0
 def test_timeout_inherited_from_marionette(self):
     w = Wait(self.m)
     self.assertEqual(w.timeout * 1000.0, self.m.timeout)
Esempio n. 34
0
class WaitUntilTest(MarionetteTestCase):
    def setUp(self):
        super(WaitUntilTest, self).setUp()

        self.m = MockMarionette()
        self.clock = TickingClock()
        self.w = Wait(self.m, timeout=10, interval=1, clock=self.clock)

    def test_true(self):
        r = self.w.until(lambda x: x.true())
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_true_within_timeout(self):
        r = self.w.until(lambda x: x.true(wait=5))
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 4)

    def test_timeout(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.true(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_exception_raises_immediately(self):
        with self.assertRaises(TypeError):
            self.w.until(lambda x: x.exception(e=TypeError))
        self.assertEqual(self.clock.ticks, 0)

    def test_ignored_exception(self):
        self.w.exceptions = (TypeError, )
        with self.assertRaises(errors.TimeoutException):
            self.w.until(lambda x: x.exception(e=TypeError))

    def test_ignored_exception_wrapped_in_timeoutexception(self):
        self.w.exceptions = (TypeError, )

        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError))
        except Exception as e:
            exc = e

        s = str(exc)
        self.assertIsNotNone(exc)
        self.assertIsInstance(exc, errors.TimeoutException)
        self.assertIn(", caused by %r" % TypeError, s)
        self.assertIn("self.w.until(lambda x: x.exception(e=TypeError))", s)

    def test_ignored_exception_after_timeout_is_not_raised(self):
        with self.assertRaises(errors.TimeoutException):
            r = self.w.until(lambda x: x.exception(wait=15))
        self.assertEqual(self.clock.ticks, 10)

    def test_keyboard_interrupt(self):
        with self.assertRaises(KeyboardInterrupt):
            self.w.until(lambda x: x.exception(e=KeyboardInterrupt))

    def test_system_exit(self):
        with self.assertRaises(SystemExit):
            self.w.until(lambda x: x.exception(SystemExit))

    def test_true_condition_returns_immediately(self):
        r = self.w.until(lambda x: x.true())
        self.assertIsInstance(r, bool)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 0)

    def test_value(self):
        r = self.w.until(lambda x: "foo")
        self.assertEqual(r, "foo")
        self.assertEqual(self.clock.ticks, 0)

    def test_custom_predicate(self):
        r = self.w.until(lambda x: x.true(wait=2), is_true=at_third_attempt)
        self.assertTrue(r)
        self.assertEqual(self.clock.ticks, 1)

    def test_custom_predicate_times_out(self):
        with self.assertRaises(errors.TimeoutException):
            self.w.until(lambda x: x.true(wait=4), is_true=at_third_attempt)

        self.assertEqual(self.clock.ticks, 2)

    def test_timeout_elapsed_duration(self):
        with self.assertRaisesRegexp(errors.TimeoutException,
                                     "Timed out after 2 seconds"):
            self.w.until(lambda x: x.true(wait=4), is_true=at_third_attempt)

    def test_message(self):
        self.w.exceptions = (TypeError, )
        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError), message="hooba")
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertIn("seconds with message: hooba, caused by", result)

    def test_no_message(self):
        self.w.exceptions = (TypeError, )
        exc = None
        try:
            self.w.until(lambda x: x.exception(e=TypeError), message="")
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertIn("seconds, caused by", result)

    def test_message_has_none_as_its_value(self):
        self.w.exceptions = (TypeError, )
        exc = None
        try:
            self.w.until(False, None, None)
        except errors.TimeoutException as e:
            exc = e

        result = str(exc)
        self.assertNotIn("with message:", result)
        self.assertNotIn("secondsNone", result)
Esempio n. 35
0
 def wait_for_element_exists(self, by, locator, timeout=None):
     Wait(self.marionette, timeout,
          ignored_exceptions=[NoSuchElementException, StaleElementException]) \
         .until(lambda m: m.find_element(by, locator))
     return self.marionette.find_element(by, locator)
Esempio n. 36
0
 def test_timeout_uses_default_if_marionette_timeout_is_none(self):
     self.m.timeout = None
     w = Wait(self.m)
     self.assertEqual(w.timeout, wait.DEFAULT_TIMEOUT)