diff options
Diffstat (limited to 'testing/web-platform/tests/tools/webdriver')
9 files changed, 1342 insertions, 0 deletions
diff --git a/testing/web-platform/tests/tools/webdriver/.gitignore b/testing/web-platform/tests/tools/webdriver/.gitignore new file mode 100644 index 000000000..c99747ced --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/.gitignore @@ -0,0 +1 @@ +webdriver.egg-info/ diff --git a/testing/web-platform/tests/tools/webdriver/COPYING b/testing/web-platform/tests/tools/webdriver/COPYING new file mode 100644 index 000000000..14e2f777f --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/COPYING @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/testing/web-platform/tests/tools/webdriver/README.md b/testing/web-platform/tests/tools/webdriver/README.md new file mode 100644 index 000000000..194009f8a --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/README.md @@ -0,0 +1,75 @@ +# WebDriver client for Python + +This package provides Python bindings +that conform to the [W3C WebDriver standard](https://w3c.github.io/webdriver/webdriver-spec.html), +which specifies a remote control protocol for web browsers. + +These bindings are written with determining +implementation compliance to the specification in mind, +so that different remote end drivers +can determine whether they meet the recognised standard. +The client is used for the WebDriver specification tests +in the [Web Platform Tests](https://github.com/w3c/web-platform-tests). + +## Installation + +To install the package individually +in your virtualenv or system-wide: + + % python setup.py install + +Since this package does not have any external dependencies, +you can also use the client directly from the checkout directory, +which is useful if you want to contribute patches back: + + % cd /path/to/wdclient + % python + Python 2.7.12+ (default, Aug 4 2016, 20:04:34) + [GCC 6.1.1 20160724] on linux2 + Type "help", "copyright", "credits" or "license" for more information. + >>> import webdriver + >>> + +If you are writing WebDriver specification tests for +[WPT](https://github.com/w3c/web-platform-tests), +there is no need to install the client manually +as it is picked up as a submodule to +[wpt-tools](https://github.com/w3c/wpt-tools) +that is checked out in `./tools`. + +## Usage + +You can use the built-in +[context manager](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) +to manage the lifetime of the session. +The session is started implicitly +at the first call to a command if it has not already been started, +and will implicitly be ended when exiting the context: + +```py +import webdriver + +with webdriver.Session("127.0.0.1", 4444) as session: + session.url = "https://mozilla.org" + print "The current URL is %s" % session.url +``` + +The following is functionally equivalent to the above, +but giving you manual control of the session: + +```py +import webdriver + +session = webdriver.Session("127.0.0.1", 4444) +session.start() + +session.url = "https://mozilla.org" +print "The current URL is %s" % session.url + +session.end() +``` + +## Dependencies + +This client has the benefit of only using standard library dependencies. +No external PyPI dependencies are needed. diff --git a/testing/web-platform/tests/tools/webdriver/setup.py b/testing/web-platform/tests/tools/webdriver/setup.py new file mode 100644 index 000000000..720fcf05c --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/setup.py @@ -0,0 +1,18 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +from setuptools import setup, find_packages + +setup(name="webdriver", + version="1.0", + description="WebDriver client compatible with " + "the W3C browser automation specification.", + author="Mozilla Engineering Productivity", + author_email="tools@lists.mozilla.org", + license="MPL 2.0", + packages=find_packages(), + classifiers=["Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", + "Operating System :: OS Independent"]) diff --git a/testing/web-platform/tests/tools/webdriver/webdriver/__init__.py b/testing/web-platform/tests/tools/webdriver/webdriver/__init__.py new file mode 100644 index 000000000..c827f59f1 --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/webdriver/__init__.py @@ -0,0 +1,31 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +from client import Cookies, Element, Find, Session, Timeouts, Window +from error import ( + ElementNotSelectableException, + ElementNotVisibleException, + InvalidArgumentException, + InvalidCookieDomainException, + InvalidElementCoordinatesException, + InvalidElementStateException, + InvalidSelectorException, + InvalidSessionIdException, + JavascriptErrorException, + MoveTargetOutOfBoundsException, + NoSuchAlertException, + NoSuchElementException, + NoSuchFrameException, + NoSuchWindowException, + ScriptTimeoutException, + SessionNotCreatedException, + StaleElementReferenceException, + TimeoutException, + UnableToSetCookieException, + UnexpectedAlertOpenException, + UnknownCommandException, + UnknownErrorException, + UnknownMethodException, + UnsupportedOperationException, + WebDriverException) diff --git a/testing/web-platform/tests/tools/webdriver/webdriver/client.py b/testing/web-platform/tests/tools/webdriver/webdriver/client.py new file mode 100644 index 000000000..8e1813f25 --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/webdriver/client.py @@ -0,0 +1,595 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import urlparse + +import error +import transport + + +element_key = "element-6066-11e4-a52e-4f735466cecf" + + +def command(func): + def inner(self, *args, **kwargs): + if hasattr(self, "session"): + session = self.session + else: + session = self + + if session.session_id is None: + session.start() + assert session.session_id != None + + return func(self, *args, **kwargs) + + inner.__name__ = func.__name__ + inner.__doc__ = func.__doc__ + + return inner + + +class Timeouts(object): + def __init__(self, session): + self.session = session + self._script = 30 + self._load = 0 + self._implicit_wait = 0 + + def _set_timeouts(self, name, value): + body = {"type": name, + "ms": value * 1000} + return self.session.send_command("POST", "timeouts", body) + + @property + def script(self): + return self._script + + @script.setter + def script(self, value): + self._set_timeouts("script", value) + self._script = value + + @property + def load(self): + return self._load + + @load.setter + def set_load(self, value): + self._set_timeouts("page load", value) + self._script = value + + @property + def implicit_wait(self): + return self._implicit_wait + + @implicit_wait.setter + def implicit_wait(self, value): + self._set_timeouts("implicit wait", value) + self._implicit_wait = value + + +class ActionSequence(object): + """API for creating and performing action sequences. + + Each action method adds one or more actions to a queue. When perform() + is called, the queued actions fire in order. + + May be chained together as in:: + + ActionSequence(session, "key", id) \ + .key_down("a") \ + .key_up("a") \ + .perform() + """ + def __init__(self, session, action_type, input_id, pointer_params=None): + """Represents a sequence of actions of one type for one input source. + + :param session: WebDriver session. + :param action_type: Action type; may be "none", "key", or "pointer". + :param input_id: ID of input source. + :param pointer_params: Optional dictionary of pointer parameters. + """ + self.session = session + self._id = input_id + self._type = action_type + self._actions = [] + self._pointer_params = pointer_params + + @property + def dict(self): + d = { + "type": self._type, + "id": self._id, + "actions": self._actions, + } + if self._pointer_params is not None: + d["parameters"] = self._pointer_params + return d + + @command + def perform(self): + """Perform all queued actions.""" + self.session.actions.perform([self.dict]) + + def _key_action(self, subtype, value): + self._actions.append({"type": subtype, "value": value}) + + def _pointer_action(self, subtype, button): + self._actions.append({"type": subtype, "button": button}) + + def pointer_move(self, x, y, duration=None, origin=None): + """Queue a pointerMove action. + + :param x: Destination x-axis coordinate of pointer in CSS pixels. + :param y: Destination y-axis coordinate of pointer in CSS pixels. + :param duration: Number of milliseconds over which to distribute the + move. If None, remote end defaults to 0. + :param origin: Origin of coordinates, either "viewport", "pointer" or + an Element. If None, remote end defaults to "viewport". + """ + # TODO change to pointerMove once geckodriver > 0.14 is available on mozilla-central + action = { + "type": "move", + "x": x, + "y": y + } + if duration is not None: + action["duration"] = duration + if origin is not None: + action["origin"] = origin if isinstance(origin, basestring) else origin.json() + self._actions.append(action) + return self + + def pointer_up(self, button): + """Queue a pointerUp action for `button`. + + :param button: Pointer button to perform action with. + """ + self._pointer_action("pointerUp", button) + return self + + def pointer_down(self, button): + """Queue a pointerDown action for `button`. + + :param button: Pointer button to perform action with. + """ + self._pointer_action("pointerDown", button) + return self + + def key_up(self, value): + """Queue a keyUp action for `value`. + + :param value: Character to perform key action with. + """ + self._key_action("keyUp", value) + return self + + def key_down(self, value): + """Queue a keyDown action for `value`. + + :param value: Character to perform key action with. + """ + self._key_action("keyDown", value) + return self + + def send_keys(self, keys): + """Queue a keyDown and keyUp action for each character in `keys`. + + :param keys: String of keys to perform key actions with. + """ + for c in keys: + self.key_down(c) + self.key_up(c) + return self + + +class Actions(object): + def __init__(self, session): + self.session = session + + @command + def perform(self, actions=None): + """Performs actions by tick from each action sequence in `actions`. + + :param actions: List of input source action sequences. A single action + sequence may be created with the help of + ``ActionSequence.dict``. + """ + body = {"actions": [] if actions is None else actions} + return self.session.send_command("POST", "actions", body) + + @command + def release(self): + return self.session.send_command("DELETE", "actions") + + def sequence(self, *args, **kwargs): + """Return an empty ActionSequence of the designated type. + + See ActionSequence for parameter list. + """ + return ActionSequence(self.session, *args, **kwargs) + +class Window(object): + def __init__(self, session): + self.session = session + + @property + @command + def size(self): + resp = self.session.send_command("GET", "window/size") + return (resp["width"], resp["height"]) + + @size.setter + @command + def size(self, (width, height)): + body = {"width": width, "height": height} + self.session.send_command("POST", "window/size", body) + + @property + @command + def position(self): + resp = self.session.send_command("GET", "window/position") + return (resp["x"], resp["y"]) + + @position.setter + @command + def position(self, (x, y)): + body = {"x": x, "y": y} + self.session.send_command("POST", "window/position", body) + + @property + @command + def maximize(self): + return self.session.send_command("POST", "window/maximize") + + +class Find(object): + def __init__(self, session): + self.session = session + + @command + def css(self, selector, all=True): + return self._find_element("css selector", selector, all) + + def _find_element(self, strategy, selector, all): + route = "elements" if all else "element" + + body = {"using": strategy, + "value": selector} + + data = self.session.send_command("POST", route, body, key="value") + + if all: + rv = [self.session._element(item) for item in data] + else: + rv = self.session._element(data) + + return rv + + +class Cookies(object): + def __init__(self, session): + self.session = session + + def __getitem__(self, name): + self.session.send_command("GET", "cookie/%s" % name, {}, key="value") + + def __setitem__(self, name, value): + cookie = {"name": name, + "value": None} + + if isinstance(name, (str, unicode)): + cookie["value"] = value + elif hasattr(value, "value"): + cookie["value"] = value.value + self.session.send_command("POST", "cookie/%s" % name, {}, key="value") + + +class UserPrompt(object): + def __init__(self, session): + self.session = session + + @command + def dismiss(self): + self.session.send_command("POST", "alert/dismiss") + + @command + def accept(self): + self.session.send_command("POST", "alert/accept") + + @property + @command + def text(self): + return self.session.send_command("GET", "alert/text", key="value") + + @text.setter + @command + def text(self, value): + body = {"value": list(value)} + self.session.send_command("POST", "alert/text", body=body) + + +class Session(object): + def __init__(self, host, port, url_prefix="/", desired_capabilities=None, + required_capabilities=None, timeout=transport.HTTP_TIMEOUT, + extension=None): + self.transport = transport.HTTPWireProtocol( + host, port, url_prefix, timeout=timeout) + self.desired_capabilities = desired_capabilities + self.required_capabilities = required_capabilities + self.session_id = None + self.timeouts = None + self.window = None + self.find = None + self._element_cache = {} + self.extension = None + self.extension_cls = extension + + self.timeouts = Timeouts(self) + self.window = Window(self) + self.find = Find(self) + self.alert = UserPrompt(self) + self.actions = Actions(self) + + def __enter__(self): + self.start() + return self + + def __exit__(self, *args, **kwargs): + self.end() + + def __del__(self): + self.end() + + def start(self): + if self.session_id is not None: + return + + body = {} + + caps = {} + if self.desired_capabilities is not None: + caps["desiredCapabilities"] = self.desired_capabilities + if self.required_capabilities is not None: + caps["requiredCapabilities"] = self.required_capabilities + #body["capabilities"] = caps + body = caps + + resp = self.transport.send("POST", "session", body=body) + self.session_id = resp["sessionId"] + + if self.extension_cls: + self.extension = self.extension_cls(self) + + return resp["value"] + + def end(self): + if self.session_id is None: + return + + url = "session/%s" % self.session_id + self.transport.send("DELETE", url) + + self.session_id = None + self.timeouts = None + self.window = None + self.find = None + self.extension = None + + def send_command(self, method, url, body=None, key=None): + if self.session_id is None: + raise error.SessionNotCreatedException() + url = urlparse.urljoin("session/%s/" % self.session_id, url) + return self.transport.send(method, url, body, key=key) + + @property + @command + def url(self): + return self.send_command("GET", "url", key="value") + + @url.setter + @command + def url(self, url): + if urlparse.urlsplit(url).netloc is None: + return self.url(url) + body = {"url": url} + return self.send_command("POST", "url", body) + + @command + def back(self): + return self.send_command("POST", "back") + + @command + def forward(self): + return self.send_command("POST", "forward") + + @command + def refresh(self): + return self.send_command("POST", "refresh") + + @property + @command + def title(self): + return self.send_command("GET", "title", key="value") + + @property + @command + def window_handle(self): + return self.send_command("GET", "window_handle", key="value") + + @window_handle.setter + @command + def window_handle(self, handle): + body = {"handle": handle} + return self.send_command("POST", "window", body=body) + + def switch_frame(self, frame): + if frame == "parent": + url = "frame/parent" + body = None + else: + url = "frame" + if isinstance(frame, Element): + body = {"id": frame.json()} + else: + body = {"id": frame} + + return self.send_command("POST", url, body) + + @command + def close(self): + return self.send_command("DELETE", "window_handle") + + @property + @command + def handles(self): + return self.send_command("GET", "window_handles", key="value") + + @property + @command + def active_element(self): + data = self.send_command("GET", "element/active", key="value") + if data is not None: + return self._element(data) + + def _element(self, data): + elem_id = data[element_key] + assert elem_id + if elem_id in self._element_cache: + return self._element_cache[elem_id] + return Element(self, elem_id) + + @command + def cookies(self, name=None): + if name is None: + url = "cookie" + else: + url = "cookie/%s" % name + return self.send_command("GET", url, {}, key="value") + + @command + def set_cookie(self, name, value, path=None, domain=None, secure=None, expiry=None): + body = {"name": name, + "value": value} + if path is not None: + body["path"] = path + if domain is not None: + body["domain"] = domain + if secure is not None: + body["secure"] = secure + if expiry is not None: + body["expiry"] = expiry + self.send_command("POST", "cookie", {"cookie": body}) + + def delete_cookie(self, name=None): + if name is None: + url = "cookie" + else: + url = "cookie/%s" % name + self.send_command("DELETE", url, {}, key="value") + + #[...] + + @command + def execute_script(self, script, args=None): + if args is None: + args = [] + + body = { + "script": script, + "args": args + } + return self.send_command("POST", "execute", body, key="value") + + @command + def execute_async_script(self, script, args=None): + if args is None: + args = [] + + body = { + "script": script, + "args": args + } + return self.send_command("POST", "execute_async", body, key="value") + + #[...] + + @command + def screenshot(self): + return self.send_command("GET", "screenshot", key="value") + + +class Element(object): + def __init__(self, session, id): + self.session = session + self.id = id + assert id not in self.session._element_cache + self.session._element_cache[self.id] = self + + def json(self): + return {element_key: self.id} + + @property + def session_id(self): + return self.session.session_id + + def url(self, suffix): + return "element/%s/%s" % (self.id, suffix) + + @command + def find_element(self, strategy, selector): + body = {"using": strategy, + "value": selector} + + elem = self.session.send_command("POST", self.url("element"), body, key="value") + return self.session.element(elem) + + @command + def click(self): + self.session.send_command("POST", self.url("click"), {}) + + @command + def tap(self): + self.session.send_command("POST", self.url("tap"), {}) + + @command + def clear(self): + self.session.send_command("POST", self.url("clear"), {}) + + @command + def send_keys(self, keys): + if isinstance(keys, (str, unicode)): + keys = [char for char in keys] + + body = {"value": keys} + + return self.session.send_command("POST", self.url("value"), body) + + @property + @command + def text(self): + return self.session.send_command("GET", self.url("text"), key="value") + + @property + @command + def name(self): + return self.session.send_command("GET", self.url("name"), key="value") + + @command + def style(self, property_name): + return self.session.send_command("GET", self.url("css/%s" % property_name), key="value") + + @property + @command + def rect(self): + return self.session.send_command("GET", self.url("rect")) + + @command + def property(self, name): + return self.session.send_command("GET", self.url("property/%s" % name), key="value") + + @command + def attribute(self, name): + return self.session.send_command("GET", self.url("attribute/%s" % name), key="value") diff --git a/testing/web-platform/tests/tools/webdriver/webdriver/error.py b/testing/web-platform/tests/tools/webdriver/webdriver/error.py new file mode 100644 index 000000000..dc168f3ef --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/webdriver/error.py @@ -0,0 +1,144 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + + +import collections + + +class WebDriverException(Exception): + http_status = None + status_code = None + + +class ElementNotSelectableException(WebDriverException): + http_status = 400 + status_code = "element not selectable" + + +class ElementNotVisibleException(WebDriverException): + http_status = 400 + status_code = "element not visible" + + +class InvalidArgumentException(WebDriverException): + http_status = 400 + status_code = "invalid argument" + + +class InvalidCookieDomainException(WebDriverException): + http_status = 400 + status_code = "invalid cookie domain" + + +class InvalidElementCoordinatesException(WebDriverException): + http_status = 400 + status_code = "invalid element coordinates" + + +class InvalidElementStateException(WebDriverException): + http_status = 400 + status_code = "invalid cookie domain" + + +class InvalidSelectorException(WebDriverException): + http_status = 400 + status_code = "invalid selector" + + +class InvalidSessionIdException(WebDriverException): + http_status = 404 + status_code = "invalid session id" + + +class JavascriptErrorException(WebDriverException): + http_status = 500 + status_code = "javascript error" + + +class MoveTargetOutOfBoundsException(WebDriverException): + http_status = 500 + status_code = "move target out of bounds" + + +class NoSuchAlertException(WebDriverException): + http_status = 400 + status_code = "no such alert" + + +class NoSuchElementException(WebDriverException): + http_status = 404 + status_code = "no such element" + + +class NoSuchFrameException(WebDriverException): + http_status = 400 + status_code = "no such frame" + + +class NoSuchWindowException(WebDriverException): + http_status = 400 + status_code = "no such window" + + +class ScriptTimeoutException(WebDriverException): + http_status = 408 + status_code = "script timeout" + + +class SessionNotCreatedException(WebDriverException): + http_status = 500 + status_code = "session not created" + + +class StaleElementReferenceException(WebDriverException): + http_status = 400 + status_code = "stale element reference" + + +class TimeoutException(WebDriverException): + http_status = 408 + status_code = "timeout" + + +class UnableToSetCookieException(WebDriverException): + http_status = 500 + status_code = "unable to set cookie" + + +class UnexpectedAlertOpenException(WebDriverException): + http_status = 500 + status_code = "unexpected alert open" + + +class UnknownErrorException(WebDriverException): + http_status = 500 + status_code = "unknown error" + + +class UnknownCommandException(WebDriverException): + http_status = 404 + status_code = "unknown command" + + +class UnknownMethodException(WebDriverException): + http_status = 405 + status_code = "unknown method" + + +class UnsupportedOperationException(WebDriverException): + http_status = 500 + status_code = "unsupported operation" + + +def get(status_code): + """Gets exception from `status_code`, falling back to + ``WebDriverException`` if it is not found. + """ + return _errors.get(status_code, WebDriverException) + + +_errors = collections.defaultdict() +for item in locals().values(): + if type(item) == type and issubclass(item, WebDriverException): + _errors[item.status_code] = item diff --git a/testing/web-platform/tests/tools/webdriver/webdriver/servo.py b/testing/web-platform/tests/tools/webdriver/webdriver/servo.py new file mode 100644 index 000000000..fd1539f7b --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/webdriver/servo.py @@ -0,0 +1,22 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +class ServoExtensionCommands(object): + def __init__(self, session): + self.session = session + + @command + def get_prefs(self, *prefs): + body = {"prefs": list(prefs)} + return self.session.send_command("POST", "servo/prefs/get", body) + + @command + def set_prefs(self, prefs): + body = {"prefs": prefs} + return self.session.send_command("POST", "servo/prefs/set", body) + + @command + def reset_prefs(self, *prefs): + body = {"prefs": list(prefs)} + return self.session.send_command("POST", "servo/prefs/reset", body) diff --git a/testing/web-platform/tests/tools/webdriver/webdriver/transport.py b/testing/web-platform/tests/tools/webdriver/webdriver/transport.py new file mode 100644 index 000000000..f3c1ed536 --- /dev/null +++ b/testing/web-platform/tests/tools/webdriver/webdriver/transport.py @@ -0,0 +1,83 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import httplib +import json +import urlparse + +import error + + +HTTP_TIMEOUT = 5 + + +class HTTPWireProtocol(object): + """Transports messages (commands and responses) over the WebDriver + wire protocol. + """ + + def __init__(self, host, port, url_prefix="/", timeout=HTTP_TIMEOUT): + """Construct interface for communicating with the remote server. + + :param url: URL of remote WebDriver server. + :param wait: Duration to wait for remote to appear. + """ + + self.host = host + self.port = port + self.url_prefix = url_prefix + + self._timeout = timeout + + def url(self, suffix): + return urlparse.urljoin(self.path_prefix, suffix) + + def send(self, method, url, body=None, headers=None, key=None): + """Send a command to the remote. + + :param method: "POST" or "GET". + :param body: Body of the request. Defaults to an empty dictionary + if ``method`` is "POST". + :param headers: Additional headers to include in the request. + :param key: Extract this key from the dictionary returned from + the remote. + """ + + if body is None and method == "POST": + body = {} + + if isinstance(body, dict): + body = json.dumps(body) + + if isinstance(body, unicode): + body = body.encode("utf-8") + + if headers is None: + headers = {} + + url = self.url_prefix + url + + conn = httplib.HTTPConnection( + self.host, self.port, strict=True, timeout=self._timeout) + conn.request(method, url, body, headers) + + resp = conn.getresponse() + resp_body = resp.read() + conn.close() + + try: + data = json.loads(resp_body) + except: + raise IOError("Could not parse response body as JSON: '%s'" % resp_body) + + if resp.status != 200: + cls = error.get(data.get("error")) + raise cls(data.get("message")) + + if key is not None: + data = data[key] + if not data: + data = None + + return data |