예제 #1
0
    def get_style(
        self,
        selector: str,
        key: str = "ALL",
        assertion_operator: Optional[AssertionOperator] = None,
        assertion_expected: Any = None,
    ):
        """Gets the computed style properties of the element selected by ``selector``

            With any other value than "ALL" will try to get CSS property with key ``key``

            Optionally matches with any sequence assertion operator.
        """
        with self.playwright.grpc_channel() as stub:
            response = stub.GetStyle(
                Request().ElementSelector(selector=selector))
            parsed = json.loads(response.body)

            if key == "ALL":
                return dict_verify_assertion(parsed, assertion_operator,
                                             assertion_expected,
                                             "Computed style is")
            else:
                item = parsed.get(key, "NOT_FOUND")
                logger.info(f"Value of key: {key}")
                logger.info(f"Value of selected property: {item}")
                return verify_assertion(
                    item,
                    assertion_operator,
                    assertion_expected,
                    f"Style value for {key} is ",
                )
예제 #2
0
    def get_checkbox_state(
        self,
        selector: str,
        assertion_operator: Optional[AssertionOperator] = None,
        expected_state: str = "Unchecked",
    ):
        """Returns the state of the checkbox found by ``selector``.

        - ``checked`` => ``True``
        - ``unchecked`` => ``False``

        Optionally asserts that the state matches the specified assertion.

        ``assertion_operator`` see `Assertions`.

        - ``==`` and ``!=`` are allowed on boolean values
        - other operators are not accepted.

        ``expected_state``: boolean value of expected state.
        Strings are interpreted as booleans.
        All strings are ``${True}`` except of the
        following `FALSE, NO, OFF, 0, UNCHECKED, NONE, ${EMPTY}``.
        (case-insensitive).
        """
        with self.playwright.grpc_channel() as stub:
            response = stub.GetBoolProperty(Request().ElementProperty(
                selector=selector, property="checked"))
            logger.info(
                f"Checkbox is {'checked' if response.log else 'unchecked'}")
            value: bool = response.body

            return bool_verify_assertion(value, assertion_operator,
                                         expected_state,
                                         f"Checkbox {selector} is")
예제 #3
0
    def get_selected_options(
        self,
        selector: str,
        option_attribute: SelectAttribute = SelectAttribute.label,
        assertion_operator: Optional[AssertionOperator] = None,
        *assertion_expected,
    ):
        """Returns the specified attribute of selected options of the ``select`` element.

        Optionally asserts that these match the specified assertion.

        ``option_attribute``: which attribute shall be returned/verified.
        Allowed values are ``<"value"|"label"|"text"|"index">``

        ``assertion_operator`` see `Assertions`.

        - ``==`` and ``!=`` can work with multiple values
        - ``contains``/``*=`` only accepts one single expected value

        Other operators are not allowed.

        Example:

        | `Select Options By`    | label                 | //select[2] | Email | Mobile | | |
        | ${selected_list}     | `Get Selected Options`  | //select[2] | | | | # getter |
        | `Get Selected Options` | //select[2] | label | == | Mobile | Mail | #assertion content |
        | `Select Options By`    | label                 | select#names | 2 | 4 | |
        | `Get Selected Options` | select#names | index | == | 2      | 4     | #assertion index  |
        | `Get Selected Options` | select#names | label | *= | Mikko  |     | #assertion contains |
        | `Get Selected Options` | select#names | label | validate | len(value) == 3  | | #assertion length |

        """
        with self.playwright.grpc_channel() as stub:
            response = stub.GetSelectContent(
                Request().ElementSelector(selector=selector))
            logger.info(response)
            expected = list(assertion_expected)
            selected: Union[List[int], List[str]]
            if option_attribute is SelectAttribute.value:
                selected = [
                    sel.value for sel in response.entry if sel.selected
                ]
            elif option_attribute is SelectAttribute.label:
                selected = [
                    sel.label for sel in response.entry if sel.selected
                ]
            elif option_attribute is SelectAttribute.index:
                selected = [
                    index for index, sel in enumerate(response.entry)
                    if sel.selected
                ]
                expected = [int(exp) for exp in expected]

            return list_verify_assertion(
                selected,
                assertion_operator,
                expected,
                "Selected Options:",
            )
예제 #4
0
    def close(self):
        logger.debug(
            "Closing all open browsers, contexts and pages in Playwright")
        with self.grpc_channel() as stub:
            response = stub.CloseAllBrowsers(Request().Empty())
            logger.info(response.log)

        logger.debug("Closing Playwright process")
        self._playwright_process.kill()
        logger.debug("Playwright process killed")
예제 #5
0
 def wait_until_server_up(self):
     for i in range(50):
         with grpc.insecure_channel(f"localhost:{self.port}") as channel:
             try:
                 stub = playwright_pb2_grpc.PlaywrightStub(channel)
                 response = stub.Health(Request().Empty())
                 logger.info(
                     f"Connected to the playwright process at port {self.port}: {response}"
                 )
                 return
             except grpc.RpcError as err:
                 logger.info(err)
                 time.sleep(0.1)
     raise RuntimeError(
         f"Could not connect to the playwright process at port {self.port}")
예제 #6
0
    def get_browser_catalog(self):
        """ Returns all Browsers, open Contexts in them and open Pages in these contexts.

            The data is parsed into a python list containing data representing the open Objects.

            On the root level the data contains a list of open Browsers.

            `` Browser: { type: Literal['chromium', 'firefox', 'webkit'], 'id': int, contexts: List[Context]}``
            `` Context: {type: 'context', 'id': int, pages: List[Page]} ``
            `` Page: {type: 'page', 'id': int, title: str, url: str} ``

            Sample: ``
            [{
                "type": "firefox",
                "id": 0,
                "contexts": [{
                    "type": "context",
                    "id": 0,
                    "pages": [{
                        "type": "page",
                        "title": "prefilled_email_form.html",
                        "url": "http://localhost:7272/prefilled_email_form.html",
                        "id": "0"
                    }]
                }, {
                    "type": "context",
                    "id": 1,
                    "pages": [{
                        "type": "page",
                        "title": "Login Page",
                        "url": "http://localhost:7272/dist/",
                        "id": "0"
                    }]
                }]
            }]

        """
        with self.playwright.grpc_channel() as stub:
            response = stub.GetBrowserCatalog(Request().Empty())
            parsed = json.loads(response.body)
            logger.info(json.dumps(parsed))
            return parsed
예제 #7
0
 def start_playwright(self):
     workdir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            "wrapper")
     playwright_script = os.path.join(workdir, "index.js")
     logfile = open(os.path.join(self.outputdir, "playwright-log.txt"), "w")
     port = str(self.find_free_port())
     env = dict(os.environ)
     env["PORT"] = port
     env["TIMEOUT"] = str(timestr_to_millisecs(self.timeout))
     if self.enable_playwright_debug:
         env["DEBUG"] = "pw:api"
     logger.info(
         f"Starting Browser process {playwright_script} using port {port}")
     self.port = port
     return Popen(
         ["node", playwright_script],
         shell=False,
         cwd=workdir,
         env=env,
         stdout=logfile,
         stderr=STDOUT,
     )