Example #1
0
    def _do_switch_to_frame(self, target_frame):
        # type: (EyesWebElement) -> None
        """
        Will be called when switching into a frame.

        :param target_frame: The element to be switched to.
        """
        argument_guard.not_none(target_frame)

        size_and_borders = target_frame.size_and_borders
        borders = size_and_borders.borders
        frame_inner_size = size_and_borders.size
        bounds = target_frame.bounding_client_rect

        content_location = Point(
            bounds["x"] + borders["left"], bounds["y"] + borders["top"]
        )
        outer_size = RectangleSize.from_(target_frame.size)
        inner_size = RectangleSize.from_(frame_inner_size)
        original_location = target_frame.scroll_location

        self._switch_to.frame(target_frame.element)

        scroll_root_element = self._driver.find_element_by_xpath("/*")
        frame = Frame(
            reference=target_frame,
            location=content_location,
            outer_size=outer_size,
            inner_size=inner_size,
            parent_scroll_position=original_location,
            scroll_root_element=scroll_root_element,
        )
        self._driver.frame_chain.push(frame)
Example #2
0
def test_rectangle_size_equality():
    a = RectangleSize(800, 600)
    b = RectangleSize(800, 600)
    c = RectangleSize(200, 200)

    assert a == b
    assert not a == c
Example #3
0
def test_rectangle_size_inequality():
    a = RectangleSize(800, 600)
    b = RectangleSize(800, 600)
    c = RectangleSize(200, 200)

    assert a != c
    assert not a != b
def test_default_rendering_of_multiple_targets(driver, vg_runner):
    driver.get("https://applitools.com/helloworld")
    eyes = Eyes(vg_runner)
    eyes.configuration.add_browser(800, 600, BrowserType.CHROME)
    eyes.configuration.add_browser(800, 600, BrowserType.FIREFOX)
    eyes.configuration.add_browser(1200, 800, BrowserType.CHROME)
    eyes.configuration.add_browser(1200, 800, BrowserType.FIREFOX)
    eyes.configuration.app_name = "TestDefaultRendering"
    eyes.configuration.test_name = "TestDefaultRenderingOfMultipleTargets"
    eyes.configuration.viewport_size = RectangleSize(800, 600)

    try:
        eyes.open(driver)
        eyes.check("", Target.window())
        eyes.close()
    finally:
        eyes.abort()

    all_test_results = vg_runner.get_all_test_results()
    batch_id = None
    batch_name = None
    for trc in all_test_results:
        if batch_id is None:
            batch_id = trc.test_results.batch_id
        if batch_name is None:
            batch_name = trc.test_results.batch_name

        assert batch_id == trc.test_results.batch_id
        assert batch_name == trc.test_results.batch_name
    def _entire_element_screenshot(self, scale_provider):
        # type: (ScaleProvider) -> EyesWebDriverScreenshot
        logger.info("Entire element screenshot requested")

        elem_position_provider = self._element_position_provider
        if elem_position_provider is None:
            scroll_root_element = self.driver.find_element_by_tag_name("html")
            elem_position_provider = self._element_position_provider_from(
                scroll_root_element)

        # TODO: Should be moved in proper place???
        if self.driver.frame_chain:
            if (self._user_agent.browser == BrowserNames.Firefox
                    and self._user_agent.browser_major_version < 60
                ) or self._user_agent.browser in (
                    BrowserNames.Chrome,
                    BrowserNames.HeadlessChrome,
                    BrowserNames.Safari,
                    BrowserNames.Edge,
                    BrowserNames.IE,
                ):
                self._region_to_check.left += int(
                    self._driver.frame_chain.peek.location.x)
        algo = self._create_full_page_capture_algorithm(scale_provider)

        image = algo.get_stitched_region(self._region_to_check, None,
                                         elem_position_provider)
        return EyesWebDriverScreenshot.create_entire_frame(
            self._driver, image, RectangleSize.from_(image))
Example #6
0
    def _check_image(self, region_provider, name, ignore_mismatch,
                     check_settings):
        # type: (RegionProvider, Text, bool, ImagesCheckSettings) -> bool
        # Set the title to be linked to the screenshot.
        self._raw_title = name if name else ""

        if not self._is_opened:
            self.abort()
            raise EyesError("you must call open() before checking")

        image = check_settings.values.image  # type: Image.Image

        if not isinstance(self.cut_provider, NullCutProvider):
            logger.debug("cutting...")
            image = self.cut_provider.cut(image)
            self.debug_screenshot_provider.save(image, "cut")

        self._screenshot = EyesImagesScreenshot(image)
        if not self.configure.viewport_size:
            self._set_viewport_size(
                RectangleSize(width=image.width, height=image.height))

        check_settings = check_settings.timeout(0)
        match_result = self._check_window_base(region_provider,
                                               self._raw_title,
                                               ignore_mismatch, check_settings)
        self._screenshot = None
        self._raw_title = None
        return match_result.as_expected
Example #7
0
    def _set_viewport_size(self, size):
        """
        Use this method only if you made a previous call to `open`.
        """
        # if self.viewport_size:
        #     logger.info("Ignored (viewport size given explicitly)")
        #     return None

        if not self.driver.is_mobile_platform:
            original_frame = self.driver.frame_chain.clone()
            self.driver.switch_to.default_content()

            try:
                self.set_viewport_size(self._driver, size)
                self._effective_viewport = Region(
                    0,
                    0,
                    width=size["width"],
                    height=size["height"],
                    coordinates_type=CoordinatesType.SCREENSHOT_AS_IS,
                )
            finally:
                # Just in case the user catches this error
                self.driver.switch_to.frames(original_frame)
        self.configure.viewport_size = RectangleSize(size["width"],
                                                     size["height"])
def test_test_results_deserialization():
    tr = json_utils.attr_from_json(get_resource("unit/testResultsData.json"),
                                   TestResults)  # type: TestResults
    assert tr.status == TestResultsStatus.Passed
    assert (
        tr.app_urls.batch ==
        "https://eyes.applitools.com/app/test-results/111?accountIdPczBANNug~~"
    )
    assert tr.accessibility_status == SessionAccessibilityStatus(
        AccessibilityStatus.Failed,
        AccessibilityLevel.AA,
        AccessibilityGuidelinesVersion.WCAG_2_0,
    )
    assert tr.host_display_size == RectangleSize(800, 800)
    assert tr.default_match_settings.ignore_regions == [
        Region(300, 300, 300, 300)
    ]
    assert tr.default_match_settings.accessibility == [
        AccessibilityRegion(300, 300, 300, 300,
                            AccessibilityRegionType.BoldText)
    ]
    assert tr.steps_info[0].name == "Login Window"
    assert (
        tr.steps_info[0].app_urls.step ==
        "https://eyes.applitools.com/app/test-results/00000215/steps/1?accountId=~"
    )
Example #9
0
def get_viewport_size_or_display_size(driver):
    logger.debug("get_viewport_size_or_display_size()")

    if not is_mobile_app(driver):
        try:
            return get_viewport_size(driver)
        except Exception as e:
            logger.warning(
                "Failed to extract viewport size using Javascript: {}".format(
                    str(e)))
    # If we failed to extract the viewport size using JS, will use the
    # window size instead.

    logger.debug("Using window size as viewport size.")
    window_size = get_window_size(driver)
    width = window_size["width"]
    height = window_size["height"]
    try:
        if is_landscape_orientation(driver) and height > width:
            height, width = width, height
    except WebDriverException:
        # Not every WebDriver supports querying for orientation.
        pass
    logger.debug("Done! Size {:d} x {:d}".format(width, height))
    return RectangleSize(width=width, height=height)
def test_abort_eyes(vg_runner, driver):
    eyes = Eyes(vg_runner)
    eyes.configuration.add_browser(800, 600, BrowserType.CHROME)
    eyes.configuration.viewport_size = RectangleSize(800, 600)
    driver.get("https://demo.applitools.com")
    eyes.open(driver, "Python | VisualGrid", "TestAbortVGEyes")
    eyes.check_window()
    eyes.abort()
Example #11
0
def test_timeout(driver, vg_runner, batch_info):
    eyes = Eyes(vg_runner)
    driver.get("https://applitools.com/helloworld")
    eyes.batch = batch_info
    eyes.open(driver, "Timeout Test", "Visual Grid Timeout Test",
              RectangleSize(1200, 800))
    eyes.check("", Target.window().with_name("Test"))
    eyes.close()
    vg_runner.get_all_test_results()
Example #12
0
def parse_viewport_size(text):
    # type: (Text) -> RectangleSize
    num_ptrs = (int_float_pattern, ) * 2
    match = re.match(r"\[(%s) (%s)\]" % num_ptrs, text)
    if match is None:
        raise ValueError(
            "Incorrect value of viewport: {}.\n\t Format should be: [800 700]".
            format(text))
    groups = match.groups()
    return RectangleSize(width=float(groups[0]), height=float(groups[1]))
Example #13
0
def test_VG_tests_count_4(eyes, batch_info, driver):
    config = (Configuration().set_batch(batch_info).set_app_name(
        "Test Count").set_test_name("Test_VGTestsCount_4").set_viewport_size(
            RectangleSize(800, 600)))
    eyes.set_configuration(config)
    eyes.open(driver)
    eyes.check("Test", Target.window())
    eyes.close()
    results_summary = eyes._runner.get_all_test_results()
    assert results_summary.size() == 1
Example #14
0
def get_current_frame_content_entire_size(driver):
    # type: (AnyWebDriver) -> ViewPort
    """
    :return: The size of the entire content.
    """
    try:
        width, height = driver.execute_script(_JS_GET_CONTENT_ENTIRE_SIZE)
    except WebDriverException:
        raise WebDriverException("Failed to extract entire size!")
    return RectangleSize(width, height)
Example #15
0
def get_viewport_size(driver):
    # type: (AnyWebDriver) -> RectangleSize
    """
    Tries to get the viewport size using Javascript. If fails, gets the entire browser window
    size!

    :param driver: The webdriver to use for getting the viewport size.
    """
    width, height = driver.execute_script(_JS_GET_VIEWPORT_SIZE)
    return RectangleSize(width=width, height=height)
def test_get_all_test_results(vg_runner, driver):
    eyes1 = Eyes(vg_runner)
    eyes2 = Eyes(vg_runner)
    eyes1.configuration.add_browser(800, 600, BrowserType.CHROME)
    eyes2.configuration.add_browser(700, 500, BrowserType.FIREFOX)

    driver.get("https://demo.applitools.com")
    eyes1.open(driver, "Python | VisualGrid", "TestClose1",
               RectangleSize(800, 600))
    eyes2.open(driver, "Python | VisualGrid", "TestClose2",
               RectangleSize(700, 500))

    eyes1.check_window()
    eyes2.check_window()

    eyes1.close_async()
    eyes2.close_async()

    results = vg_runner.get_all_test_results(False)
    print(results)
Example #17
0
def test_get_all_tests_results_timeout(driver, vg_runner, batch_info):
    eyes = Eyes(vg_runner)
    eyes.configure.test_name = "GetAllTestsResultsTimeout"
    eyes.configure.app_name = "Visual Grid Render Test"
    eyes.configure.batch = batch_info
    eyes.configure.viewport_size = RectangleSize(1024, 768)
    driver.get("https://demo.applitools.com")
    eyes.open(driver)
    eyes.check_window()
    eyes.close_async()
    with pytest.raises(EyesError):
        vg_runner.get_all_test_results(False, 0.001)
Example #18
0
 def _get_entire_size(self, image, position_provider):
     # type: (Image, PositionProvider) -> RectangleSize
     try:
         entire_size = position_provider.get_entire_size()
         logger.info(
             "Entire size of region context: {}".format(entire_size))
     except WebDriverException as e:
         logger.warning(
             "Failed to extract entire size of region context {}".format(e))
         logger.debug("Using image size instead: {} x {}".format(
             image.width, image.height))
         entire_size = RectangleSize(image.width, image.height)
     return entire_size
    def get_image(self):
        image = TakesScreenshotImageProvider(self._eyes).get_image()

        if self._eyes.is_cut_provider_explicitly_set:
            return image

        logger.info("physical device pixel size",
                    width=image.width,
                    height=image.height)

        viewport_location = device_viewport_location(self._eyes.driver)
        if viewport_location:
            original_viewport_size = self._eyes._get_viewport_size()
            viewport_size = original_viewport_size.scale(
                self._eyes.device_pixel_ratio)
            crop_region = Region(
                viewport_location.x,
                viewport_location.y,
                viewport_size.width,
                viewport_size.height,
            )
            logger.info("calculated viewport region",
                        viewport_region=crop_region)
            image = image_utils.crop_image(image, crop_region)
        else:
            if self._devices_regions is None:
                self.init_device_regions_table()
            original_viewport_size = RectangleSize.from_(
                self._eyes.scroll_root_element.size_and_borders.size)
            device_data = DeviceData(
                image.width,
                image.height,
                original_viewport_size.width,
                original_viewport_size.height,
            )
            if device_data in self._devices_regions:
                logger.debug("device model found in hash table")
                crop_by_version = self._devices_regions.get(device_data)
                if (crop_by_version.major_version <=
                        self._useragent.browser_major_version):
                    image = image_utils.crop_image(image,
                                                   crop_by_version.region)
                else:
                    logger.debug(
                        "device version not found in list. returning original image."
                    )
            else:
                logger.debug(
                    "device not found in list. returning original image.")

        return image
Example #20
0
    def check(self, name, check_settings):
        # type: (Text, ImagesCheckSettings) -> bool
        if self.configure.is_disabled:
            return False
        if name:
            check_settings = check_settings.with_name(name)
        else:
            name = check_settings.values.name

        image = check_settings.values.image
        if self.configure.viewport_size is None:
            self.configure.viewport_size = RectangleSize.from_(image)

        return self._check_image(NULL_REGION_PROVIDER, name, False, check_settings)
Example #21
0
def test_layout_region_calculation_for_targets(driver, fake_connector_class,
                                               target, expected_layout_region):
    eyes = Eyes()
    eyes.send_dom = False
    eyes.server_connector = fake_connector_class()
    driver = eyes.open(driver, "a", "b", RectangleSize(height=1024, width=768))
    driver.get("https://applitools.github.io/demo/TestPages/"
               "SimpleTestPage/modal_scrollable.html")

    eyes.check(target)
    _, match_data = eyes.server_connector.calls["match_window"]

    assert match_data.options.image_match_settings.layout_regions == [
        expected_layout_region
    ]
Example #22
0
def test_layout_region_calculation_for_frame_target(driver,
                                                    fake_connector_class):
    eyes = Eyes()
    eyes.server_connector = fake_connector_class()
    driver = eyes.open(driver, "a", "b", RectangleSize(height=1024, width=768))
    driver.get(
        "https://applitools.github.io/demo/TestPages/CorsTestPage/index.html")

    eyes.check(
        Target.frame([By.CSS_SELECTOR,
                      "body>iframe"]).layout([By.ID, "inner-frame-div"]))
    _, match_data = eyes.server_connector.calls["match_window"]

    assert match_data.options.image_match_settings.layout_regions == [
        Region(8, 8, 304, 184)
    ]
Example #23
0
    def check(self, check_settings, name=None):
        if self.configure.is_disabled:
            return False
        if isinstance(name, ImagesCheckSettings) or isinstance(
                check_settings, basestring):
            check_settings, name = name, check_settings
        if name:
            check_settings = check_settings.with_name(name)

        image = check_settings.values.image
        if self.configure.viewport_size is None:
            self.configure.viewport_size = RectangleSize.from_(image)

        return self._check_image(NULL_REGION_PROVIDER,
                                 check_settings.values.name, False,
                                 check_settings)
Example #24
0
def get_viewport_size(driver):
    # type: (AnyWebDriver) -> RectangleSize
    """
    Tries to get the viewport size using Javascript. If fails, gets the entire browser window
    size!

    :param driver: The webdriver to use for getting the viewport size.
    """
    # noinspection PyBroadException
    try:
        width, height = driver.execute_script(_JS_GET_VIEWPORT_SIZE)
        return RectangleSize(width=width, height=height)
    except WebDriverException:
        logger.warning(
            "Failed to get viewport size. Only window size is available")
        return get_window_size(driver)
Example #25
0
    def _entire_element_screenshot(self, scale_provider):
        # type: (ScaleProvider) -> EyesWebDriverScreenshot
        logger.info("Entire element screenshot requested")

        elem_position_provider = self._element_position_provider
        if elem_position_provider is None:
            scroll_root_element = self.driver.find_element_by_tag_name("html")
            elem_position_provider = self._element_position_provider_from(
                scroll_root_element)
        algo = self._create_full_page_capture_algorithm(scale_provider)

        image = algo.get_stitched_region(self._region_to_check,
                                         self._full_region_to_check,
                                         elem_position_provider)
        return EyesWebDriverScreenshot.create_entire_frame(
            self._driver, image, RectangleSize.from_(image))
Example #26
0
def test_check_region_with_bad_selector_before_valid_check(driver, vg_runner):
    eyes = Eyes(vg_runner)
    driver.get(
        "https://applitools.github.io/demo/TestPages/VisualGridTestPage/")
    eyes.open(
        driver,
        "Applitools Eyes Python SDK",
        "TestCheckRegionWithBadSelectorBeforeValidCheck_VG",
        viewport_size=RectangleSize(800, 600),
    )
    with pytest.raises(NoSuchElementException):
        eyes.check_region("#element_that_does_not_exist")
        driver.find_element_by_id("centred").click()
        eyes.check_region("#modal-content")

        eyes.close_async()
        vg_runner.get_all_test_results()
Example #27
0
    def open(self, config):
        # type: (Configuration) -> None
        """Starts a new test without setting the viewport size of the AUT."""
        logger.info("opening EyesConnector with viewport size: {}".format(
            self._browser_info.viewport_size))
        self._config = config.clone()
        if self.device:
            self._config.viewport_size = self.device_size
        elif self._browser_info.viewport_size:
            self._config.viewport_size = self._browser_info.viewport_size
        else:
            # this means it's a emulationInfo
            if isinstance(self._browser_info.emulation_info, EmulationDevice):
                emu_device = self._browser_info.emulation_info
                self._config.viewport_size = RectangleSize.from_(emu_device)

        self._config.baseline_env_name = self._browser_info.baseline_env_name
        self._open_base()
    def _set_viewport_size(self):
        viewport_size = self.configure.viewport_size

        if viewport_size is None:
            for render_bi in self.configure.browsers_info:
                if not render_bi.emulation_info:
                    viewport_size = RectangleSize(render_bi.width, render_bi.height)
                    break

        if viewport_size is None:
            viewport_size = self._get_viewport_size()

        self.configure.viewport_size = viewport_size
        try:
            eyes_selenium_utils.set_viewport_size(self.driver, viewport_size)
        except Exception as e:
            logger.exception(e)
            raise EyesError(str(e))
 def _get_image_parts(self, full_area, image):
     # type: (Region, Image) -> List[Region]
     # The screenshot part is a bit smaller than the screenshot size,
     # in order to eliminate duplicate bottom scroll bars, as well as fixed
     # position footers.
     part_image_size = RectangleSize(
         image.width,
         max([
             image.height - self.stitching_overlap,
             self.MIN_SCREENSHOT_PART_HEIGHT
         ]),
     )
     logger.info("entire page region: %s, image part size: %s" %
                 (full_area, part_image_size))
     # Getting the list of sub-regions composing the whole region (we'll take
     # screenshot for each one).
     image_parts = full_area.get_sub_regions(
         part_image_size)  # type: Region
     return image_parts
Example #30
0
def test_check_region_with_bad_ignore_selector(driver, vg_runner):
    eyes = Eyes(vg_runner)
    driver.get(
        "https://applitools.github.io/demo/TestPages/VisualGridTestPage/")
    eyes.open(
        driver,
        "Applitools Eyes Python SDK",
        "TestCheckRegionWithBadIgnoreSelector_VG",
        RectangleSize(800, 600),
    )
    eyes.check(
        "",
        Target.window().ignore("body>p:nth-of-type("
                               "14)").
        before_render_screenshot_hook(
            "var p = document.querySelector('body>p:nth-of-type(14)'); p.parentNode.removeChild(p);"
        ),
    )
    eyes.close()
    vg_runner.get_all_test_results()