selenium-selenium-4.18.1/ 0000755 0001750 0001750 00000000000 14565422564 015142 5 ustar carsten carsten selenium-selenium-4.18.1/CONTRIBUTING.md 0000644 0001750 0001750 00000025523 14564764517 017410 0 ustar carsten carsten # Contributing to Selenium
The Selenium project welcomes contributions from everyone. There are a
number of ways you can help:
## Bug Reports
When opening new issues or commenting on existing issues please make
sure discussions are related to concrete technical issues with the
Selenium software.
It's imperative that issue reports outline the steps to reproduce
the defect. If the issue can't be reproduced it will be closed.
Please provide [concise reproducible test cases](http://sscce.org/)
and describe what results you are seeing and what results you expect.
Issues shouldn't be used for support. Please address questions to the
[`selenium-users@` mailing list](https://groups.google.com/forum/#!forum/selenium-users).
Discussion of high level project ideas or non-technical topics should
move to the
[`selenium-developers@` mailing list](https://groups.google.com/forum/#!forum/selenium-developers)
instead.
We also need help with triaging
[issues that needs investigation](https://github.com/SeleniumHQ/selenium/labels/I-needs%20investigation).
This means asking the right questions, procuring the right information
to properly debug and verify the issue, and bisecting a commit range if
the issue is a regression.
## Feature Requests
If you find that Selenium is missing something, feel free to open an issue
with details describing what feature(s) you'd like added or changed.
If you'd like a hand at trying to implement the feature yourself, please refer to the [Code Contributions](#code-contributions) section of the document.
## Documentation
Selenium is a big software project and documentation is key to
understanding how things work and learning effective ways to exploit
its potential.
The [seleniumhq.github.io](https://github.com/SeleniumHQ/seleniumhq.github.io/)
repository contains both Selenium’s site and documentation. This is an ongoing effort (not targeted
at any specific release) to provide updated information on how to use Selenium effectively, how to
get involved and how to contribute to Selenium.
The official documentation of Selenium is at https://selenium.dev/documentation/. More details on
how to get involved and contribute, please check the site's and
documentation [contributing guidelines](https://www.selenium.dev/documentation/about/contributing/).
## Code Contributions
The Selenium project welcomes new contributors. Individuals making
significant and valuable contributions over time are made _Committers_
and given commit-access to the project.
If you're looking for easy bugs, have a look at
[issues labelled E-easy](https://github.com/SeleniumHQ/selenium/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy)
on Github.
This document will guide you through the contribution process.
### Step 1: Fork
Fork the project [on Github](https://github.com/seleniumhq/selenium)
and check out your copy locally. Use `--depth 1` for a quick check out.
The repository is ~2GB and checking the whole history takes a while.
```shell
% git clone git@github.com:username/selenium.git --depth 1
% cd selenium
% git remote add upstream git://github.com/seleniumhq/selenium.git
```
#### Dependencies
We bundle dependencies in the _third-party/_ directory that is not
part of the proper project. Any changes to files in this directory or
its subdirectories should be sent upstream to the respective projects.
Please don't send your patch to us as we cannot accept it.
We do accept help in upgrading our existing dependencies or removing
superfluous dependencies. If you need to add a new dependency it's
often a good idea to reach out to the committers on the
[IRC channel or the mailing list](https://github.com/SeleniumHQ/selenium/blob/trunk/CONTRIBUTING.md#communication)
to check that your approach aligns with the project's
ideas. Nothing is more frustrating than seeing your hard work go to
waste because your vision doesn't align with the project's.
#### License Headers
Every file in the Selenium project must carry the following license
header boilerplate:
```text
Licensed to the Software Freedom Conservancy (SFC) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The SFC licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
```
There's no need to include a copyright statement in the file's header.
The copyright attributions can be reviewed in the
[NOTICE](https://github.com/SeleniumHQ/selenium/blob/trunk/NOTICE)
file found in the top-level directory.
### Step 2: Branch
Create a feature branch and start hacking:
```shell
% git checkout -b my-feature-branch
```
We practice HEAD-based development, which means all changes are applied
directly on top of trunk.
### Step 3: Commit
First make sure git knows your name and email address:
```shell
% git config --global user.name 'Santa Claus'
% git config --global user.email 'santa@example.com'
```
**Writing good commit messages is important.** A commit message
should describe what changed, why, and reference issues fixed (if
any). Follow these guidelines when writing one:
1. The first line should be around 50 characters or less and contain a
short description of the change.
2. Keep the second line blank.
3. Wrap all other lines at 72 columns.
4. Include `Fixes #N`, where _N_ is the issue number the commit
fixes, if any.
A good commit message can look like this:
```text
explain commit normatively in one line
Body of commit message is a few lines of text, explaining things
in more detail, possibly giving some background about the issue
being fixed, etc.
The body of the commit message can be several paragraphs, and
please do proper word-wrap and keep columns shorter than about
72 characters or so. That way `git log` will show things
nicely even when it is indented.
Fixes #141
```
The first line must be meaningful as it's what people see when they
run `git shortlog` or `git log --oneline`.
### Step 4: Rebase
Use `git rebase` (not `git merge`) to sync your work from time to time.
```shell
% git fetch upstream
% git rebase upstream/trunk
```
### Step 5: Test
Bug fixes and features **should have tests**. Look at other tests to
see how they should be structured. Verify that new and existing tests are
passing locally before pushing code.
#### Running tests locally
Build your code for the latest changes and run tests locally.
##### Python
Click to see How to run Python Tests.
It's not mandatory to run tests sequentially but running Unit tests
before browser testing is recommended.
Unit Tests
```shell
% bazel test //py:unit
```
Remote Tests
```shell
% bazel test --jobs 1 //py:test-remote
```
Browser Tests
```shell
% bazel test //py:test- #eg test-chrome, test-firefox
```
##### Javascript
Click to see How to run JavaScript Tests.
Node Tests
```shell
% bazel test //javascript/node/selenium-webdriver:tests
```
Firefox Atom Tests
```shell
% bazel test --test_tag_filters=firefox //javascript/atoms/... //javascript/selenium-atoms/... //javascript/webdriver/...
```
Grid UI Unit Tests
```shell
% cd javascript/grid-ui && npm install && npm test
```
##### Java
Click to see How to run Java Tests.
Small Tests
```shell
% bazel test --cache_test_results=no --test_size_filters=small grid java/test/...
```
Large Tests
```shell
% bazel test --cache_test_results=no java/test/org/openqa/selenium/grid/router:large-tests
```
Browser Tests
```shell
bazel test --test_size_filters=small,medium --cache_test_results=no --test_tag_filters=-browser-test //java/...
```
##### Ruby
Please see https://github.com/SeleniumHQ/selenium#ruby for details about running
tests.
### Step 6: Push
```shell
% git push origin my-feature-branch
```
Go to https://github.com/yourusername/selenium.git and press the _Pull
Request_ and fill out the form.
Pull requests are usually reviewed within a few days. If there are
comments to address, apply your changes in new commits (preferably
[fixups](http://git-scm.com/docs/git-commit)) and push to the same
branch.
### Step 7: Integration
When code review is complete, a committer will take your PR and
integrate it on Selenium's trunk branch. Because we like to keep a
linear history on the trunk branch, we will normally squash and rebase
your branch history.
## Stages of an Issue or PR
From your create your issue or pull request, through code review and
towards integration, it will be assigned different Github labels. The
labels serve for the committers to more easily keep track of work
that's pending or awaiting action.
Component labels are yellow and carry the **C** prefix. They highlight
the subsystem or component your PR makes changes in.
The driver labels (**D**) indicate if the changes are related to a
WebDriver implementation or the Selenium atoms.
The review labels (**R**) are:
* **awaiting answer**: awaits an answer from you
* **awaiting merge**: waits for a committer to integrate the PR
* **awaiting reviewer**: pending code review
* **blocked on external**: a change in an upstream repo is required
* **needs code changes**: waiting for you to fix a review issue
* **needs rebase**: the branch isn't in sync with trunk and needs to
be rebased
Issues are labelled to make them easier to categorise and find by:
* which **component** they relate to (java, cpp, dotnet, py, rb, nodejs)
* which **driver** is affected
* their presumed **difficulty** (easy, less easy, hard)
* what **type** of issue they are (defect, race condition, cleanup)
## Communication
Selenium contributors frequent the `#selenium` channel on
[`irc.freenode.org`](https://webchat.freenode.net/). You can also join
the [`selenium-developers@` mailing list](https://groups.google.com/forum/#!forum/selenium-developers).
Check https://selenium.dev/support/ for a complete list of options to communicate.
## Using the EngFlow RBE
To access the EngFlow RBE, a developer needs to be granted access to our project
container repository. Once that has been done, then any bazel command can be run
remotely by using `--config=remote`. For example: `bazel build --config=remote
grid` or `bazel test --config=remote java/test/...`
When you run a remote build, one of the first lines of output from Bazel will
include a link to the EngFlow UI so you can track the progress of the build and
gather information about the efficiency of the build.
selenium-selenium-4.18.1/MANIFEST.in 0000644 0001750 0001750 00000001502 14564764517 016704 0 ustar carsten carsten prune *
recursive-include selenium/webdriver *.py
recursive-include selenium/webdriver/common *.py
recursive-include selenium/webdriver/common/actions *.py
recursive-include selenium/webdriver/common/html5 *.py
recursive-include selenium/common *.py
recursive-include selenium/webdriver/chromium *.py
recursive-include selenium/webdriver/chrome *.py
recursive-include selenium/webdriver/phantomjs *.py
recursive-include selenium/webdriver/firefox *.py *.xpi *.json
recursive-include selenium/webdriver/ie *.py
recursive-include selenium/webdriver/edge *.py
recursive-include selenium/webdriver/remote *.py *.js
recursive-include selenium/webdriver/support *.py
include selenium/selenium.py
include selenium/__init__.py
include selenium/py.typed
include CHANGES
include README.rst
include LICENSE
recursive-include selenium.egg-info *
selenium-selenium-4.18.1/.skipped-tests 0000644 0001750 0001750 00000004151 14564764517 017751 0 ustar carsten carsten -//dotnet/test/common:DevTools/DevToolsNetworkTest-chrome
-//dotnet/test/common:Interactions/BasicMouseInterfaceTest-chrome
-//dotnet/test/common:Interactions/BasicMouseInterfaceTest-firefox
-//dotnet/test/common:JavascriptEnabledBrowserTest-chrome
-//dotnet/test/common:NetworkInterceptionTests-chrome
-//dotnet/test/common:TakesScreenshotTest-chrome
-//dotnet/test/common:TakesScreenshotTest-firefox
-//dotnet/test/common:VirtualAuthn/VirtualAuthenticatorTest-chrome
-//dotnet/test/support/UI:SelectBrowserTests-firefox
-//dotnet/test/support/UI:SelectTests
-//java/test/org/openqa/selenium/bidi/browsingcontext:BrowsingContextTest
-//java/test/org/openqa/selenium/bidi/browsingcontext:BrowsingContextTest-remote
-//java/test/org/openqa/selenium/chrome:ChromeDriverFunctionalTest
-//java/test/org/openqa/selenium/chrome:ChromeDriverFunctionalTest-remote
-//java/test/org/openqa/selenium/federatedcredentialmanagement:FederatedCredentialManagementTest
-//java/test/org/openqa/selenium/firefox:FirefoxDriverBuilderTest
-//java/test/org/openqa/selenium/grid/gridui:OverallGridTest
-//java/test/org/openqa/selenium/grid/router:RemoteWebDriverDownloadTest
-//java/test/org/openqa/selenium/grid/router:RemoteWebDriverDownloadTest-chrome
-//java/test/org/openqa/selenium/grid/router:RemoteWebDriverDownloadTest-chrome-remote
-//java/test/org/openqa/selenium/grid/router:RemoteWebDriverDownloadTest-remote
-//java/test/org/openqa/selenium/interactions:DefaultMouseTest
-//java/test/org/openqa/selenium/interactions:DefaultMouseTest-remote
-//java/test/org/openqa/selenium/remote:RemoteWebDriverBuilderTest
-//java/test/org/openqa/selenium/remote:RemoteWebDriverScreenshotTest-remote
-//javascript/atoms:test-chrome
-//javascript/atoms:test-firefox-beta
-//javascript/atoms:test-firefox-dev
-//py:common-chrome-test/selenium/webdriver/common/virtual_authenticator_tests.py
-//py:test-chrome-test/selenium/webdriver/chrome/chrome_launcher_tests.py
-//py:test-chrome-test/selenium/webdriver/chrome/chrome_service_tests.py
-//py:test-chrome-test/selenium/webdriver/chrome/proxy_tests.py
-//py:unit-test/unit/selenium/webdriver/common/cdp_module_fallback_tests.py
selenium-selenium-4.18.1/requirements.txt 0000644 0001750 0001750 00000001152 14564764517 020433 0 ustar carsten carsten async-generator==1.10
attrs==23.1.0
certifi==2023.7.22
cffi==1.16.0
cryptography==41.0.4
dataclasses==0.6
debugpy==1.8.0
h11==0.14.0
idna==3.4
importlib-metadata==6.8.0
inflection==0.5.1
iniconfig==2.0.0
more-itertools==10.1.0
multidict==6.0.2
outcome==1.3.0
packaging==23.2
pluggy==1.3.0
py==1.11.0
pycparser==2.21
pyOpenSSL==22.0.0
pyparsing==3.1.1
PySocks==1.7.1
pytest==7.4.2
pytest-instafail==0.5.0
pytest-mock==3.12.0
pytest-trio==0.8.0
sniffio==1.3.0
sortedcontainers==2.4.0
toml==0.10.2
trio>=0.20.2
trio-websocket==0.9.2
twine==4.0.2
typing_extensions==4.9.0
urllib3[socks]==2.0.7
wsproto==1.2.0
zipp==3.17.0
selenium-selenium-4.18.1/test/ 0000755 0001750 0001750 00000000000 14564764517 016127 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/ 0000755 0001750 0001750 00000000000 14564764517 017106 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/__init__.py 0000644 0001750 0001750 00000001423 14564764517 021217 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/ 0000755 0001750 0001750 00000000000 14564764517 020727 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/__init__.py 0000644 0001750 0001750 00000001423 14564764517 023040 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/webdriver/ 0000755 0001750 0001750 00000000000 14564764517 022720 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/common/ 0000755 0001750 0001750 00000000000 14564764517 024210 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/common/common_options_tests.py 0000644 0001750 0001750 00000005066 14564764517 031056 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver import Proxy
from selenium.webdriver.common.options import ArgOptions
from selenium.webdriver.common.proxy import ProxyType
@pytest.fixture
def options():
return ArgOptions()
def test_add_arguments(options):
options.add_argument("foo")
assert "foo" in options._arguments
def test_get_arguments(options):
options._arguments = ["foo"]
assert "foo" in options.arguments
def test_enables_mobile(options):
options.enable_mobile(android_package="cheese")
assert options.mobile_options["androidPackage"] == "cheese"
assert not hasattr(options.mobile_options, "androidActivity")
assert not hasattr(options.mobile_options, "androidDeviceSerial")
def test_enable_mobile_errors_without_package(options):
with pytest.raises(AttributeError):
options.enable_mobile()
def test_enable_mobile_with_activity(options):
options.enable_mobile(android_package="sausages", android_activity="eating")
assert options.mobile_options["androidActivity"] == "eating"
def test_enable_mobile_with_device_serial(options):
options.enable_mobile(android_package="cheese", android_activity="crackers", device_serial="1234")
options.mobile_options["androidDeviceSerial"] == "1234"
def test_missing_capabilities_return_false_rather_than_none():
options = ArgOptions()
assert options.strict_file_interactability is False
assert options.set_window_rect is False
assert options.accept_insecure_certs is False
def test_add_proxy():
options = ArgOptions()
proxy = Proxy({"proxyType": ProxyType.MANUAL})
proxy.http_proxy = "http://user:password@http_proxy.com:8080"
options.proxy = proxy
caps = options.to_capabilities()
assert options.proxy == proxy
assert caps.get("proxy") == proxy.to_capabilities()
selenium-selenium-4.18.1/test/unit/selenium/webdriver/common/cdp_module_fallback_tests.py 0000644 0001750 0001750 00000002373 14564764517 031743 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import re
import types
from selenium.webdriver.common.bidi.cdp import import_devtools
def test_missing_cdp_devtools_version_falls_back(caplog):
with caplog.at_level(logging.DEBUG, logger="selenium"):
assert isinstance(import_devtools("will_never_exist"), types.ModuleType)
# assert the fallback occurred successfully offered up a v{n} option.
assert re.match(r"Falling back to loading `devtools`: v\d+", caplog.records[-1].getMessage()) is not None
selenium-selenium-4.18.1/test/unit/selenium/webdriver/common/print_page_options_tests.py 0000644 0001750 0001750 00000006225 14564764517 031714 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.print_page_options import PrintOptions
@pytest.fixture
def print_options():
return PrintOptions()
def test_set_orientation(print_options):
print_options.orientation = "portrait"
assert print_options.orientation == "portrait"
def test_raises_exception_if_orientation_is_invalid(print_options):
with pytest.raises(ValueError):
print_options.orientation = "foobar"
def test_set_scale(print_options):
print_options.scale = 1
assert print_options.scale == 1
def test_raises_exception_if_scale_is_outside_range(print_options):
with pytest.raises(ValueError):
print_options.scale = 3
def test_raises_exception_if_scale_is_not_an_integer(print_options):
with pytest.raises(ValueError):
print_options.scale = "1"
def test_set_background(print_options):
print_options.background = True
assert print_options.background is True
def test_unset_value_to_be_none(print_options):
assert print_options.page_width is None
def test_set_width(print_options):
print_options.page_width = 3
assert print_options.page_width == 3
def test_raises_exception_if_set_invalid_width(print_options):
with pytest.raises(ValueError):
print_options.page_width = -1
def test_raises_exception_if_set_with_not_int(print_options):
with pytest.raises(ValueError):
print_options.page_width = "2"
def test_set_height(print_options):
print_options.page_height = 2
assert print_options.page_height == 2
def test_set_shrink_to_fit(print_options):
print_options.shrink_to_fit = True
assert print_options.shrink_to_fit is True
def test_raises_exception_if_set_shrink_to_fit_non_bool(print_options):
with pytest.raises(ValueError):
print_options.shrink_to_fit = "True"
def test_set_page_ranges(print_options):
print_options.page_ranges = ["1-2"]
assert print_options.page_ranges == ["1-2"]
def test_raises_exception_if_page_ranges_not_list(print_options):
with pytest.raises(ValueError):
print_options.page_ranges = "foobar"
def test_margin_height(print_options):
print_options.margin_top = 2
assert print_options.margin_top == 2
def test_raises_exception_if_margin_is_invalid(print_options):
with pytest.raises(ValueError):
print_options.margin_top = -1
with pytest.raises(ValueError):
print_options.margin_top = "2"
selenium-selenium-4.18.1/test/unit/selenium/webdriver/virtual_authenticator/ 0000755 0001750 0001750 00000000000 14564764517 027340 5 ustar carsten carsten ././@LongLink 0000644 0000000 0000000 00000000163 00000000000 011603 L ustar root root selenium-selenium-4.18.1/test/unit/selenium/webdriver/virtual_authenticator/virtual_authenticator_options_tests.py selenium-selenium-4.18.1/test/unit/selenium/webdriver/virtual_authenticator/virtual_authenticator_op0000644 0001750 0001750 00000003647 14564764517 034413 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions
@pytest.fixture
def options():
return VirtualAuthenticatorOptions()
def test_bespoke_options_for_virtual_authenticator():
assert VirtualAuthenticatorOptions(
protocol="ctap1/u2f",
transport="ble",
has_resident_key=True,
has_user_verification=True,
is_user_consenting=False,
is_user_verified=True,
).to_dict() == {
"protocol": "ctap1/u2f",
"transport": "ble",
"hasResidentKey": True,
"hasUserVerification": True,
"isUserConsenting": False,
"isUserVerified": True,
}
def test_to_dict_with_defaults(options):
default_options = options.to_dict()
assert default_options["transport"] == VirtualAuthenticatorOptions.Transport.USB.value
assert default_options["protocol"] == VirtualAuthenticatorOptions.Protocol.CTAP2.value
assert default_options["hasResidentKey"] is False
assert default_options["hasUserVerification"] is False
assert default_options["isUserConsenting"] is True
assert default_options["isUserVerified"] is False
selenium-selenium-4.18.1/test/unit/selenium/webdriver/virtual_authenticator/credentials_test.py 0000644 0001750 0001750 00000013032 14564764517 033245 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from base64 import urlsafe_b64decode
from base64 import urlsafe_b64encode
from typing import Tuple
import pytest
from selenium.webdriver.common.virtual_authenticator import Credential
BASE64__ENCODED_PK = """
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
"""
@pytest.fixture()
def data() -> Tuple:
_id = bytearray({1, 2, 3, 4})
rp_id = "localhost"
user_handle = bytearray({1})
privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
sign_count = 0
return (_id, rp_id, user_handle, privatekey, sign_count)
def test_rk_enabled_credential(data):
_id, rp_id, user_handle, privatekey, sign_count = data
credential = Credential.create_resident_credential(_id, rp_id, user_handle, privatekey, sign_count)
assert credential.id == urlsafe_b64encode(bytearray({1, 2, 3, 4})).decode()
if credential.is_resident_credential is True:
assert True
assert credential.rp_id == "localhost"
assert credential.user_handle == urlsafe_b64encode(bytearray({1})).decode()
assert credential.private_key == urlsafe_b64encode(privatekey).decode()
assert credential.sign_count == 0
def test_rk_disabled_credentials(data):
_id, rp_id, user_handle, privatekey, sign_count = data
credential = Credential.create_non_resident_credential(_id, rp_id, privatekey, sign_count)
assert credential.id == urlsafe_b64encode(bytearray({1, 2, 3, 4})).decode()
assert credential.private_key == urlsafe_b64encode(privatekey).decode()
assert credential.sign_count == 0
assert credential.rp_id == "localhost"
if credential.is_resident_credential is False:
assert True
else:
assert False
if credential.user_handle is None:
assert True
else:
assert False
def test_to_dict(data):
_id, rp_id, user_handle, privatekey, sign_count = data
credential = Credential.create_resident_credential(_id, rp_id, user_handle, privatekey, sign_count)
credential_dict = credential.to_dict()
assert credential_dict["credentialId"] == urlsafe_b64encode(bytearray({1, 2, 3, 4})).decode()
if credential_dict["isResidentCredential"] is True:
assert True
else:
assert False
assert credential_dict["rpId"] == "localhost"
assert credential_dict["userHandle"] == urlsafe_b64encode(bytearray({1})).decode()
assert credential_dict["privateKey"] == urlsafe_b64encode(privatekey).decode()
assert credential_dict["signCount"] == 0
def test_from_dict():
data = {
"credentialId": urlsafe_b64encode(bytearray({1, 2, 3, 4})).decode(),
"isResidentCredential": True,
"rpId": "localhost",
"userHandle": urlsafe_b64encode(bytearray({1})).decode(),
"privateKey": BASE64__ENCODED_PK,
"signCount": 0,
}
credential = Credential.from_dict(data)
key = urlsafe_b64decode(BASE64__ENCODED_PK)
assert credential.id == urlsafe_b64encode(bytearray({1, 2, 3, 4})).decode()
if credential.is_resident_credential is True:
assert True
else:
assert False
assert credential.rp_id == "localhost"
assert credential.user_handle == urlsafe_b64encode(bytearray({1})).decode()
assert credential.private_key == urlsafe_b64encode(key).decode()
assert credential.sign_count == 0
selenium-selenium-4.18.1/test/unit/selenium/webdriver/virtual_authenticator/__init__.py 0000644 0001750 0001750 00000001423 14564764517 031451 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/webdriver/webkitgtk/ 0000755 0001750 0001750 00000000000 14564764517 024713 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/webkitgtk/webkitgtk_options_tests.py 0000644 0001750 0001750 00000004407 14564764517 032262 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.webkitgtk.options import Options
@pytest.fixture
def options():
return Options()
def test_set_binary_location(options):
options.binary_location = "/foo/bar"
assert options._binary_location == "/foo/bar"
def test_get_binary_location(options):
options._binary_location = "/foo/bar"
assert options.binary_location == "/foo/bar"
def test_set_overlay_scrollbars_enabled(options):
options.overlay_scrollbars_enabled = False
assert options._overlay_scrollbars_enabled is False
def test_get_overlay_scrollbars_enabled(options):
options._overlay_scrollbars_enabled = True
assert options.overlay_scrollbars_enabled is True
def test_creates_capabilities(options):
options._arguments = ["foo"]
options._binary_location = "/bar"
options._overlay_scrollbars_enabled = True
caps = options.to_capabilities()
opts = caps.get(Options.KEY)
assert opts
assert "foo" in opts["args"]
assert opts["binary"] == "/bar"
assert opts["useOverlayScrollbars"] is True
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.WEBKITGTK.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
selenium-selenium-4.18.1/test/unit/selenium/webdriver/__init__.py 0000644 0001750 0001750 00000001423 14564764517 025031 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/webdriver/support/ 0000755 0001750 0001750 00000000000 14564764517 024434 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/support/color_tests.py 0000644 0001750 0001750 00000007127 14564764517 027355 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.webdriver.support.color import Color
def test_color_can_be_subclassed():
class MyColor(Color):
pass
assert isinstance(MyColor.from_string("rgb(1, 2, 3)"), MyColor)
def test_rgb_to_rgb():
rgb = "rgb(1, 2, 3)"
assert Color.from_string(rgb).rgb == rgb
def test_rgb_to_rgba():
rgb = "rgb(1, 2, 3)"
assert Color.from_string(rgb).rgba == "rgba(1, 2, 3, 1)"
def test_rgb_pct_to_rgba():
rgb = "rgb(10%, 20%, 30%)"
assert Color.from_string(rgb).rgba == "rgba(25, 51, 76, 1)"
def test_rgb_allows_whitespace():
rgb = "rgb(\t1, 2 , 3)"
assert Color.from_string(rgb).rgb == "rgb(1, 2, 3)"
def test_rgba_to_rgba():
rgba = "rgba(1, 2, 3, 0.5)"
assert Color.from_string(rgba).rgba == rgba
def test_rgba_pct_to_rgba():
rgba = "rgba(10%, 20%, 30%, 0.5)"
assert Color.from_string(rgba).rgba == "rgba(25, 51, 76, 0.5)"
def test_hex_to_hex():
hex_ = "#ff00a0"
assert Color.from_string(hex_).hex == hex_
def test_hex_to_rgb():
hex_ = "#01Ff03"
rgb = "rgb(1, 255, 3)"
assert Color.from_string(hex_).rgb == rgb
def test_hex_to_rgba():
hex_ = "#01Ff03"
rgba = "rgba(1, 255, 3, 1)"
assert Color.from_string(hex_).rgba == rgba
hex_ = "#00ff33"
rgba = "rgba(0, 255, 51, 1)"
assert Color.from_string(hex_).rgba == rgba
def test_rgb_to_hex():
assert Color.from_string("rgb(1, 255, 3)").hex == "#01ff03"
def test_hex3_to_rgba():
assert Color.from_string("#0f3").rgba == "rgba(0, 255, 51, 1)"
def test_hsl_to_rgba():
hsl = "hsl(120, 100%, 25%)"
rgba = "rgba(0, 128, 0, 1)"
assert Color.from_string(hsl).rgba == rgba
hsl = "hsl(100, 0%, 50%)"
rgba = "rgba(128, 128, 128, 1)"
assert Color.from_string(hsl).rgba == rgba
def test_hsla_to_rgba():
hsla = "hsla(120, 100%, 25%, 1)"
rgba = "rgba(0, 128, 0, 1)"
assert Color.from_string(hsla).rgba == rgba
hsla = "hsla(100, 0%, 50%, 0.5)"
rgba = "rgba(128, 128, 128, 0.5)"
assert Color.from_string(hsla).rgba == rgba
def test_named_color():
assert Color.from_string("green").rgba == "rgba(0, 128, 0, 1)"
assert Color.from_string("gray").rgba == "rgba(128, 128, 128, 1)"
assert Color.from_string("aqua").hex == "#00ffff"
assert Color.from_string("transparent").rgba == "rgba(0, 0, 0, 0)"
def test_equals():
assert Color.from_string("#f00") == Color.from_string("rgb(255, 0, 0)")
assert Color.from_string("rgba(30, 30, 30, 0.2)") != Color.from_string("rgba(30, 30, 30, 1)")
def test_hash():
hash1 = hash(Color.from_string("#f00"))
hash2 = hash(Color.from_string("rgb(255, 0, 0)"))
assert hash1 == hash2
def test_string_representations():
hex_ = "#01Ff03"
assert str(Color.from_string(hex_)) == "Color: rgba(1, 255, 3, 1)"
assert repr(Color.from_string(hex_)) == "Color(red=1, green=255, blue=3, alpha=1)"
selenium-selenium-4.18.1/test/unit/selenium/webdriver/ie/ 0000755 0001750 0001750 00000000000 14564764517 023315 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/ie/__init__.py 0000644 0001750 0001750 00000001423 14564764517 025426 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/webdriver/ie/test_ie_options.py 0000644 0001750 0001750 00000014536 14564764517 027107 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.ie.options import ElementScrollBehavior
from selenium.webdriver.ie.options import Options
TIMEOUT = 30
@pytest.fixture
def opts():
yield Options()
def test_arguments(opts):
arg1 = "-k"
arg2 = "-private"
opts.add_argument(arg1)
opts.add_argument(arg2)
assert arg1 in opts.arguments
assert arg2 in opts.arguments
def test_browser_attach_timeout(opts):
opts.browser_attach_timeout = TIMEOUT
assert opts.browser_attach_timeout == TIMEOUT
assert opts.options.get(Options.BROWSER_ATTACH_TIMEOUT) == TIMEOUT
def test_raises_exception_for_invalid_browser_attach_timeout(opts):
with pytest.raises(ValueError):
opts.browser_attach_timeout = "foo"
def test_element_scroll_behavior(opts):
opts.element_scroll_behavior = ElementScrollBehavior.BOTTOM
assert opts.element_scroll_behavior == ElementScrollBehavior.BOTTOM
assert opts.options.get(Options.ELEMENT_SCROLL_BEHAVIOR) == ElementScrollBehavior.BOTTOM
def test_ensure_clean_session(opts):
opts.ensure_clean_session = True
assert opts.ensure_clean_session is True
assert opts.options.get(Options.ENSURE_CLEAN_SESSION) is True
def test_file_upload_dialog_timeout(opts):
opts.file_upload_dialog_timeout = TIMEOUT
assert opts.file_upload_dialog_timeout is TIMEOUT
assert opts.options.get(Options.FILE_UPLOAD_DIALOG_TIMEOUT) is TIMEOUT
def test_raises_exception_for_file_upload_dialog_timeout(opts):
with pytest.raises(ValueError):
opts.file_upload_dialog_timeout = "foo"
def test_force_create_process_api(opts):
opts.force_create_process_api = True
assert opts.force_create_process_api is True
assert opts.options.get(Options.FORCE_CREATE_PROCESS_API) is True
def test_force_shell_windows_api(opts):
opts.force_shell_windows_api = True
assert opts.force_shell_windows_api is True
assert opts.options.get(Options.FORCE_SHELL_WINDOWS_API) is True
def test_full_page_screenshot(opts):
opts.full_page_screenshot = True
assert opts.full_page_screenshot is True
assert opts.options.get(Options.FULL_PAGE_SCREENSHOT) is True
def test_ignore_protected_mode_settings(opts):
opts.ignore_protected_mode_settings = True
assert opts.ignore_protected_mode_settings is True
assert opts.options.get(Options.IGNORE_PROTECTED_MODE_SETTINGS) is True
def test_ignore_zoom_level(opts):
opts.ignore_zoom_level = True
assert opts.ignore_zoom_level is True
assert opts.options.get(Options.IGNORE_ZOOM_LEVEL) is True
def test_initial_browser_url(opts):
url = "http://www.selenium.dev"
opts.initial_browser_url = url
assert opts.initial_browser_url == url
assert opts.options.get(Options.INITIAL_BROWSER_URL) == url
def test_native_events(opts):
opts.native_events = True
assert opts.native_events is True
assert opts.options.get(Options.NATIVE_EVENTS) is True
def test_persistent_hover(opts):
opts.persistent_hover = True
assert opts.persistent_hover is True
assert opts.options.get(Options.PERSISTENT_HOVER) is True
def test_require_window_focus(opts):
opts.require_window_focus = True
assert opts.require_window_focus is True
assert opts.options.get(Options.REQUIRE_WINDOW_FOCUS) is True
def test_use_per_process_proxy(opts):
opts.use_per_process_proxy = True
assert opts.use_per_process_proxy is True
assert opts.options.get(Options.USE_PER_PROCESS_PROXY) is True
def test_use_legacy_file_upload_dialog_handling(opts):
opts.use_legacy_file_upload_dialog_handling = True
assert opts.use_legacy_file_upload_dialog_handling is True
assert opts.options.get(Options.USE_LEGACY_FILE_UPLOAD_DIALOG_HANDLING) is True
def test_attach_to_edge_chrome(opts):
opts.attach_to_edge_chrome = True
assert opts.attach_to_edge_chrome is True
assert opts.options.get(Options.ATTACH_TO_EDGE_CHROME) is True
def test_edge_executable_path(opts):
path = "/path/to/edge"
opts.edge_executable_path = path
assert opts.edge_executable_path == path
assert opts.options.get(Options.EDGE_EXECUTABLE_PATH) == path
def test_additional_options(opts):
opts.add_additional_option("foo", "bar")
assert opts.additional_options.get("foo") == "bar"
def test_to_capabilities(opts):
opts._options["foo"] = "bar"
assert Options.KEY in opts.to_capabilities()
assert opts.to_capabilities().get(Options.KEY) == opts._options
def test_to_capabilities_arguments(opts):
arg = "-k"
opts.add_argument(arg)
caps_opts = opts.to_capabilities().get(Options.KEY)
assert caps_opts.get(Options.SWITCHES) == arg
def test_to_capabilities_additional_options(opts):
name = "foo"
value = "bar"
opts.add_additional_option(name, value)
caps_opts = opts.to_capabilities().get(Options.KEY)
assert caps_opts.get(name) == value
def test_to_capabilities_should_not_modify_set_options(opts):
opts._options["foo"] = "bar"
arg = "-k"
opts.add_argument(arg)
opts.add_additional_option("baz", "qux")
opts.to_capabilities().get(Options.KEY)
assert opts.options.get("foo") == "bar"
assert opts.arguments[0] == arg
assert opts.additional_options.get("baz") == "qux"
def test_starts_with_default_capabilities(opts):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.INTERNETEXPLORER.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert opts._caps == caps
def test_is_a_baseoptions(opts):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(opts, BaseOptions)
selenium-selenium-4.18.1/test/unit/selenium/webdriver/edge/ 0000755 0001750 0001750 00000000000 14564764517 023624 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/edge/edge_options_tests.py 0000644 0001750 0001750 00000004313 14564764517 030100 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.edge.options import Options
@pytest.fixture
def options():
return Options()
def test_raises_exception_with_invalid_page_load_strategy(options):
with pytest.raises(ValueError):
options.page_load_strategy = "never"
def test_set_page_load_strategy(options):
options.page_load_strategy = PageLoadStrategy.normal
caps = options.to_capabilities()
assert caps["pageLoadStrategy"] == PageLoadStrategy.normal
def test_get_page_load_strategy(options):
options._caps["pageLoadStrategy"] = PageLoadStrategy.normal
assert options.page_load_strategy == PageLoadStrategy.normal
def test_creates_capabilities(options):
options.page_load_strategy = PageLoadStrategy.eager
caps = options.to_capabilities()
assert caps["pageLoadStrategy"] == PageLoadStrategy.eager
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.EDGE.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
def test_use_webview():
options = Options()
options.use_webview = True
caps = options.to_capabilities()
assert caps["browserName"] == "webview2"
selenium-selenium-4.18.1/test/unit/selenium/webdriver/firefox/ 0000755 0001750 0001750 00000000000 14564764517 024362 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/firefox/firefox_options_tests.py 0000644 0001750 0001750 00000012756 14564764517 031406 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.options import Options
@pytest.fixture
def options():
return Options()
def test_set_binary_with_firefox_binary(options):
binary = FirefoxBinary("foo")
options.binary = binary
assert options.binary_location == "foo"
def test_set_binary_with_path(options):
options.binary = "/foo"
assert options.binary_location == "/foo"
def test_get_binary(options):
options.binary = "/foo"
assert options.binary._start_cmd == "/foo"
def test_set_binary_location(options):
options.binary_location = "/foo"
assert options.binary_location == "/foo"
def test_get_binary_location(options):
options._binary_location = "/foo"
assert options.binary_location == "/foo"
def test_set_preference(options):
options.set_preference("foo", "bar")
assert options._preferences["foo"] == "bar"
def test_get_preferences(options):
options._preferences = {"foo": "bar"}
assert options.preferences["foo"] == "bar"
def test_set_proxy(options):
proxy = Proxy({"proxyType": ProxyType.MANUAL})
options.proxy = proxy
assert options._proxy == proxy
def test_set_proxy_isnt_in_moz_prefix(options):
proxy = Proxy({"proxyType": ProxyType.MANUAL})
options.proxy = proxy
caps = options.to_capabilities()
assert caps["proxy"]["proxyType"] == "manual"
assert caps.get("moz:firefoxOptions") is None
def test_raises_exception_if_proxy_is_not_proxy_object(options):
with pytest.raises(InvalidArgumentException):
options.proxy = "foo"
def test_get_proxy(options):
options._proxy = "foo"
assert options.proxy == "foo"
def test_set_profile_with_firefox_profile(options):
profile = FirefoxProfile()
options.profile = profile
assert options._profile == profile
def test_set_profile_with_path(options):
options.profile = None
assert isinstance(options._profile, FirefoxProfile)
def test_get_profile(options):
options._profile = "foo"
assert options.profile == "foo"
def test_add_arguments(options):
options.add_argument("foo")
assert "foo" in options._arguments
def test_get_arguments(options):
options._arguments = ["foo"]
assert "foo" in options.arguments
def test_raises_exception_if_argument_is_falsy(options):
with pytest.raises(ValueError):
options.add_argument(None)
def test_set_log_level(options):
options.log.level = "debug"
assert options.log.level == "debug"
def test_creates_capabilities(options):
profile = FirefoxProfile()
options._arguments = ["foo"]
options._binary_location = "/bar"
options._preferences = {"foo": "bar"}
options.proxy = Proxy({"proxyType": ProxyType.MANUAL})
options._profile = profile
options.log.level = "debug"
caps = options.to_capabilities()
opts = caps.get(Options.KEY)
assert opts
assert "foo" in opts["args"]
assert opts["binary"] == "/bar"
assert opts["prefs"]["foo"] == "bar"
assert isinstance(opts["profile"], str) and opts["profile"]
assert caps["proxy"]["proxyType"] == "manual"
assert opts["log"]["level"] == "debug"
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
def test_raises_exception_with_invalid_page_load_strategy(options):
with pytest.raises(ValueError):
options.page_load_strategy = "never"
def test_set_page_load_strategy(options):
options.page_load_strategy = PageLoadStrategy.normal
assert options._caps["pageLoadStrategy"] == PageLoadStrategy.normal
def test_get_page_load_strategy(options):
options._page_load_strategy = PageLoadStrategy.normal
assert options._caps["pageLoadStrategy"] == PageLoadStrategy.normal
def test_creates_capabilities_with_page_load_strategy(options):
options.page_load_strategy = PageLoadStrategy.eager
caps = options.to_capabilities()
assert caps["pageLoadStrategy"] == PageLoadStrategy.eager
def test_enables_firefox_mobile(options):
options.enable_mobile()
result_caps = options.to_capabilities()
assert result_caps["moz:firefoxOptions"]["androidPackage"] == "org.mozilla.firefox"
selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/ 0000755 0001750 0001750 00000000000 14564764517 024213 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/remote_connection_tests.py 0000644 0001750 0001750 00000022355 14564764517 031530 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from urllib import parse
import pytest
import urllib3
from selenium import __version__
from selenium.webdriver.remote.remote_connection import RemoteConnection
def test_get_remote_connection_headers_defaults():
url = "http://remote"
headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
assert "Authorization" not in headers
assert "Connection" not in headers
assert headers.get("Accept") == "application/json"
assert headers.get("Content-Type") == "application/json;charset=UTF-8"
assert headers.get("User-Agent").startswith(f"selenium/{__version__} (python ")
assert headers.get("User-Agent").split(" ")[-1] in {"windows)", "mac)", "linux)"}
def test_get_remote_connection_headers_adds_auth_header_if_pass():
url = "http://user:pass@remote"
headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url))
assert headers.get("Authorization") == "Basic dXNlcjpwYXNz"
def test_get_remote_connection_headers_adds_keep_alive_if_requested():
url = "http://remote"
headers = RemoteConnection.get_remote_connection_headers(parse.urlparse(url), keep_alive=True)
assert headers.get("Connection") == "keep-alive"
def test_get_proxy_url_http(mock_proxy_settings):
proxy = "http://http_proxy.com:8080"
remote_connection = RemoteConnection("http://remote", keep_alive=False)
proxy_url = remote_connection._get_proxy_url()
assert proxy_url == proxy
def test_get_proxy_url_https(mock_proxy_settings):
proxy = "http://https_proxy.com:8080"
remote_connection = RemoteConnection("https://remote", keep_alive=False)
proxy_url = remote_connection._get_proxy_url()
assert proxy_url == proxy
def test_get_proxy_url_none(mock_proxy_settings_missing):
remote_connection = RemoteConnection("https://remote", keep_alive=False)
proxy_url = remote_connection._get_proxy_url()
assert proxy_url is None
def test_get_proxy_url_http_auth(mock_proxy_auth_settings):
remote_connection = RemoteConnection("http://remote", keep_alive=False)
proxy_url = remote_connection._get_proxy_url()
raw_proxy_url, basic_auth_string = remote_connection._separate_http_proxy_auth()
assert proxy_url == "http://user:password@http_proxy.com:8080"
assert raw_proxy_url == "http://http_proxy.com:8080"
assert basic_auth_string == "user:password"
def test_get_proxy_url_https_auth(mock_proxy_auth_settings):
remote_connection = RemoteConnection("https://remote", keep_alive=False)
proxy_url = remote_connection._get_proxy_url()
raw_proxy_url, basic_auth_string = remote_connection._separate_http_proxy_auth()
assert proxy_url == "https://user:password@https_proxy.com:8080"
assert raw_proxy_url == "https://https_proxy.com:8080"
assert basic_auth_string == "user:password"
def test_get_connection_manager_without_proxy(mock_proxy_settings_missing):
remote_connection = RemoteConnection("http://remote", keep_alive=False)
conn = remote_connection._get_connection_manager()
assert isinstance(conn, urllib3.PoolManager)
def test_get_connection_manager_for_certs_and_timeout(monkeypatch):
monkeypatch.setattr(RemoteConnection, "get_timeout", lambda _: 10) # Class state; leaks into subsequent tests.
remote_connection = RemoteConnection("http://remote", keep_alive=False)
conn = remote_connection._get_connection_manager()
assert conn.connection_pool_kw["timeout"] == 10
assert conn.connection_pool_kw["cert_reqs"] == "CERT_REQUIRED"
assert "certifi/cacert.pem" in conn.connection_pool_kw["ca_certs"]
def test_default_socket_timeout_is_correct():
remote_connection = RemoteConnection("http://remote", keep_alive=True)
conn = remote_connection._get_connection_manager()
assert conn.connection_pool_kw["timeout"] is None
def test_get_connection_manager_with_proxy(mock_proxy_settings):
remote_connection = RemoteConnection("http://remote", keep_alive=False)
conn = remote_connection._get_connection_manager()
assert isinstance(conn, urllib3.ProxyManager)
assert conn.proxy.scheme == "http"
assert conn.proxy.host == "http_proxy.com"
assert conn.proxy.port == 8080
remote_connection_https = RemoteConnection("https://remote", keep_alive=False)
conn = remote_connection_https._get_connection_manager()
assert isinstance(conn, urllib3.ProxyManager)
assert conn.proxy.scheme == "http"
assert conn.proxy.host == "https_proxy.com"
assert conn.proxy.port == 8080
def test_get_connection_manager_with_auth_proxy(mock_proxy_auth_settings):
proxy_auth_header = urllib3.make_headers(proxy_basic_auth="user:password")
remote_connection = RemoteConnection("http://remote", keep_alive=False)
conn = remote_connection._get_connection_manager()
assert isinstance(conn, urllib3.ProxyManager)
assert conn.proxy.scheme == "http"
assert conn.proxy.host == "http_proxy.com"
assert conn.proxy.port == 8080
assert conn.proxy_headers == proxy_auth_header
remote_connection_https = RemoteConnection("https://remote", keep_alive=False)
conn = remote_connection_https._get_connection_manager()
assert isinstance(conn, urllib3.ProxyManager)
assert conn.proxy.scheme == "https"
assert conn.proxy.host == "https_proxy.com"
assert conn.proxy.port == 8080
assert conn.proxy_headers == proxy_auth_header
@pytest.mark.parametrize(
"url",
[
"*",
".localhost",
"localhost:80",
"locahost",
"127.0.0.1",
"LOCALHOST",
"LOCALHOST:80",
"http://localhost",
"https://localhost",
"test.localhost",
" localhost",
"::1",
"127.0.0.2",
],
)
def test_get_connection_manager_when_no_proxy_set(mock_no_proxy_settings, url):
remote_connection = RemoteConnection(url)
conn = remote_connection._get_connection_manager()
assert isinstance(conn, urllib3.PoolManager)
def test_ignore_proxy_env_vars(mock_proxy_settings):
remote_connection = RemoteConnection("http://remote", ignore_proxy=True)
conn = remote_connection._get_connection_manager()
assert isinstance(conn, urllib3.PoolManager)
def test_get_socks_proxy_when_set(mock_socks_proxy_settings):
remote_connection = RemoteConnection("http://127.0.0.1:4444/wd/hub")
conn = remote_connection._get_connection_manager()
from urllib3.contrib.socks import SOCKSProxyManager
assert isinstance(conn, SOCKSProxyManager)
class MockResponse:
code = 200
headers = []
def read(self):
return b"{}"
def close(self):
pass
def getheader(self, *args, **kwargs):
pass
@pytest.fixture(scope="function")
def mock_proxy_settings_missing(monkeypatch):
monkeypatch.delenv("HTTPS_PROXY", raising=False)
monkeypatch.delenv("HTTP_PROXY", raising=False)
monkeypatch.delenv("https_proxy", raising=False)
monkeypatch.delenv("http_proxy", raising=False)
@pytest.fixture(scope="function")
def mock_socks_proxy_settings(monkeypatch):
http_proxy = "SOCKS5://http_proxy.com:8080"
https_proxy = "SOCKS5://https_proxy.com:8080"
monkeypatch.setenv("HTTPS_PROXY", https_proxy)
monkeypatch.setenv("HTTP_PROXY", http_proxy)
monkeypatch.setenv("https_proxy", https_proxy)
monkeypatch.setenv("http_proxy", http_proxy)
@pytest.fixture(scope="function")
def mock_proxy_settings(monkeypatch):
http_proxy = "http://http_proxy.com:8080"
https_proxy = "http://https_proxy.com:8080"
monkeypatch.setenv("HTTPS_PROXY", https_proxy)
monkeypatch.setenv("HTTP_PROXY", http_proxy)
monkeypatch.setenv("https_proxy", https_proxy)
monkeypatch.setenv("http_proxy", http_proxy)
@pytest.fixture(scope="function")
def mock_proxy_auth_settings(monkeypatch):
http_proxy = "http://user:password@http_proxy.com:8080"
https_proxy = "https://user:password@https_proxy.com:8080"
monkeypatch.setenv("HTTPS_PROXY", https_proxy)
monkeypatch.setenv("HTTP_PROXY", http_proxy)
monkeypatch.setenv("https_proxy", https_proxy)
monkeypatch.setenv("http_proxy", http_proxy)
@pytest.fixture(scope="function")
def mock_no_proxy_settings(monkeypatch):
http_proxy = "http://http_proxy.com:8080"
https_proxy = "http://https_proxy.com:8080"
monkeypatch.setenv("HTTPS_PROXY", https_proxy)
monkeypatch.setenv("HTTP_PROXY", http_proxy)
monkeypatch.setenv("https_proxy", https_proxy)
monkeypatch.setenv("http_proxy", http_proxy)
monkeypatch.setenv("no_proxy", "65.253.214.253,localhost,127.0.0.1,*zyz.xx,::1")
monkeypatch.setenv("NO_PROXY", "65.253.214.253,localhost,127.0.0.1,*zyz.xx,::1,127.0.0.0/8")
selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/__init__.py 0000644 0001750 0001750 00000001423 14564764517 026324 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/error_handler_tests.py 0000644 0001750 0001750 00000026744 14564764517 030652 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common import exceptions
from selenium.webdriver.remote.errorhandler import ErrorCode
from selenium.webdriver.remote.errorhandler import ErrorHandler
@pytest.fixture
def handler():
yield ErrorHandler()
def test_does_not_raise_exception_on_success(handler):
assert handler.check_response({"status": ErrorCode.SUCCESS}) is None
assert handler.check_response({}) is None
@pytest.mark.parametrize("code", ErrorCode.NO_SUCH_ELEMENT)
def test_raises_exception_for_no_such_element(handler, code):
with pytest.raises(exceptions.NoSuchElementException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.NO_SUCH_FRAME)
def test_raises_exception_for_no_such_frame(handler, code):
with pytest.raises(exceptions.NoSuchFrameException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNKNOWN_COMMAND)
def test_raises_exception_for_unknown_command(handler, code):
with pytest.raises(exceptions.WebDriverException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.STALE_ELEMENT_REFERENCE)
def test_raises_exception_for_stale_element_reference(handler, code):
with pytest.raises(exceptions.StaleElementReferenceException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.ELEMENT_NOT_VISIBLE)
def test_raises_exception_for_element_not_visible(handler, code):
with pytest.raises(exceptions.ElementNotVisibleException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_ELEMENT_STATE)
def test_raises_exception_for_invalid_element_state(handler, code):
with pytest.raises(exceptions.InvalidElementStateException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNKNOWN_ERROR)
def test_raises_exception_for_unknown_error(handler, code):
with pytest.raises(exceptions.WebDriverException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.ELEMENT_IS_NOT_SELECTABLE)
def test_raises_exception_for_element_not_selectable(handler, code):
with pytest.raises(exceptions.ElementNotSelectableException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.JAVASCRIPT_ERROR)
def test_raises_exception_for_javascript_error(handler, code):
with pytest.raises(exceptions.JavascriptException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.XPATH_LOOKUP_ERROR)
def test_raises_exception_for_xpath_lookup_error(handler, code):
with pytest.raises(exceptions.WebDriverException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.TIMEOUT)
def test_raises_exception_for_timeout(handler, code):
with pytest.raises(exceptions.TimeoutException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.NO_SUCH_WINDOW)
def test_raises_exception_for_no_such_window(handler, code):
with pytest.raises(exceptions.NoSuchWindowException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_COOKIE_DOMAIN)
def test_raises_exception_for_invalid_cookie_domain(handler, code):
with pytest.raises(exceptions.InvalidCookieDomainException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNABLE_TO_SET_COOKIE)
def test_raises_exception_for_unable_to_set_cookie(handler, code):
with pytest.raises(exceptions.UnableToSetCookieException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNEXPECTED_ALERT_OPEN)
def test_raises_exception_for_unexpected_alert_open(handler, code):
with pytest.raises(exceptions.UnexpectedAlertPresentException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.NO_ALERT_OPEN)
def test_raises_exception_for_no_alert_open(handler, code):
with pytest.raises(exceptions.NoAlertPresentException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.SCRIPT_TIMEOUT)
def test_raises_exception_for_script_timeout(handler, code):
with pytest.raises(exceptions.TimeoutException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_ELEMENT_COORDINATES)
def test_raises_exception_for_invalid_element_coordinates(handler, code):
with pytest.raises(exceptions.WebDriverException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.IME_NOT_AVAILABLE)
def test_raises_exception_for_ime_not_available(handler, code):
with pytest.raises(exceptions.ImeNotAvailableException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.IME_ENGINE_ACTIVATION_FAILED)
def test_raises_exception_for_ime_activation_failed(handler, code):
with pytest.raises(exceptions.ImeActivationFailedException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_SELECTOR)
def test_raises_exception_for_invalid_selector(handler, code):
with pytest.raises(exceptions.InvalidSelectorException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.SESSION_NOT_CREATED)
def test_raises_exception_for_session_not_created(handler, code):
with pytest.raises(exceptions.SessionNotCreatedException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS)
def test_raises_exception_for_move_target_out_of_bounds(handler, code):
with pytest.raises(exceptions.MoveTargetOutOfBoundsException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_XPATH_SELECTOR)
def test_raises_exception_for_invalid_xpath_selector(handler, code):
with pytest.raises(exceptions.InvalidSelectorException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER)
def test_raises_exception_for_invalid_xpath_selector_return_typer(handler, code):
with pytest.raises(exceptions.InvalidSelectorException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.ELEMENT_NOT_INTERACTABLE)
def test_raises_exception_for_element_not_interactable(handler, code):
with pytest.raises(exceptions.ElementNotInteractableException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INSECURE_CERTIFICATE)
def test_raises_exception_for_insecure_certificate(handler, code):
with pytest.raises(exceptions.InsecureCertificateException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_ARGUMENT)
def test_raises_exception_for_invalid_argument(handler, code):
with pytest.raises(exceptions.InvalidArgumentException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_COORDINATES)
def test_raises_exception_for_invalid_coordinates(handler, code):
with pytest.raises(exceptions.InvalidCoordinatesException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.INVALID_SESSION_ID)
def test_raises_exception_for_invalid_session_id(handler, code):
with pytest.raises(exceptions.InvalidSessionIdException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.NO_SUCH_COOKIE)
def test_raises_exception_for_no_such_cookie(handler, code):
with pytest.raises(exceptions.NoSuchCookieException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNABLE_TO_CAPTURE_SCREEN)
def test_raises_exception_for_unable_to_capture_screen_exception(handler, code):
with pytest.raises(exceptions.ScreenshotException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.ELEMENT_CLICK_INTERCEPTED)
def test_raises_exception_for_element_click_intercepted(handler, code):
with pytest.raises(exceptions.ElementClickInterceptedException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.UNKNOWN_METHOD)
def test_raises_exception_for_unknown_method(handler, code):
with pytest.raises(exceptions.UnknownMethodException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("code", ErrorCode.METHOD_NOT_ALLOWED)
def test_raises_exception_for_method_not_allowed(handler, code):
with pytest.raises(exceptions.WebDriverException):
handler.check_response({"status": code, "value": "foo"})
@pytest.mark.parametrize("key", ["stackTrace", "stacktrace"])
def test_relays_exception_stacktrace(handler, key):
import json
stacktrace = {"lineNumber": 100, "fileName": "egg", "methodName": "ham", "className": "Spam"}
value = {key: [stacktrace], "message": "very bad", "error": ErrorCode.UNKNOWN_METHOD[0]}
response = {"status": 400, "value": json.dumps({"value": value})}
with pytest.raises(exceptions.UnknownMethodException) as e:
handler.check_response(response)
assert "Spam.ham" in e.value.stacktrace[0]
def test_handle_errors_better(handler):
import json
response = {
"status": 500,
"value": json.dumps(
{
"value": {
"message": "Could not start a new session. No Node supports the required capabilities: Capabilities {browserName: chrome, goog:chromeOptions: {args: [headless, silent], extensions: [], w3c: false}}, Capabilities {browserName: chrome, goog:chromeOptions: {args: [headless, silent], extensions: [], w3c: false}, version: }\nBuild info: version: '4.0.0-beta-3', revision: '5d108f9a67'\nSystem info: host: '9315f0a993d2', ip: '172.17.0.8', os.name: 'Linux', os.arch: 'amd64', os.version: '5.8.0-44-generic', java.version: '1.8.0_282'\nDriver info: driver.version: unknown"
}
}
),
}
with pytest.raises(exceptions.WebDriverException) as e:
handler.check_response(response)
assert "Could not start a new session." in e.value.msg
selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/new_session_tests.py 0000644 0001750 0001750 00000010411 14564764517 030340 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from importlib import import_module
import pytest
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.options import ArgOptions
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote import webdriver
from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webdriver import WebDriver
def test_converts_proxy_type_value_to_lowercase_for_w3c(mocker):
mock = mocker.patch("selenium.webdriver.remote.webdriver.WebDriver.execute")
w3c_caps = {"pageLoadStrategy": "normal", "proxy": {"proxyType": "manual", "httpProxy": "foo"}}
options = ArgOptions()
proxy = Proxy({"proxyType": ProxyType.MANUAL, "httpProxy": "foo"})
options.proxy = proxy
WebDriver(options=options)
expected_params = {"capabilities": {"firstMatch": [{}], "alwaysMatch": w3c_caps}}
mock.assert_called_with(Command.NEW_SESSION, expected_params)
def test_works_as_context_manager(mocker):
mocker.patch("selenium.webdriver.remote.webdriver.WebDriver.execute")
quit_ = mocker.patch("selenium.webdriver.remote.webdriver.WebDriver.quit")
with WebDriver(options=ChromeOptions()) as driver:
assert isinstance(driver, WebDriver)
assert quit_.call_count == 1
@pytest.mark.parametrize("browser_name", ["firefox", "chrome", "ie"])
def test_accepts_options_to_remote_driver(mocker, browser_name):
options = import_module(f"selenium.webdriver.{browser_name}.options")
mock = mocker.patch("selenium.webdriver.remote.webdriver.WebDriver.start_session")
opts = options.Options()
opts.add_argument("foo")
WebDriver(options=opts)
expected_caps = opts.to_capabilities()
mock.assert_called_with(expected_caps)
def test_always_match_if_2_of_the_same_options():
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.options import Options as ChromeOptions2
co1 = ChromeOptions()
co1.add_argument("foo")
co2 = ChromeOptions2()
co2.add_argument("bar")
expected = {
"capabilities": {
"alwaysMatch": {
"browserName": "chrome",
"pageLoadStrategy": PageLoadStrategy.normal,
},
"firstMatch": [
{"goog:chromeOptions": {"args": ["foo"], "extensions": []}},
{"goog:chromeOptions": {"args": ["bar"], "extensions": []}},
],
}
}
result = webdriver.create_matches([co1, co2])
assert expected == result
def test_first_match_when_2_different_option_types():
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
expected = {
"capabilities": {
"alwaysMatch": {"pageLoadStrategy": PageLoadStrategy.normal},
"firstMatch": [
{"browserName": "chrome", "goog:chromeOptions": {"extensions": [], "args": []}},
{
"browserName": "firefox",
"acceptInsecureCerts": True,
"moz:debuggerAddress": True,
"moz:firefoxOptions": {"args": ["foo"]},
},
],
}
}
firefox_options = FirefoxOptions()
firefox_options.add_argument("foo")
result = webdriver.create_matches([ChromeOptions(), firefox_options])
assert expected == result
selenium-selenium-4.18.1/test/unit/selenium/webdriver/remote/subtyping_tests.py 0000644 0001750 0001750 00000004175 14564764517 030042 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webdriver import WebElement
def test_web_element_not_subclassed():
"""A registered subtype of WebElement should work with isinstance checks."""
class MyWebElement:
def __init__(self, parent, id, _w3c=True):
self.parent = parent
self.id = id
self._w3c = _w3c
# Test that non registered class instance is not instance of Remote WebElement
my_web_element = MyWebElement("parent", "1")
assert not isinstance(my_web_element, WebElement)
# Register the class as a subtype of WebElement
WebElement.register(MyWebElement)
my_registered_web_element = MyWebElement("parent", "2")
assert isinstance(my_registered_web_element, WebElement)
def test_webdriver_not_subclassed():
"""A registered subtype of WebDriver should work with isinstance checks."""
class MyWebDriver:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Test that non registered class instance is not instance of Remote WebDriver
my_driver = MyWebDriver()
assert not isinstance(my_driver, WebDriver)
# Register the class as a subtype of WebDriver
WebDriver.register(MyWebDriver)
my_registered_driver = MyWebDriver()
assert isinstance(my_registered_driver, MyWebDriver)
selenium-selenium-4.18.1/test/unit/selenium/webdriver/chrome/ 0000755 0001750 0001750 00000000000 14564764517 024175 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/chrome/chrome_options_tests.py 0000644 0001750 0001750 00000011025 14564764517 031020 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import platform
from os import path
import pytest
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.options import PageLoadStrategy
@pytest.fixture
def options():
return Options()
def test_set_binary_location(options):
options.binary_location = "/foo/bar"
assert options._binary_location == "/foo/bar"
def test_get_binary_location(options):
options._binary_location = "/foo/bar"
assert options.binary_location == "/foo/bar"
def test_set_debugger_address(options):
options.debugger_address = "/foo/bar"
assert options._debugger_address == "/foo/bar"
def test_get_debugger_address(options):
options._debugger_address = "/foo/bar"
assert options.debugger_address == "/foo/bar"
def test_add_arguments(options):
options.add_argument("foo")
assert "foo" in options._arguments
def test_get_arguments(options):
options._arguments = ["foo"]
assert "foo" in options.arguments
def test_raises_exception_if_argument_is_falsy(options):
with pytest.raises(ValueError):
options.add_argument(None)
def test_raises_exception_if_extension_is_falsy(options):
with pytest.raises(ValueError):
options.add_extension(None)
def test_raises_exception_if_extension_does_not_exist(options):
with pytest.raises(IOError):
options.add_extension(path.join(path.abspath(path.curdir), "fakepath"))
def test_add_extension(options, mocker):
pth = path.abspath(path.expanduser("/foo/bar"))
mocker.patch("os.path.exists").return_value = True
options.add_extension(pth)
assert pth in options._extension_files
def test_raises_exception_if_encoded_extension_is_falsy(options):
with pytest.raises(ValueError):
options.add_encoded_extension(None)
def test_add_encoded_extension(options):
options.add_encoded_extension("/foo/bar")
assert "/foo/bar" in options._extensions
def test_get_extensions_from_extension_files(options, mocker):
null = "NUL" if platform.system().lower() == "windows" else "/dev/null"
mocker.patch("selenium.webdriver.chromium.options.open").return_value = open(null)
mocker.patch("base64.b64encode").return_value = b"foo"
options._extension_files = ["foo"]
assert "foo" in options.extensions
def test_get_extensions_from_encoded_extensions(options, mocker):
options._extensions = ["foo"]
assert "foo" in options.extensions
def test_add_experimental_options(options):
options.add_experimental_option("foo", "bar")
assert options._experimental_options["foo"] == "bar"
def test_get_experimental_options(options):
options._experimental_options = {"foo": "bar"}
assert options.experimental_options["foo"] == "bar"
def test_creates_capabilities(options):
options._arguments = ["foo"]
options._binary_location = "/bar"
options._extensions = ["baz"]
options._debugger_address = "/foo/bar"
options._experimental_options = {"foo": "bar"}
caps = options.to_capabilities()
opts = caps.get(Options.KEY)
assert opts
assert "foo" in opts["args"]
assert opts["binary"] == "/bar"
assert "baz" in opts["extensions"]
assert opts["debuggerAddress"] == "/foo/bar"
assert opts["foo"] == "bar"
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.CHROME.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
def test_enables_chrome_mobile(options):
options.enable_mobile()
result_caps = options.to_capabilities()
assert result_caps["goog:chromeOptions"]["androidPackage"] == "com.android.chrome"
selenium-selenium-4.18.1/test/unit/selenium/webdriver/wpewebkit/ 0000755 0001750 0001750 00000000000 14564764517 024721 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/wpewebkit/wpewebkit_options_tests.py 0000644 0001750 0001750 00000003564 14564764517 032301 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.wpewebkit.options import Options
@pytest.fixture
def options():
return Options()
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.WPEWEBKIT.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_set_binary_location(options):
options.binary_location = "/foo/bar"
assert options._binary_location == "/foo/bar"
def test_get_binary_location(options):
options._binary_location = "/foo/bar"
assert options.binary_location == "/foo/bar"
def test_creates_capabilities(options):
options._arguments = ["foo"]
options._binary_location = "/bar"
caps = options.to_capabilities()
opts = caps.get(Options.KEY)
assert opts
assert "foo" in opts["args"]
assert opts["binary"] == "/bar"
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
selenium-selenium-4.18.1/test/unit/selenium/webdriver/safari/ 0000755 0001750 0001750 00000000000 14564764517 024165 5 ustar carsten carsten selenium-selenium-4.18.1/test/unit/selenium/webdriver/safari/safari_options_tests.py 0000644 0001750 0001750 00000004335 14564764517 031006 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import PageLoadStrategy
from selenium.webdriver.safari.options import Options
@pytest.fixture
def options():
return Options()
def test_starts_with_default_capabilities(options):
from selenium.webdriver import DesiredCapabilities
caps = DesiredCapabilities.SAFARI.copy()
caps.update({"pageLoadStrategy": PageLoadStrategy.normal})
assert options._caps == caps
def test_is_a_baseoptions(options):
from selenium.webdriver.common.options import BaseOptions
assert isinstance(options, BaseOptions)
def test_can_set_automatic_inspection(options):
options.automatic_inspection = True
assert options.automatic_inspection is True
assert options._caps.get(Options.AUTOMATIC_INSPECTION) is True
def test_can_set_automatic_profiling(options):
options.automatic_profiling = True
assert options.automatic_profiling is True
assert options._caps.get(Options.AUTOMATIC_PROFILING) is True
def test_setting_technology_preview_changes_browser_name(options):
from selenium.webdriver import DesiredCapabilities
BROWSER_NAME = "browserName"
assert options._caps.get(BROWSER_NAME) == DesiredCapabilities.SAFARI[BROWSER_NAME]
options.use_technology_preview = True
assert options._caps.get(BROWSER_NAME) == options.SAFARI_TECH_PREVIEW
options.use_technology_preview = False
assert options._caps.get(BROWSER_NAME) == DesiredCapabilities.SAFARI[BROWSER_NAME]
selenium-selenium-4.18.1/test/__init__.py 0000644 0001750 0001750 00000001423 14564764517 020240 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/runner/ 0000755 0001750 0001750 00000000000 14564764517 017440 5 ustar carsten carsten selenium-selenium-4.18.1/test/runner/run_pytest.py 0000644 0001750 0001750 00000002051 14564764517 022224 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
with open("pytest.ini", "w", encoding="utf-8") as ini_file:
ini_file.write("[pytest]\n")
ini_file.write("addopts = -r=a\n")
ini_file.write("rootdir = py\n")
ini_file.write("python_files = test_*.py *_tests.py\n")
raise SystemExit(pytest.main())
selenium-selenium-4.18.1/test/selenium/ 0000755 0001750 0001750 00000000000 14564764517 017750 5 ustar carsten carsten selenium-selenium-4.18.1/test/selenium/__init__.py 0000644 0001750 0001750 00000001423 14564764517 022061 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/selenium/webdriver/ 0000755 0001750 0001750 00000000000 14564764517 021741 5 ustar carsten carsten selenium-selenium-4.18.1/test/selenium/webdriver/common/ 0000755 0001750 0001750 00000000000 14564764517 023231 5 ustar carsten carsten selenium-selenium-4.18.1/test/selenium/webdriver/common/virtual_authenticator_tests.py 0000644 0001750 0001750 00000032251 14564764517 031450 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from base64 import b64decode
from base64 import urlsafe_b64decode
from typing import List
import pytest
from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.common.virtual_authenticator import Credential
from selenium.webdriver.common.virtual_authenticator import VirtualAuthenticatorOptions
from selenium.webdriver.remote.webdriver import WebDriver
# working Key
BASE64__ENCODED_PK = """
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
"""
REGISTER_CREDENTIAL = "registerCredential().then(arguments[arguments.length - 1]);"
GET_CREDENTIAL = """getCredential([{
"type": "public-key",
"id": Int8Array.from(arguments[0]),
}]).then(arguments[arguments.length - 1]);"""
def create_rk_enabled_u2f_authenticator(driver) -> WebDriver:
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key = True
driver.add_virtual_authenticator(options)
return driver
def create_rk_disabled_u2f_authenticator(driver) -> WebDriver:
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
options.has_resident_key = False
driver.add_virtual_authenticator(options)
return driver
def create_rk_enabled_ctap2_authenticator(driver) -> WebDriver:
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
options.has_resident_key = True
options.has_user_verification = True
options.is_user_verified = True
driver.add_virtual_authenticator(options)
return driver
def create_rk_disabled_ctap2_authenticator(driver) -> WebDriver:
options = VirtualAuthenticatorOptions()
options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
options.transport = VirtualAuthenticatorOptions.Transport.USB
options.has_resident_key = False
options.has_user_verification = True
options.is_user_verified = True
driver.add_virtual_authenticator(options)
return driver
def get_assertion_for(webdriver: WebDriver, credential_id: List[int]):
return webdriver.execute_async_script(GET_CREDENTIAL, credential_id)
def extract_id(response):
return response.get("credential", {}).get("id", "")
def extract_raw_id(response):
return response.get("credential", {}).get("rawId", "")
def not_allowed_error_in(response) -> bool:
return response.get("status", "").startswith("NotAllowedError")
# ---------------- TESTS ------------------------------------
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_add_and_remove_virtual_authenticator(driver, pages):
driver = create_rk_disabled_ctap2_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
result = driver.execute_async_script(REGISTER_CREDENTIAL)
assert result.get("status", "") == "OK"
assert get_assertion_for(driver, result["credential"]["rawId"]).get("status", "") == "OK"
assert driver.virtual_authenticator_id is not None
driver.remove_virtual_authenticator()
assert driver.virtual_authenticator_id is None
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_add_and_remove_non_resident_credentials(driver, pages):
driver = create_rk_disabled_ctap2_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
assert driver.virtual_authenticator_id is not None
credential = Credential.create_non_resident_credential(
bytearray({1, 2, 3, 4}),
"localhost",
b64decode(BASE64__ENCODED_PK),
0,
)
driver.add_credential(credential)
assert get_assertion_for(driver, [1, 2, 3, 4]).get("status", "") == "OK"
driver.remove_virtual_authenticator()
assert driver.virtual_authenticator_id is None
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_add_non_resident_credential_when_authenticator_uses_u2f_protocol(driver, pages):
driver = create_rk_disabled_u2f_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
base64_pk = """
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q
hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU
RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB
"""
credential = Credential.create_non_resident_credential(
bytearray({1, 2, 3, 4}),
"localhost",
urlsafe_b64decode(base64_pk),
0,
)
driver.add_credential(credential)
assert get_assertion_for(driver, [1, 2, 3, 4]).get("status", "") == "OK"
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver, pages):
driver = create_rk_enabled_u2f_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
base64_pk = """
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q
hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU
RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB
"""
credential = Credential.create_resident_credential(
bytearray({1, 2, 3, 4}),
"localhost",
bytearray({1}),
urlsafe_b64decode(base64_pk),
0,
)
with pytest.raises(InvalidArgumentException):
driver.add_credential(credential)
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_get_credentials(driver, pages):
driver = create_rk_enabled_ctap2_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
# Register a Resident Credential
response1 = driver.execute_async_script(
"""
registerCredential({authenticatorSelection: {requireResidentKey: true}})
.then(arguments[arguments.length - 1]);
"""
)
assert response1.get("status", "") == "OK"
# Register a Non-Resident Credential
response2 = driver.execute_async_script(REGISTER_CREDENTIAL)
assert response2.get("status", "") == "OK"
assert extract_id(response1) != extract_id(response2)
# Retrieve the two credentials
credentials = driver.get_credentials()
assert len(credentials) == 2
credential1, credential2 = None, None
for credential in credentials:
# Using startswith because there can be padding difference '==' or '=' in the end
if credential.id.startswith(extract_id(response1)):
credential1: Credential = credential
elif credential.id.startswith(extract_id(response2)):
credential2: Credential = credential
else:
assert False, "Unknown credential"
assert credential1.is_resident_credential, "Credential1 should be resident credential"
assert credential1.private_key is not None, "Credential1 should have private key"
assert credential2.is_resident_credential is False, "Credential2 should not be resident credential"
assert credential2.private_key is not None, "Credential2 should have private key"
assert credential2.sign_count == 1
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_remove_credential_by_raw_Id(driver, pages):
driver = create_rk_disabled_u2f_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
# register a credential
response = driver.execute_async_script(REGISTER_CREDENTIAL)
assert response.get("status", "") == "OK"
# remove the credential using array of bytes: rawId
raw_id = extract_raw_id(response)
driver.remove_credential(bytearray(raw_id))
# Trying to get the assertion should fail
response = get_assertion_for(driver, raw_id)
assert not_allowed_error_in(response), "Should have thrown a NotAllowedError"
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_remove_credential_by_b64_urlId(driver, pages):
driver = create_rk_disabled_u2f_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
# register a credential
response = driver.execute_async_script(REGISTER_CREDENTIAL)
assert response.get("status", "") == "OK"
# remove the credential using array of bytes: rawId
raw_id = extract_raw_id(response)
credential_id = extract_id(response)
driver.remove_credential(credential_id)
# Trying to get the assertion should fail
response = get_assertion_for(driver, raw_id)
assert not_allowed_error_in(response), "Should have thrown a NotAllowedError"
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_remove_all_credentials(driver, pages):
driver = create_rk_disabled_u2f_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
# Register 2 credentials
response1 = driver.execute_async_script(REGISTER_CREDENTIAL)
raw_id1 = response1["credential"]["rawId"]
response2 = driver.execute_async_script(REGISTER_CREDENTIAL)
raw_id2 = response2["credential"]["rawId"]
driver.remove_all_credentials()
response = driver.execute_async_script(
"""
getCredential([{
"type": "public-key",
"id": Int8Array.from(arguments[0]),
}, {
"type": "public-key",
"id": Int8Array.from(arguments[1]),
}]).then(arguments[arguments.length - 1]);
""",
raw_id1,
raw_id2,
)
assert not_allowed_error_in(response), "Should have thrown a NotAllowedError"
driver.remove_virtual_authenticator()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_set_user_verified(driver, pages):
driver = create_rk_enabled_ctap2_authenticator(driver)
driver.get(pages.url("virtual-authenticator.html", localhost=True))
# Register a credential requiring UV.
response = driver.execute_async_script(
"registerCredential({authenticatorSelection: {userVerification: 'required'}}).then(arguments[arguments.length - 1]);"
)
assert response.get("status", "") == "OK"
raw_id = response["credential"]["rawId"]
# Getting an assertion requiring user verification should succeed.
response = driver.execute_async_script(GET_CREDENTIAL, raw_id)
assert response.get("status", "") == "OK"
# Disable user verified.
driver.set_user_verified(False)
# Getting an assertion requiring user verification should fail.
response = driver.execute_async_script(GET_CREDENTIAL, raw_id)
assert not_allowed_error_in(response), "Should have thrown a NotAllowedError"
driver.remove_virtual_authenticator()
selenium-selenium-4.18.1/test/selenium/webdriver/common/executing_javascript_tests.py 0000644 0001750 0001750 00000024224 14564764517 031252 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
try:
str = unicode
except NameError:
pass
def test_should_be_able_to_execute_simple_javascript_and_return_astring(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return document.title")
assert isinstance(result, str), "The type of the result is %s" % type(result)
assert "XHTML Test Page" == result
def test_should_be_able_to_execute_simple_javascript_and_return_an_integer(driver, pages):
pages.load("nestedElements.html")
result = driver.execute_script("return document.getElementsByName('checky').length")
assert isinstance(result, int)
assert int(result) > 1
def test_should_be_able_to_execute_simple_javascript_and_return_aweb_element(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return document.getElementById('id1')")
assert result is not None
assert isinstance(result, WebElement)
assert "a" == result.tag_name.lower()
def test_should_be_able_to_execute_simple_javascript_and_return_alist_of_web_elements(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return document.querySelectorAll('div.navigation a')")
assert result is not None
assert isinstance(result, list)
assert all(isinstance(item, WebElement) for item in result)
assert all("a" == item.tag_name.lower() for item in result)
def test_should_be_able_to_execute_simple_javascript_and_return_web_elements_inside_alist(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return [document.body]")
assert result is not None
assert isinstance(result, list)
assert isinstance(result[0], WebElement)
def test_should_be_able_to_execute_simple_javascript_and_return_web_elements_inside_anested_list(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return [document.body, [document.getElementById('id1')]]")
assert result is not None
assert isinstance(result, list)
assert isinstance(result[0], WebElement)
assert isinstance(result[1][0], WebElement)
def test_should_be_able_to_execute_simple_javascript_and_return_web_elements_inside_adict(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return {el1: document.body}")
assert result is not None
assert isinstance(result, dict)
assert isinstance(result.get("el1"), WebElement)
def test_should_be_able_to_execute_simple_javascript_and_return_web_elements_inside_anested_dict(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return {el1: document.body, " "nested: {el2: document.getElementById('id1')}}")
assert result is not None
assert isinstance(result, dict)
assert isinstance(result.get("el1"), WebElement)
assert isinstance(result.get("nested").get("el2"), WebElement)
def test_should_be_able_to_execute_simple_javascript_and_return_web_elements_inside_alist_inside_adict(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return {el1: [document.body]}")
assert result is not None
assert isinstance(result, dict)
assert isinstance(result.get("el1"), list)
assert isinstance(result.get("el1")[0], WebElement)
def test_should_be_able_to_execute_simple_javascript_and_return_aboolean(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return true")
assert result is not None
assert isinstance(result, bool)
assert bool(result)
def test_should_be_able_to_execute_simple_javascript_and_astrings_array(driver, pages):
pages.load("javascriptPage.html")
expectedResult = []
expectedResult.append("zero")
expectedResult.append("one")
expectedResult.append("two")
result = driver.execute_script("return ['zero', 'one', 'two']")
assert expectedResult == result
def test_should_be_able_to_execute_simple_javascript_and_return_an_array(driver, pages):
pages.load("javascriptPage.html")
expectedResult = []
expectedResult.append("zero")
subList = []
subList.append(True)
subList.append(False)
expectedResult.append(subList)
result = driver.execute_script("return ['zero', [true, false]]")
assert result is not None
assert isinstance(result, list)
assert expectedResult == result
def test_passing_and_returning_an_int_should_return_awhole_number(driver, pages):
pages.load("javascriptPage.html")
expectedResult = 1
result = driver.execute_script("return arguments[0]", expectedResult)
assert isinstance(result, int)
assert expectedResult == result
def test_passing_and_returning_adouble_should_return_adecimal(driver, pages):
pages.load("javascriptPage.html")
expectedResult = 1.2
result = driver.execute_script("return arguments[0]", expectedResult)
assert isinstance(result, float)
assert expectedResult == result
def test_should_throw_an_exception_when_the_javascript_is_bad(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(WebDriverException):
driver.execute_script("return squiggle()")
def test_should_be_able_to_call_functions_defined_on_the_page(driver, pages):
pages.load("javascriptPage.html")
driver.execute_script("displayMessage('I like cheese')")
text = driver.find_element(By.ID, "result").text
assert "I like cheese" == text.strip()
def test_should_be_able_to_pass_astring_an_as_argument(driver, pages):
pages.load("javascriptPage.html")
value = driver.execute_script("return arguments[0] == 'fish' ? 'fish' : 'not fish'", "fish")
assert "fish" == value
def test_should_be_able_to_pass_aboolean_an_as_argument(driver, pages):
pages.load("javascriptPage.html")
value = bool(driver.execute_script("return arguments[0] == true", True))
assert value
def test_should_be_able_to_pass_anumber_an_as_argument(driver, pages):
pages.load("javascriptPage.html")
value = bool(driver.execute_script("return arguments[0] == 1 ? true : false", 1))
assert value
def test_should_be_able_to_pass_aweb_element_as_argument(driver, pages):
pages.load("javascriptPage.html")
button = driver.find_element(By.ID, "plainButton")
value = driver.execute_script(
"arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble']", button
)
assert "plainButton" == value
def test_should_be_able_to_pass_an_array_as_argument(driver, pages):
pages.load("javascriptPage.html")
array = ["zero", 1, True, 3.14159]
length = int(driver.execute_script("return arguments[0].length", array))
assert len(array) == length
def test_should_be_able_to_pass_acollection_as_argument(driver, pages):
pages.load("javascriptPage.html")
collection = []
collection.append("Cheddar")
collection.append("Brie")
collection.append(7)
length = int(driver.execute_script("return arguments[0].length", collection))
assert len(collection) == length
collection = []
collection.append("Gouda")
collection.append("Stilton")
collection.append("Stilton")
collection.append(True)
length = int(driver.execute_script("return arguments[0].length", collection))
assert len(collection) == length
def test_should_throw_an_exception_if_an_argument_is_not_valid(driver, pages):
pages.load("javascriptPage.html")
with pytest.raises(Exception):
driver.execute_script("return arguments[0]", driver)
def test_should_be_able_to_pass_in_more_than_one_argument(driver, pages):
pages.load("javascriptPage.html")
result = driver.execute_script("return arguments[0] + arguments[1]", "one", "two")
assert "onetwo" == result
def test_javascript_string_handling_should_work_as_expected(driver, pages):
pages.load("javascriptPage.html")
value = driver.execute_script("return ''")
assert "" == value
value = driver.execute_script("return undefined")
assert value is None
value = driver.execute_script("return ' '")
assert " " == value
def test_should_be_able_to_create_apersistent_value(driver, pages):
pages.load("formPage.html")
driver.execute_script("document.alerts = []")
driver.execute_script("document.alerts.push('hello world')")
text = driver.execute_script("return document.alerts.shift()")
assert "hello world" == text
def test_can_pass_adictionary_as_aparameter(driver, pages):
pages.load("simpleTest.html")
nums = [1, 2]
args = {"bar": "test", "foo": nums}
res = driver.execute_script("return arguments[0]['foo'][1]", args)
assert 2 == res
def test_can_pass_anone(driver, pages):
pages.load("simpleTest.html")
res = driver.execute_script("return arguments[0] === null", None)
assert res
def test_can_return_a_const(driver, pages):
pages.load("simpleTest.html")
res = driver.execute_script("const cheese='cheese'; return cheese")
assert res == "cheese"
def test_can_return_a_const_in_a_page(driver, pages):
pages.load("const_js.html")
res = driver.execute_script("return makeMeA('sandwich');")
assert res == "cheese sandwich"
@pytest.mark.xfail_remote
@pytest.mark.xfail_firefox
def test_can_return_global_const(driver, pages):
pages.load("const_js.html")
# cheese is a variable with "cheese" in it
res = driver.execute_script("return cheese")
assert res == "cheese"
selenium-selenium-4.18.1/test/selenium/webdriver/common/utils.py 0000644 0001750 0001750 00000002021 14564764517 024736 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
def convert_cookie_to_json(cookie):
cookie_dict = {}
for key, value in cookie.items():
if key == "expires":
cookie_dict["expiry"] = int(value) * 1000
else:
cookie_dict[key] = value
return cookie_dict
selenium-selenium-4.18.1/test/selenium/webdriver/common/stale_reference_tests.py 0000644 0001750 0001750 00000003517 14564764517 030161 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
def test_old_page(driver, pages):
pages.load("simpleTest.html")
elem = driver.find_element(by=By.ID, value="links")
pages.load("xhtmlTest.html")
msg = r"\/errors#stale-element-reference-exception"
with pytest.raises(StaleElementReferenceException, match=msg):
elem.click()
@pytest.mark.xfail_safari
def test_should_not_crash_when_calling_get_size_on_an_obsolete_element(driver, pages):
pages.load("simpleTest.html")
elem = driver.find_element(by=By.ID, value="links")
pages.load("xhtmlTest.html")
with pytest.raises(StaleElementReferenceException):
elem.size
@pytest.mark.xfail_safari
def test_should_not_crash_when_querying_the_attribute_of_astale_element(driver, pages):
pages.load("xhtmlTest.html")
heading = driver.find_element(by=By.XPATH, value="//h1")
pages.load("simpleTest.html")
with pytest.raises(StaleElementReferenceException):
heading.get_attribute("class")
selenium-selenium-4.18.1/test/selenium/webdriver/common/timeout_tests.py 0000644 0001750 0001750 00000004362 14564764517 026520 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.timeouts import Timeouts
def test_should_create_timeouts_object():
implicit_wait = 10
page_load = 10
script = 10
timeouts = Timeouts(implicit_wait=implicit_wait, page_load=page_load, script=script)
assert implicit_wait == timeouts.implicit_wait
assert page_load == timeouts.page_load
assert script == timeouts.script
def test_should_error_if_implicit_wait_isnt_a_number():
with pytest.raises(TypeError):
Timeouts(implicit_wait="abc")
timeout = Timeouts(implicit_wait=0)
with pytest.raises(TypeError):
timeout.implicit_wait = "abc"
def test_should_error_if_page_load_isnt_a_number():
with pytest.raises(TypeError):
Timeouts(page_load="abc")
timeout = Timeouts(page_load=0)
with pytest.raises(TypeError):
timeout.page_load = "abc"
def test_should_error_if_script_isnt_a_number():
with pytest.raises(TypeError):
Timeouts(script="abc")
timeout = Timeouts(script=0)
with pytest.raises(TypeError):
timeout.script = "abc"
def test_should_get_timeouts_without_setting_them(driver):
results = driver.timeouts
assert results.implicit_wait == 0
assert results.page_load == 300
assert results.script == 30
def test_should_set_and_get_timeouts_on_remote_end(driver):
timeout = Timeouts(implicit_wait=10)
driver.timeouts = timeout
result = driver.timeouts
assert result.implicit_wait == timeout.implicit_wait
selenium-selenium-4.18.1/test/selenium/webdriver/common/select_element_handling_tests.py 0000644 0001750 0001750 00000006745 14564764517 031675 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.webdriver.common.by import By
def test_should_be_possible_to_deselect_asingle_option_from_aselect_which_allows_multiple_choice(driver, pages):
pages.load("formPage.html")
multiSelect = driver.find_element(By.ID, "multi")
options = multiSelect.find_elements(By.TAG_NAME, "option")
option = options[0]
assert option.is_selected() is True
option.click()
assert option.is_selected() is False
option.click()
assert option.is_selected() is True
option = options[2]
assert option.is_selected() is True
def test_should_be_able_to_change_the_selected_option_in_aselec(driver, pages):
pages.load("formPage.html")
selectBox = driver.find_element(By.XPATH, "//select[@name='selectomatic']")
options = selectBox.find_elements(By.TAG_NAME, "option")
one = options[0]
two = options[1]
assert one.is_selected() is True
assert two.is_selected() is False
two.click()
assert one.is_selected() is False
assert two.is_selected() is True
def test_should_be_able_to_select_more_than_one_option_from_aselect_which_allows_multiple_choice(driver, pages):
pages.load("formPage.html")
multiSelect = driver.find_element(By.ID, "multi")
options = multiSelect.find_elements(By.TAG_NAME, "option")
for option in options:
if not option.is_selected():
option.click()
for i in range(len(options)):
option = options[i]
assert option.is_selected() is True
def test_should_select_first_option_if_none_is_selected(driver, pages):
pages.load("formPage.html")
selectBox = driver.find_element(By.XPATH, "//select[@name='select-default']")
options = selectBox.find_elements(By.TAG_NAME, "option")
one = options[0]
two = options[1]
assert one.is_selected() is True
assert two.is_selected() is False
two.click()
assert one.is_selected() is False
assert two.is_selected() is True
def test_can_select_elements_in_opt_group(driver, pages):
pages.load("selectPage.html")
element = driver.find_element(By.ID, "two-in-group")
element.click()
assert element.is_selected() is True
def test_can_get_value_from_option_via_attribute_when_attribute_doesnt_exist(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.CSS_SELECTOR, "select[name='select-default'] option")
assert element.get_attribute("value") == "One"
element = driver.find_element(By.ID, "blankOption")
assert element.get_attribute("value") == ""
def test_can_get_value_from_option_via_attribute_when_attribute_is_empty_string(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "optionEmptyValueSet")
assert element.get_attribute("value") == ""
selenium-selenium-4.18.1/test/selenium/webdriver/common/repr_tests.py 0000644 0001750 0001750 00000003042 14564764517 025774 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
def test_should_implement_repr_for_web_driver(driver):
driver_repr = repr(driver)
assert type(driver).__name__ in driver_repr
assert driver.session_id in driver_repr
def test_should_implement_repr_for_web_element(driver, pages):
pages.load("simpleTest.html")
elem = driver.find_element(By.ID, "validImgTag")
elem_repr = repr(elem)
assert type(elem).__name__ in elem_repr
assert driver.session_id in elem_repr
assert elem._id in elem_repr
def test_should_implement_repr_for_wait(driver):
wait = WebDriverWait(driver, 30)
wait_repr = repr(wait)
assert type(wait).__name__ in wait_repr
assert driver.session_id in wait_repr
selenium-selenium-4.18.1/test/selenium/webdriver/common/test_file2.txt 0000644 0001750 0001750 00000000033 14564764517 026026 0 ustar carsten carsten lorem ipsum dolor sit amet
selenium-selenium-4.18.1/test/selenium/webdriver/common/webdriverwait_tests.py 0000644 0001750 0001750 00000037217 14564764517 027715 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import time
import pytest
from selenium.common.exceptions import InvalidElementStateException
from selenium.common.exceptions import InvalidSelectorException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def throw_sere(driver):
raise StaleElementReferenceException("test")
def test_should_fail_with_invalid_selector_exception(driver, pages):
pages.load("dynamic.html")
with pytest.raises(InvalidSelectorException):
WebDriverWait(driver, 0.7).until(EC.presence_of_element_located((By.XPATH, "//*[contains(@id,'something'")))
def test_should_explicitly_wait_for_a_single_element(driver, pages):
pages.load("dynamic.html")
add = driver.find_element(By.ID, "adder")
add.click()
WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.ID, "box0"))
) # All is well if this doesn't throw.
def test_should_still_fail_to_find_an_element_with_explicit_wait(driver, pages):
pages.load("dynamic.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.presence_of_element_located((By.ID, "box0")))
def test_should_explicitly_wait_until_at_least_one_element_is_found_when_searching_for_many(driver, pages):
pages.load("dynamic.html")
add = driver.find_element(By.ID, "adder")
add.click()
add.click()
elements = WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "redbox")))
assert len(elements) >= 1
def test_should_fail_to_find_elements_when_explicit_waiting(driver, pages):
pages.load("dynamic.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "redbox")))
def test_should_wait_until_at_least_one_visible_elements_is_found_when_searching_for_many(driver, pages):
pages.load("hidden_partially.html")
add_visible = driver.find_element(By.ID, "addVisible")
add_hidden = driver.find_element(By.ID, "addHidden")
add_visible.click()
add_visible.click()
add_hidden.click()
class wait_for_two_elements:
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
elements = [element for element in driver.find_elements(*self.locator) if EC._element_if_visible(element)]
return elements if len(elements) == 2 else False
elements = WebDriverWait(driver, 3).until(wait_for_two_elements((By.CLASS_NAME, "redbox")))
assert len(elements) == 2
def test_should_fail_to_find_visible_elements_when_explicit_waiting(driver, pages):
pages.load("hidden_partially.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "redbox")))
def test_should_wait_until_all_visible_elements_are_found_when_searching_for_many(driver, pages):
pages.load("hidden_partially.html")
add_visible = driver.find_element(By.ID, "addVisible")
add_visible.click()
add_visible.click()
elements = WebDriverWait(driver, 3).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "redbox")))
assert len(elements) == 2
def test_should_fail_if_not_all_elements_are_visible(driver, pages):
pages.load("hidden_partially.html")
add_visible = driver.find_element(By.ID, "addVisible")
add_hidden = driver.find_element(By.ID, "addHidden")
add_visible.click()
add_hidden.click()
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "redbox")))
def test_should_wait_only_as_long_as_timeout_specified_when_implicit_waits_are_set(driver, pages):
pages.load("dynamic.html")
driver.implicitly_wait(0.5)
start = time.time()
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.ID, "box0")))
assert time.time() - start < 1.5
def test_should_wait_at_least_once(driver, pages):
pages.load("simpleTest.html")
elements = WebDriverWait(driver, 0).until(lambda d: d.find_elements(By.TAG_NAME, "h1"))
assert len(elements) >= 1
def test_wait_until_not_returns_if_evaluates_to_false(driver, pages):
assert WebDriverWait(driver, 1).until_not(lambda d: False) is False
def test_wait_should_still_fail_if_produce_ignored_exception(driver, pages):
ignored = (InvalidElementStateException, StaleElementReferenceException)
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1, 0.7, ignored_exceptions=ignored).until(throw_sere)
def test_wait_should_still_fail_if_produce_child_of_ignored_exception(driver, pages):
ignored = WebDriverException
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1, 0.7, ignored_exceptions=ignored).until(throw_sere)
def test_wait_until_not_should_not_fail_if_produce_ignored_exception(driver, pages):
ignored = (InvalidElementStateException, StaleElementReferenceException)
assert WebDriverWait(driver, 1, 0.7, ignored_exceptions=ignored).until_not(throw_sere)
def test_expected_condition_title_is(driver, pages):
pages.load("blank.html")
WebDriverWait(driver, 1).until(EC.title_is("blank"))
driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")
WebDriverWait(driver, 2).until(EC.title_is("not blank"))
assert driver.title == "not blank"
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.title_is("blank"))
def test_expected_condition_title_contains(driver, pages):
pages.load("blank.html")
driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")
WebDriverWait(driver, 2).until(EC.title_contains("not"))
assert driver.title == "not blank"
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.title_contains("blanket"))
@pytest.mark.xfail_safari
def test_expected_condition_visibility_of_element_located(driver, pages):
pages.load("javascriptPage.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.visibility_of_element_located((By.ID, "clickToHide")))
driver.find_element(By.ID, "clickToShow").click()
element = WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.ID, "clickToHide")))
assert element.is_displayed() is True
@pytest.mark.xfail_safari
def test_expected_condition_visibility_of(driver, pages):
pages.load("javascriptPage.html")
hidden = driver.find_element(By.ID, "clickToHide")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.visibility_of(hidden))
driver.find_element(By.ID, "clickToShow").click()
element = WebDriverWait(driver, 5).until(EC.visibility_of(hidden))
assert element.is_displayed() is True
def test_expected_condition_text_to_be_present_in_element(driver, pages):
pages.load("booleanAttributes.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, "unwrappable"), "Expected"))
driver.execute_script(
"setTimeout(function(){var el = document.getElementById('unwrappable'); el.textContent = el.innerText = 'Unwrappable Expected text'}, 200)"
)
WebDriverWait(driver, 2).until(EC.text_to_be_present_in_element((By.ID, "unwrappable"), "Expected"))
assert "Unwrappable Expected text" == driver.find_element(By.ID, "unwrappable").text
def test_expected_condition_text_to_be_present_in_element_value(driver, pages):
pages.load("booleanAttributes.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, "inputRequired"), "Expected"))
driver.execute_script(
"setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)"
)
WebDriverWait(driver, 2).until(EC.text_to_be_present_in_element_value((By.ID, "inputRequired"), "Expected"))
assert "Example Expected text" == driver.find_element(By.ID, "inputRequired").get_attribute("value")
def test_expected_condition_text_to_be_present_in_element_attribute(driver, pages):
pages.load("booleanAttributes.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1).until(
EC.text_to_be_present_in_element_attribute((By.ID, "inputRequired"), "value", "Expected")
)
driver.execute_script(
"setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)"
)
WebDriverWait(driver, 2).until(
EC.text_to_be_present_in_element_attribute((By.ID, "inputRequired"), "value", "Expected")
)
assert "Example Expected text" == driver.find_element(By.ID, "inputRequired").get_attribute("value")
def test_expected_condition_frame_to_be_available_and_switch_to_it_by_locator(driver, pages):
pages.load("blank.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "myFrame")))
driver.execute_script(
"setTimeout(function(){var f = document.createElement('iframe'); f.id='myFrame'; f.src = '"
+ pages.url("iframeWithAlert.html")
+ "'; document.body.appendChild(f)}, 200)"
)
WebDriverWait(driver, 2).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "myFrame")))
assert "click me" == driver.find_element(By.ID, "alertInFrame").text
def test_expected_condition_invisiblity_of_element(driver, pages):
pages.load("javascriptPage.html")
target = driver.find_element(By.ID, "clickToHide")
driver.execute_script("delayedShowHide(0, true)")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.invisibility_of_element(target))
driver.execute_script("delayedShowHide(200, false)")
element = WebDriverWait(driver, 2).until(EC.invisibility_of_element(target))
assert element.is_displayed() is False
assert target == element
def test_expected_condition_invisiblity_of_element_located(driver, pages):
pages.load("javascriptPage.html")
driver.execute_script("delayedShowHide(0, true)")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.invisibility_of_element_located((By.ID, "clickToHide")))
driver.execute_script("delayedShowHide(200, false)")
element = WebDriverWait(driver, 2).until(EC.invisibility_of_element_located((By.ID, "clickToHide")))
assert element.is_displayed() is False
@pytest.mark.xfail_safari
def test_expected_condition_element_to_be_clickable(driver, pages):
pages.load("javascriptPage.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.element_to_be_clickable((By.ID, "clickToHide")))
driver.execute_script("delayedShowHide(200, true)")
WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.ID, "clickToHide")))
element = driver.find_element(By.ID, "clickToHide")
element.click()
WebDriverWait(driver, 4.5).until(EC.invisibility_of_element_located((By.ID, "clickToHide")))
assert element.is_displayed() is False
def test_expected_condition_staleness_of(driver, pages):
pages.load("dynamicallyModifiedPage.html")
element = driver.find_element(By.ID, "element-to-remove")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.staleness_of(element))
driver.find_element(By.ID, "buttonDelete").click()
assert "element" == element.text
WebDriverWait(driver, 2).until(EC.staleness_of(element))
with pytest.raises(StaleElementReferenceException):
element.text
def test_expected_condition_element_to_be_selected(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "checky")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.element_to_be_selected(element))
driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")
WebDriverWait(driver, 2).until(EC.element_to_be_selected(element))
assert element.is_selected() is True
def test_expected_condition_element_located_to_be_selected(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "checky")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.element_located_to_be_selected((By.ID, "checky")))
driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")
WebDriverWait(driver, 2).until(EC.element_located_to_be_selected((By.ID, "checky")))
assert element.is_selected() is True
def test_expected_condition_element_selection_state_to_be(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "checky")
WebDriverWait(driver, 0.7).until(EC.element_selection_state_to_be(element, False))
assert element.is_selected() is False
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.element_selection_state_to_be(element, True))
driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")
WebDriverWait(driver, 2).until(EC.element_selection_state_to_be(element, True))
assert element.is_selected() is True
def test_expected_condition_element_located_selection_state_to_be(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "checky")
WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, "checky"), False))
assert element.is_selected() is False
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, "checky"), True))
driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")
WebDriverWait(driver, 2).until(EC.element_located_selection_state_to_be((By.ID, "checky"), True))
assert element.is_selected() is True
def test_expected_condition_alert_is_present(driver, pages):
pages.load("blank.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 0.7).until(EC.alert_is_present())
driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")
WebDriverWait(driver, 2).until(EC.alert_is_present())
alert = driver.switch_to.alert
assert "alerty" == alert.text
alert.dismiss()
def test_expected_condition_attribute_to_be_include_in_element(driver, pages):
pages.load("booleanAttributes.html")
with pytest.raises(TimeoutException):
WebDriverWait(driver, 1).until(EC.element_attribute_to_include((By.ID, "inputRequired"), "test"))
value = WebDriverWait(driver, 2).until(EC.element_attribute_to_include((By.ID, "inputRequired"), "value"))
assert value is not None
selenium-selenium-4.18.1/test/selenium/webdriver/common/w3c_interaction_tests.py 0000644 0001750 0001750 00000031266 14564764517 030130 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.common.actions.wheel_input import WheelInput
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
def test_should_be_able_to_get_pointer_and_keyboard_inputs(driver, pages):
actions = ActionBuilder(driver)
pointers = actions.pointer_inputs
keyboards = actions.key_inputs
assert pointers is not None
assert keyboards is not None
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_sending_keys_to_active_element_with_modifier(driver, pages):
pages.load("formPage.html")
e = driver.find_element(By.ID, "working")
e.click()
actions = ActionBuilder(driver)
key_action = actions.key_action
key_action.key_down(Keys.SHIFT).send_keys("abc").key_up(Keys.SHIFT)
actions.perform()
assert "ABC" == e.get_attribute("value")
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_create_pause_action_on_keyboard(driver, pages):
# If we don't get an error and takes less than 3 seconds to run, we are good
import datetime
start = datetime.datetime.now()
actions1 = ActionBuilder(driver)
key_actions = actions1.key_action
key_actions.pause(1)
actions1.perform()
finish = datetime.datetime.now()
assert (finish - start).seconds <= 3
# Add a filler step
actions2 = ActionBuilder(driver)
key_action = actions2.key_action
key_action.pause()
actions2.perform()
def test_can_create_pause_action_on_pointer(driver, pages):
# If we don't get an error and takes less than 3 seconds to run, we are good
import datetime
start = datetime.datetime.now()
actions1 = ActionBuilder(driver)
key_actions = actions1.pointer_action
key_actions.pause(1)
actions1.perform()
finish = datetime.datetime.now()
assert (finish - start).seconds <= 3
# Add a filler step
actions2 = ActionBuilder(driver)
key_action = actions2.pointer_action
key_action.pause()
actions2.perform()
def test_can_clear_actions(driver, pages):
actions = ActionBuilder(driver)
actions.clear_actions()
def test_move_and_click(driver, pages):
pages.load("javascriptPage.html")
toClick = driver.find_element(By.ID, "clickField")
actions = ActionBuilder(driver)
pointer = actions.pointer_action
pointer.move_to(toClick).click()
actions.perform()
assert "Clicked" == toClick.get_attribute("value")
def test_drag_and_drop(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
element_available_timeout = 15
wait = WebDriverWait(driver, element_available_timeout)
pages.load("droppableItems.html")
wait.until(lambda dr: _is_element_available(driver, "draggable"))
if not _is_element_available(driver, "draggable"):
raise AssertionError("Could not find draggable element after 15 seconds.")
toDrag = driver.find_element(By.ID, "draggable")
dropInto = driver.find_element(By.ID, "droppable")
actions = ActionBuilder(driver)
pointer = actions.pointer_action
pointer.click_and_hold(toDrag).move_to(dropInto).release()
actions.perform()
dropInto = driver.find_element(By.ID, "droppable")
text = dropInto.find_element(By.TAG_NAME, "p").text
assert "Dropped!" == text
def test_context_click(driver, pages):
pages.load("javascriptPage.html")
toContextClick = driver.find_element(By.ID, "doubleClickField")
actions = ActionBuilder(driver)
pointer = actions.pointer_action
pointer.context_click(toContextClick)
actions.perform()
assert "ContextClicked" == toContextClick.get_attribute("value")
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote(reason="Fails on Travis")
@pytest.mark.xfail_chrome(reason="Fails on Travis")
def test_double_click(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("javascriptPage.html")
toDoubleClick = driver.find_element(By.ID, "doubleClickField")
actions = ActionBuilder(driver)
pointer = actions.pointer_action
pointer.double_click(toDoubleClick)
actions.perform()
assert "DoubleClicked" == toDoubleClick.get_attribute("value")
def test_dragging_element_with_mouse_moves_it_to_another_list(driver, pages):
_perform_drag_and_drop_with_mouse(driver, pages)
dragInto = driver.find_element(By.ID, "sortable1")
assert 6 == len(dragInto.find_elements(By.TAG_NAME, "li"))
def test_dragging_element_with_mouse_fires_events(driver, pages):
_perform_drag_and_drop_with_mouse(driver, pages)
dragReporter = driver.find_element(By.ID, "dragging_reports")
assert "Nothing happened. DragOut DropIn RightItem 3" == dragReporter.text
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_pen_pointer_properties(driver, pages):
pages.load("pointerActionsPage.html")
pointerArea = driver.find_element(By.CSS_SELECTOR, "#pointerArea")
pointer_input = PointerInput(interaction.POINTER_PEN, "pen")
actions = ActionBuilder(driver, mouse=pointer_input)
center = _get_inview_center(pointerArea.rect, _get_viewport_rect(driver))
actions.pointer_action.move_to(pointerArea).pointer_down(pressure=0.36, tilt_x=-72, tilt_y=9, twist=86).move_to(
pointerArea, x=5, y=10
).pointer_up().move_to(pointerArea, x=5, y=10)
actions.perform()
events = _get_events(driver)
assert events[3]["type"] == "pointerdown"
assert events[3]["pageX"] == pytest.approx(center["x"], abs=1.0)
assert events[3]["pageY"] == pytest.approx(center["y"], abs=1.0)
assert events[3]["target"] == "pointerArea"
assert events[3]["pointerType"] == "pen"
# The default value of width and height for mouse and pen inputs is 1
assert round(events[3]["width"], 2) == 1
assert round(events[3]["height"], 2) == 1
assert round(events[3]["pressure"], 2) == 0.36
assert events[3]["tiltX"] == -72
assert events[3]["tiltY"] == 9
assert events[3]["twist"] == 86
assert events[6]["type"] == "pointermove"
assert events[6]["target"] == "pointerArea"
assert events[6]["pointerType"] == "pen"
assert round(events[6]["width"], 2) == 1
assert round(events[6]["height"], 2) == 1
# The default value of pressure for all inputs is 0.5, other properties are 0
assert round(events[6]["pressure"], 2) == 0.5
assert events[6]["tiltX"] == 0
assert events[6]["tiltY"] == 0
assert events[6]["twist"] == 0
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_touch_pointer_properties(driver, pages):
pages.load("pointerActionsPage.html")
pointerArea = driver.find_element(By.CSS_SELECTOR, "#pointerArea")
center = _get_inview_center(pointerArea.rect, _get_viewport_rect(driver))
touch_input = PointerInput(interaction.POINTER_TOUCH, "touch")
touch_chain = ActionBuilder(driver, mouse=touch_input)
touch_chain.pointer_action.move_to(pointerArea).pointer_down(
width=23, height=31, pressure=0.78, tilt_x=21, tilt_y=-8, twist=355
).move_to(
pointerArea, x=10, y=10, width=39, height=35, pressure=0.91, tilt_x=-19, tilt_y=62, twist=345
).pointer_up().move_to(
pointerArea, x=15, y=15
)
touch_chain.perform()
events = _get_events(driver)
assert len(events) == 7
event_types = [e["type"] for e in events]
assert [
"pointerover",
"pointerenter",
"pointerdown",
"pointermove",
"pointerup",
"pointerout",
"pointerleave",
] == event_types
assert events[2]["type"] == "pointerdown"
assert events[2]["pageX"] == pytest.approx(center["x"], abs=1.0)
assert events[2]["pageY"] == pytest.approx(center["y"], abs=1.0)
assert events[2]["target"] == "pointerArea"
assert events[2]["pointerType"] == "touch"
assert round(events[2]["width"], 2) == 23
assert round(events[2]["height"], 2) == 31
assert round(events[2]["pressure"], 2) == 0.78
assert events[2]["tiltX"] == 21
assert events[2]["tiltY"] == -8
assert events[2]["twist"] == 355
assert events[3]["type"] == "pointermove"
assert events[3]["pageX"] == pytest.approx(center["x"] + 10, abs=1.0)
assert events[3]["pageY"] == pytest.approx(center["y"] + 10, abs=1.0)
assert events[3]["target"] == "pointerArea"
assert events[3]["pointerType"] == "touch"
assert round(events[3]["width"], 2) == 39
assert round(events[3]["height"], 2) == 35
assert round(events[3]["pressure"], 2) == 0.91
assert events[3]["tiltX"] == -19
assert events[3]["tiltY"] == 62
assert events[3]["twist"] == 345
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_scroll_mouse_wheel(driver, pages):
pages.load("scrollingPage.html")
driver.execute_script("document.scrollingElement.scrollTop = 0")
scrollable = driver.find_element(By.CSS_SELECTOR, "#scrollable")
wheel_input = WheelInput("wheel")
actions = ActionBuilder(driver, wheel=wheel_input)
actions.wheel_action.scroll(0, 0, 5, 10, 0, scrollable)
actions.perform()
events = _get_events(driver)
assert len(events) == 1
assert events[0]["type"] == "wheel"
assert events[0]["deltaX"] >= 5
assert events[0]["deltaY"] >= 10
assert events[0]["deltaZ"] == 0
assert events[0]["target"] == "scrollContent"
def _perform_drag_and_drop_with_mouse(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("draggableLists.html")
dragReporter = driver.find_element(By.ID, "dragging_reports")
toDrag = driver.find_element(By.ID, "rightitem-3")
dragInto = driver.find_element(By.ID, "sortable1")
actions = ActionBuilder(driver)
pointer = actions.pointer_action
pointer.click_and_hold(toDrag).move_to(driver.find_element(By.ID, "leftitem-4")).move_to(dragInto).release()
assert "Nothing happened." == dragReporter.text
actions.perform()
assert "Nothing happened. DragOut" in dragReporter.text
def _is_element_available(driver, id):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
try:
driver.find_element(By.ID, id)
return True
except Exception:
return False
def _get_events(driver):
"""Return list of key events recorded in the test_keys_page fixture."""
events = driver.execute_script("return allEvents.events;") or []
# `key` values in `allEvents` may be escaped (see `escapeSurrogateHalf` in
# test_keys_wdspec.html), so this converts them back into unicode literals.
for e in events:
# example: turn "U+d83d" (6 chars) into u"\ud83d" (1 char)
if "key" in e and e["key"].startswith("U+"):
key = e["key"]
hex_suffix = key[key.index("+") + 1 :]
e["key"] = chr(int(hex_suffix, 16))
# WebKit sets code as 'Unidentified' for unidentified key codes, but
# tests expect ''.
if "code" in e and e["code"] == "Unidentified":
e["code"] = ""
return events
def _get_inview_center(elem_rect, viewport_rect):
x = {
"left": max(0, min(elem_rect["x"], elem_rect["x"] + elem_rect["width"])),
"right": min(viewport_rect["width"], max(elem_rect["x"], elem_rect["x"] + elem_rect["width"])),
}
y = {
"top": max(0, min(elem_rect["y"], elem_rect["y"] + elem_rect["height"])),
"bottom": min(viewport_rect["height"], max(elem_rect["y"], elem_rect["y"] + elem_rect["height"])),
}
return {
"x": (x["left"] + x["right"]) / 2,
"y": (y["top"] + y["bottom"]) / 2,
}
def _get_viewport_rect(driver):
return driver.execute_script(
"""
return {
height: window.innerHeight || document.documentElement.clientHeight,
width: window.innerWidth || document.documentElement.clientWidth,
};
"""
)
selenium-selenium-4.18.1/test/selenium/webdriver/common/click_scrolling_tests.py 0000644 0001750 0001750 00000015735 14564764517 030201 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def test_clicking_on_anchor_scrolls_page(driver, pages):
scrollScript = """var pageY;
if (typeof(window.pageYOffset) == 'number') {
pageY = window.pageYOffset;
} else {
pageY = document.documentElement.scrollTop;
}
return pageY;"""
pages.load("macbeth.html")
driver.find_element(By.PARTIAL_LINK_TEXT, "last speech").click()
yOffset = driver.execute_script(scrollScript)
# Focusing on to click, but not actually following,
# the link will scroll it in to view, which is a few pixels further than 0
assert yOffset > 300
def test_should_scroll_to_click_on_an_element_hidden_by_overflow(driver, pages):
pages.load("click_out_of_bounds_overflow.html")
link = driver.find_element(By.ID, "link")
try:
link.click()
except MoveTargetOutOfBoundsException as e:
AssertionError("Should not be out of bounds: %s" % e.msg)
def test_should_be_able_to_click_on_an_element_hidden_by_overflow(driver, pages):
pages.load("scroll.html")
link = driver.find_element(By.ID, "line8")
# This used to throw a MoveTargetOutOfBoundsException - we don't expect it to
link.click()
assert "line8" == driver.find_element(By.ID, "clicked").text
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_should_be_able_to_click_on_an_element_hidden_by_double_overflow(driver, pages):
pages.load("scrolling_tests/page_with_double_overflow_auto.html")
driver.find_element(By.ID, "link").click()
WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))
def test_should_be_able_to_click_on_an_element_hidden_by_yoverflow(driver, pages):
pages.load("scrolling_tests/page_with_y_overflow_auto.html")
driver.find_element(By.ID, "link").click()
WebDriverWait(driver, 3).until(EC.title_is("Clicked Successfully!"))
def test_should_not_scroll_overflow_elements_which_are_visible(driver, pages):
pages.load("scroll2.html")
list = driver.find_element(By.TAG_NAME, "ul")
item = list.find_element(By.ID, "desired")
item.click()
yOffset = driver.execute_script("return arguments[0].scrollTop", list)
assert 0 == yOffset, "Should not have scrolled"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_should_not_scroll_if_already_scrolled_and_element_is_in_view(driver, pages):
pages.load("scroll3.html")
driver.find_element(By.ID, "button2").click()
scrollTop = get_scroll_top(driver)
driver.find_element(By.ID, "button1").click()
assert scrollTop == get_scroll_top(driver)
def test_should_be_able_to_click_radio_button_scrolled_into_view(driver, pages):
pages.load("scroll4.html")
driver.find_element(By.ID, "radio").click()
# If we don't throw, we're good
@pytest.mark.xfail_safari
def test_should_scroll_overflow_elements_if_click_point_is_out_of_view_but_element_is_in_view(driver, pages):
pages.load("scroll5.html")
driver.find_element(By.ID, "inner").click()
assert "clicked" == driver.find_element(By.ID, "clicked").text
@pytest.mark.xfail_firefox(reason="https://github.com/w3c/webdriver/issues/408")
@pytest.mark.xfail_remote(reason="https://github.com/w3c/webdriver/issues/408")
@pytest.mark.xfail_safari
def test_should_be_able_to_click_element_in_aframe_that_is_out_of_view(driver, pages):
pages.load("scrolling_tests/page_with_frame_out_of_view.html")
driver.switch_to.frame(driver.find_element(By.NAME, "frame"))
element = driver.find_element(By.NAME, "checkbox")
element.click()
assert element.is_selected()
def test_should_be_able_to_click_element_that_is_out_of_view_in_aframe(driver, pages):
pages.load("scrolling_tests/page_with_scrolling_frame.html")
driver.switch_to.frame(driver.find_element(By.NAME, "scrolling_frame"))
element = driver.find_element(By.NAME, "scroll_checkbox")
element.click()
assert element.is_selected()
def test_should_not_be_able_to_click_element_that_is_out_of_view_in_anon_scrollable_frame(driver, pages):
pages.load("scrolling_tests/page_with_non_scrolling_frame.html")
driver.switch_to.frame("scrolling_frame")
element = driver.find_element(By.NAME, "scroll_checkbox")
element.click()
# TODO we should assert that the click was unsuccessful
@pytest.mark.xfail_safari
def test_should_be_able_to_click_element_that_is_out_of_view_in_aframe_that_is_out_of_view(driver, pages):
pages.load("scrolling_tests/page_with_scrolling_frame_out_of_view.html")
driver.switch_to.frame(driver.find_element(By.NAME, "scrolling_frame"))
element = driver.find_element(By.NAME, "scroll_checkbox")
element.click()
assert element.is_selected()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_chrome
@pytest.mark.xfail_remote
def test_should_be_able_to_click_element_that_is_out_of_view_in_anested_frame(driver, pages):
pages.load("scrolling_tests/page_with_nested_scrolling_frames.html")
driver.switch_to.frame(driver.find_element(By.NAME, "scrolling_frame"))
driver.switch_to.frame(driver.find_element(By.NAME, "nested_scrolling_frame"))
element = driver.find_element(By.NAME, "scroll_checkbox")
element.click()
assert element.is_selected()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_chrome
@pytest.mark.xfail_remote
def test_should_be_able_to_click_element_that_is_out_of_view_in_anested_frame_that_is_out_of_view(driver, pages):
pages.load("scrolling_tests/page_with_nested_scrolling_frames_out_of_view.html")
driver.switch_to.frame(driver.find_element(By.NAME, "scrolling_frame"))
driver.switch_to.frame(driver.find_element(By.NAME, "nested_scrolling_frame"))
element = driver.find_element(By.NAME, "scroll_checkbox")
element.click()
assert element.is_selected()
def test_should_not_scroll_when_getting_element_size(driver, pages):
pages.load("scroll3.html")
scrollTop = get_scroll_top(driver)
driver.find_element(By.ID, "button1").size
assert scrollTop == get_scroll_top(driver)
def get_scroll_top(driver):
return driver.execute_script("return document.body.scrollTop")
selenium-selenium-4.18.1/test/selenium/webdriver/common/element_aria_label_tests.py 0000644 0001750 0001750 00000002172 14564764517 030613 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_return_accessible_name(driver):
driver.get("data:text/html,
Level 1 Header
")
header1 = driver.find_element(By.CSS_SELECTOR, "h1")
assert header1.accessible_name == "Level 1 Header"
selenium-selenium-4.18.1/test/selenium/webdriver/common/quit_tests.py 0000644 0001750 0001750 00000001677 14564764517 026022 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
@pytest.mark.no_driver_after_test
def test_quit(driver, pages):
driver.quit()
with pytest.raises(Exception):
pages.load("simpleTest.html")
selenium-selenium-4.18.1/test/selenium/webdriver/common/interactions_tests.py 0000644 0001750 0001750 00000032124 14564764517 027531 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Tests for advanced user interactions."""
import pytest
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
def perform_drag_and_drop_with_mouse(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("draggableLists.html")
dragReporter = driver.find_element(By.ID, "dragging_reports")
toDrag = driver.find_element(By.ID, "rightitem-3")
dragInto = driver.find_element(By.ID, "sortable1")
holdItem = ActionChains(driver).click_and_hold(toDrag)
moveToSpecificItem = ActionChains(driver).move_to_element(driver.find_element(By.ID, "leftitem-4"))
moveToOtherList = ActionChains(driver).move_to_element(dragInto)
drop = ActionChains(driver).release(dragInto)
assert "Nothing happened." == dragReporter.text
holdItem.perform()
moveToSpecificItem.perform()
moveToOtherList.perform()
assert "Nothing happened. DragOut" == dragReporter.text
drop.perform()
@pytest.mark.xfail_safari
def test_dragging_element_with_mouse_moves_it_to_another_list(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
perform_drag_and_drop_with_mouse(driver, pages)
dragInto = driver.find_element(By.ID, "sortable1")
assert 6 == len(dragInto.find_elements(By.TAG_NAME, "li"))
@pytest.mark.xfail_safari
def test_dragging_element_with_mouse_fires_events(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
perform_drag_and_drop_with_mouse(driver, pages)
dragReporter = driver.find_element(By.ID, "dragging_reports")
assert "Nothing happened. DragOut DropIn RightItem 3" == dragReporter.text
def _is_element_available(driver, id):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
try:
driver.find_element(By.ID, id)
return True
except Exception:
return False
@pytest.mark.xfail_safari
def test_drag_and_drop(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
element_available_timeout = 15
wait = WebDriverWait(driver, element_available_timeout)
pages.load("droppableItems.html")
wait.until(lambda dr: _is_element_available(driver, "draggable"))
if not _is_element_available(driver, "draggable"):
raise AssertionError("Could not find draggable element after 15 seconds.")
toDrag = driver.find_element(By.ID, "draggable")
dropInto = driver.find_element(By.ID, "droppable")
holdDrag = ActionChains(driver).click_and_hold(toDrag)
move = ActionChains(driver).move_to_element(dropInto)
drop = ActionChains(driver).release(dropInto)
holdDrag.perform()
move.perform()
drop.perform()
dropInto = driver.find_element(By.ID, "droppable")
text = dropInto.find_element(By.TAG_NAME, "p").text
assert "Dropped!" == text
@pytest.mark.xfail_safari
def test_double_click(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("javascriptPage.html")
toDoubleClick = driver.find_element(By.ID, "doubleClickField")
dblClick = ActionChains(driver).double_click(toDoubleClick)
dblClick.perform()
assert "DoubleClicked" == toDoubleClick.get_attribute("value")
def test_context_click(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("javascriptPage.html")
toContextClick = driver.find_element(By.ID, "doubleClickField")
contextClick = ActionChains(driver).context_click(toContextClick)
contextClick.perform()
assert "ContextClicked" == toContextClick.get_attribute("value")
def test_move_and_click(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("javascriptPage.html")
toClick = driver.find_element(By.ID, "clickField")
click = ActionChains(driver).move_to_element(toClick).click()
click.perform()
assert "Clicked" == toClick.get_attribute("value")
def test_cannot_move_to_anull_locator(driver, pages):
"""Copied from org.openqa.selenium.interactions.TestBasicMouseInterface."""
pages.load("javascriptPage.html")
with pytest.raises(AttributeError):
move = ActionChains(driver).move_to_element(None)
move.perform()
@pytest.mark.xfail_safari
def test_clicking_on_form_elements(driver, pages):
"""Copied from org.openqa.selenium.interactions.CombinedInputActionsTest."""
pages.load("formSelectionPage.html")
options = driver.find_elements(By.TAG_NAME, "option")
selectThreeOptions = (
ActionChains(driver).click(options[1]).key_down(Keys.SHIFT).click(options[3]).key_up(Keys.SHIFT)
)
selectThreeOptions.perform()
showButton = driver.find_element(By.NAME, "showselected")
showButton.click()
resultElement = driver.find_element(By.ID, "result")
assert "roquefort parmigiano cheddar" == resultElement.text
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
def test_selecting_multiple_items(driver, pages):
"""Copied from org.openqa.selenium.interactions.CombinedInputActionsTest."""
pages.load("selectableItems.html")
reportingElement = driver.find_element(By.ID, "infodiv")
assert "no info" == reportingElement.text
listItems = driver.find_elements(By.TAG_NAME, "li")
selectThreeItems = (
ActionChains(driver)
.key_down(Keys.CONTROL)
.click(listItems[1])
.click(listItems[3])
.click(listItems[5])
.key_up(Keys.CONTROL)
)
selectThreeItems.perform()
assert "#item2 #item4 #item6" == reportingElement.text
# Now click on another element, make sure that's the only one selected.
actionsBuilder = ActionChains(driver)
actionsBuilder.click(listItems[6]).perform()
assert "#item7" == reportingElement.text
@pytest.mark.xfail_safari
def test_sending_keys_to_active_element_with_modifier(driver, pages):
pages.load("formPage.html")
e = driver.find_element(By.ID, "working")
e.click()
ActionChains(driver).key_down(Keys.SHIFT).send_keys("abc").key_up(Keys.SHIFT).perform()
assert "ABC" == e.get_attribute("value")
def test_sending_keys_to_element(driver, pages):
pages.load("formPage.html")
e = driver.find_element(By.ID, "working")
ActionChains(driver).send_keys_to_element(e, "abc").perform()
assert "abc" == e.get_attribute("value")
def test_can_send_keys_between_clicks(driver, pages):
"""
For W3C, ensures that the correct number of pauses are given to the other
input device.
"""
pages.load("javascriptPage.html")
keyup = driver.find_element(By.ID, "keyUp")
keydown = driver.find_element(By.ID, "keyDown")
ActionChains(driver).click(keyup).send_keys("foobar").click(keydown).perform()
assert "foobar" == keyup.get_attribute("value")
def test_can_reset_interactions(driver):
actions = ActionChains(driver)
actions.click()
actions.key_down("A")
assert all(len(device.actions) > 0 for device in actions.w3c_actions.devices if device.type != interaction.WHEEL)
actions.reset_actions()
assert all(len(device.actions) == 0 for device in actions.w3c_actions.devices)
def test_can_pause(driver, pages):
from time import time
pages.load("javascriptPage.html")
pause_time = 2
toClick = driver.find_element(By.ID, "clickField")
toDoubleClick = driver.find_element(By.ID, "doubleClickField")
pause = ActionChains(driver).click(toClick).pause(pause_time).click(toDoubleClick)
start = time()
pause.perform()
end = time()
assert pause_time < end - start
assert "Clicked" == toClick.get_attribute("value")
assert "Clicked" == toDoubleClick.get_attribute("value")
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_scroll_to_element(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")
iframe = driver.find_element(By.TAG_NAME, "iframe")
assert not _in_viewport(driver, iframe)
ActionChains(driver).scroll_to_element(iframe).perform()
assert _in_viewport(driver, iframe)
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_scroll_from_element_by_amount(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")
iframe = driver.find_element(By.TAG_NAME, "iframe")
scroll_origin = ScrollOrigin.from_element(iframe)
ActionChains(driver).scroll_from_origin(scroll_origin, 0, 200).pause(0.2).perform()
driver.switch_to.frame(iframe)
checkbox = driver.find_element(By.NAME, "scroll_checkbox")
assert _in_viewport(driver, checkbox)
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_scroll_from_element_with_offset_by_amount(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")
footer = driver.find_element(By.TAG_NAME, "footer")
scroll_origin = ScrollOrigin.from_element(footer, 0, -50)
ActionChains(driver).scroll_from_origin(scroll_origin, 0, 200).pause(0.2).perform()
iframe = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(iframe)
checkbox = driver.find_element(By.NAME, "scroll_checkbox")
assert _in_viewport(driver, checkbox)
def test_errors_when_element_offset_not_in_viewport(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")
footer = driver.find_element(By.TAG_NAME, "footer")
scroll_origin = ScrollOrigin.from_element(footer, 0, 50)
with pytest.raises(MoveTargetOutOfBoundsException):
ActionChains(driver).scroll_from_origin(scroll_origin, 0, 200).pause(0.2).perform()
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_scroll_from_viewport_by_amount(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")
footer = driver.find_element(By.TAG_NAME, "footer")
delta_y = footer.rect["y"]
ActionChains(driver).scroll_by_amount(0, delta_y).pause(0.2).perform()
assert _in_viewport(driver, footer)
def test_can_scroll_from_viewport_with_offset_by_amount(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame.html")
scroll_origin = ScrollOrigin.from_viewport(10, 10)
ActionChains(driver).scroll_from_origin(scroll_origin, 0, 200).pause(0.2).perform()
iframe = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(iframe)
checkbox = driver.find_element(By.NAME, "scroll_checkbox")
assert _in_viewport(driver, checkbox)
def test_errors_when_origin_offset_not_in_viewport(driver, pages):
pages.load("scrolling_tests/frame_with_nested_scrolling_frame.html")
scroll_origin = ScrollOrigin.from_viewport(-10, -10)
with pytest.raises(MoveTargetOutOfBoundsException):
ActionChains(driver).scroll_from_origin(scroll_origin, 0, 200).pause(0.2).perform()
def _get_events(driver):
"""Return list of key events recorded in the test_keys_page fixture."""
events = driver.execute_script("return allEvents.events;") or []
# `key` values in `allEvents` may be escaped (see `escapeSurrogateHalf` in
# test_keys_wdspec.html), so this converts them back into unicode literals.
for e in events:
# example: turn "U+d83d" (6 chars) into u"\ud83d" (1 char)
if "key" in e and e["key"].startswith("U+"):
key = e["key"]
hex_suffix = key[key.index("+") + 1 :]
e["key"] = chr(int(hex_suffix, 16))
# WebKit sets code as 'Unidentified' for unidentified key codes, but
# tests expect ''.
if "code" in e and e["code"] == "Unidentified":
e["code"] = ""
return events
def _in_viewport(driver, element):
script = (
"for(var e=arguments[0],f=e.offsetTop,t=e.offsetLeft,o=e.offsetWidth,n=e.offsetHeight;\n"
"e.offsetParent;)f+=(e=e.offsetParent).offsetTop,t+=e.offsetLeft;\n"
"return f\n"
"window.pageYOffset&&t+o>window.pageXOffset"
)
return driver.execute_script(script, element)
selenium-selenium-4.18.1/test/selenium/webdriver/common/executing_async_javascript_tests.py 0000644 0001750 0001750 00000020776 14564764517 032457 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
@pytest.fixture(autouse=True)
def reset_timeouts(driver):
driver.set_script_timeout(5)
yield
driver.set_script_timeout(30)
def test_should_not_timeout_if_callback_invoked_immediately(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1](123);")
assert isinstance(result, int)
assert 123 == result
def test_should_be_able_to_return_javascript_primitives_from_async_scripts_neither_none_nor_undefined(driver, pages):
pages.load("ajaxy_page.html")
assert 123 == driver.execute_async_script("arguments[arguments.length - 1](123);")
assert "abc" == driver.execute_async_script("arguments[arguments.length - 1]('abc');")
assert not bool(driver.execute_async_script("arguments[arguments.length - 1](false);"))
assert bool(driver.execute_async_script("arguments[arguments.length - 1](true);"))
def test_should_be_able_to_return_javascript_primitives_from_async_scripts_null_and_undefined(driver, pages):
pages.load("ajaxy_page.html")
assert driver.execute_async_script("arguments[arguments.length - 1](null)") is None
assert driver.execute_async_script("arguments[arguments.length - 1]()") is None
def test_should_be_able_to_return_an_array_literal_from_an_async_script(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1]([]);")
assert "Expected not to be null!", result is not None
assert isinstance(result, list)
assert len(result) == 0
def test_should_be_able_to_return_an_array_object_from_an_async_script(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1](new Array());")
assert "Expected not to be null!", result is not None
assert isinstance(result, list)
assert len(result) == 0
def test_should_be_able_to_return_arrays_of_primitives_from_async_scripts(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);")
assert result is not None
assert isinstance(result, list)
assert not bool(result.pop())
assert bool(result.pop())
assert "abc" == result.pop()
assert 123 == result.pop()
assert result.pop() is None
assert len(result) == 0
def test_should_be_able_to_return_web_elements_from_async_scripts(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1](document.body);")
assert isinstance(result, WebElement)
assert "body" == result.tag_name.lower()
@pytest.mark.xfail_safari
@pytest.mark.xfail_chrome(reason="https://bugs.chromium.org/p/chromedriver/issues/detail?id=4525")
def test_should_be_able_to_return_arrays_of_web_elements_from_async_scripts(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script("arguments[arguments.length - 1]([document.body, document.body]);")
assert result is not None
assert isinstance(result, list)
list_ = result
assert 2 == len(list_)
assert isinstance(list_[0], WebElement)
assert isinstance(list_[1], WebElement)
assert "body" == list_[0].tag_name
# assert list_[0] == list_[1]
def test_should_timeout_if_script_does_not_invoke_callback(driver, pages):
pages.load("ajaxy_page.html")
with pytest.raises(TimeoutException):
# Script is expected to be async and explicitly callback, so this should timeout.
driver.execute_async_script("return 1 + 2;")
def test_should_timeout_if_script_does_not_invoke_callback_with_azero_timeout(driver, pages):
pages.load("ajaxy_page.html")
with pytest.raises(TimeoutException):
driver.execute_async_script("window.setTimeout(function() {}, 0);")
def test_should_not_timeout_if_script_callsback_inside_azero_timeout(driver, pages):
pages.load("ajaxy_page.html")
driver.execute_async_script(
"""var callback = arguments[arguments.length - 1];
window.setTimeout(function() { callback(123); }, 0)"""
)
def test_should_timeout_if_script_does_not_invoke_callback_with_long_timeout(driver, pages):
driver.set_script_timeout(0.5)
pages.load("ajaxy_page.html")
with pytest.raises(TimeoutException):
driver.execute_async_script(
"""var callback = arguments[arguments.length - 1];
window.setTimeout(callback, 1500);"""
)
def test_should_detect_page_loads_while_waiting_on_an_async_script_and_return_an_error(driver, pages):
pages.load("ajaxy_page.html")
driver.set_script_timeout(0.1)
with pytest.raises(WebDriverException):
url = pages.url("dynamic.html")
driver.execute_async_script(f"window.location = '{url}';")
def test_should_catch_errors_when_executing_initial_script(driver, pages):
pages.load("ajaxy_page.html")
with pytest.raises(WebDriverException):
driver.execute_async_script("throw Error('you should catch this!');")
def test_should_be_able_to_execute_asynchronous_scripts(driver, pages):
pages.load("ajaxy_page.html")
typer = driver.find_element(by=By.NAME, value="typer")
typer.send_keys("bob")
assert "bob" == typer.get_attribute("value")
driver.find_element(by=By.ID, value="red").click()
driver.find_element(by=By.NAME, value="submit").click()
assert 1 == len(
driver.find_elements(by=By.TAG_NAME, value="div")
), "There should only be 1 DIV at this point, which is used for the butter message"
driver.set_script_timeout(10)
text = driver.execute_async_script(
"""var callback = arguments[arguments.length - 1];
window.registerListener(arguments[arguments.length - 1]);"""
)
assert "bob" == text
assert "" == typer.get_attribute("value")
assert 2 == len(
driver.find_elements(by=By.TAG_NAME, value="div")
), "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)"
def test_should_be_able_to_pass_multiple_arguments_to_async_scripts(driver, pages):
pages.load("ajaxy_page.html")
result = driver.execute_async_script(
"""
arguments[arguments.length - 1](arguments[0] + arguments[1]);""",
1,
2,
)
assert 3 == result
# TODO DavidBurns Disabled till Java WebServer is used
# def test_should_be_able_to_make_xmlhttp_requests_and_wait_for_the_response(driver, pages):
# script = """
# var url = arguments[0];
# var callback = arguments[arguments.length - 1];
# // Adapted from http://www.quirksmode.org/js/xmlhttp.html
# var XMLHttpFactories = [
# function () return new XMLHttpRequest(),
# function () return new ActiveXObject('Msxml2.XMLHTTP'),
# function () return new ActiveXObject('Msxml3.XMLHTTP'),
# function () return new ActiveXObject('Microsoft.XMLHTTP')
# ];
# var xhr = false;
# while (!xhr && XMLHttpFactories.length)
# try{
# xhr = XMLHttpFactories.shift().call();
# }catch (e)
#
# if (!xhr) throw Error('unable to create XHR object');
# xhr.open('GET', url, true);
# xhr.onreadystatechange = function()
# if (xhr.readyState == 4) callback(xhr.responseText);
#
# xhr.send('');""" # empty string to stop firefox 3 from choking
#
# pages.load("ajaxy_page.html")
# driver.set_script_timeout(3)
# response = driver.execute_async_script(script, pages.sleepingPage + "?time=2")
# htm = "DoneSlept for 2s"
# assert response.strip() == htm
selenium-selenium-4.18.1/test/selenium/webdriver/common/window_switching_tests.py 0000644 0001750 0001750 00000016476 14564764517 030431 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchWindowException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.window import WindowTypes
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
@pytest.fixture(autouse=True)
def close_windows(driver):
main_windows_handle = driver.current_window_handle
yield
from urllib import request as url_request
URLError = url_request.URLError
try:
window_handles = driver.window_handles
except URLError:
return
for handle in window_handles:
if handle != main_windows_handle:
driver.switch_to.window(handle)
driver.close()
driver.switch_to.window(main_windows_handle)
def test_should_switch_focus_to_anew_window_when_it_is_opened_and_not_stop_future_operations(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open new window").click()
assert driver.title == "XHTML Test Page"
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
assert driver.title == "We Arrive Here"
pages.load("iframes.html")
handle = driver.current_window_handle
driver.find_element(By.ID, "iframe_page_heading")
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
assert driver.current_window_handle == handle
def test_can_switch_to_window_by_name(driver, pages):
pages.load("xhtmlTest.html")
handles = driver.window_handles
driver.find_element(By.LINK_TEXT, "Open new window").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
driver.switch_to.window("result")
assert driver.title == "We Arrive Here"
def test_should_throw_no_such_window_exception(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchWindowException):
driver.switch_to.window("invalid name")
@pytest.mark.xfail_safari
def test_should_throw_no_such_window_exception_on_an_attempt_to_get_its_handle(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.LINK_TEXT, "Open new window").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
driver.close()
with pytest.raises(NoSuchWindowException):
driver.current_window_handle
@pytest.mark.xfail_ie
def test_should_throw_no_such_window_exception_on_any_operation_if_awindow_is_closed(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.LINK_TEXT, "Open new window").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
driver.close()
with pytest.raises(NoSuchWindowException):
driver.title
with pytest.raises(NoSuchWindowException):
driver.find_element(By.TAG_NAME, "body")
@pytest.mark.xfail_ie
@pytest.mark.xfail_safari
def test_should_throw_no_such_window_exception_on_any_element_operation_if_awindow_is_closed(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.LINK_TEXT, "Open new window").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
element = driver.find_element(By.TAG_NAME, "body")
driver.close()
with pytest.raises(NoSuchWindowException):
element.text
def test_clicking_on_abutton_that_closes_an_open_window_does_not_cause_the_browser_to_hang(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.NAME, "windowThree").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
driver.find_element(By.ID, "close").click()
driver.switch_to.window(current)
driver.find_element(By.ID, "linkId")
@pytest.mark.xfail_safari
def test_can_call_get_window_handles_after_closing_awindow(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.NAME, "windowThree").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
driver.find_element(By.ID, "close").click()
WebDriverWait(driver, 3).until(EC.number_of_windows_to_be(1))
def test_can_obtain_awindow_handle(driver, pages):
pages.load("xhtmlTest.html")
currentHandle = driver.current_window_handle
assert currentHandle is not None
def test_failing_to_switch_to_awindow_leaves_the_current_window_as_is(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
with pytest.raises(NoSuchWindowException):
driver.switch_to.window("I will never exist")
new_handle = driver.current_window_handle
assert current == new_handle
@pytest.mark.xfail_safari
def test_that_accessing_finding_an_element_after_window_is_closed_and_haventswitched_doesnt_crash(driver, pages):
pages.load("xhtmlTest.html")
current = driver.current_window_handle
handles = driver.window_handles
driver.find_element(By.NAME, "windowThree").click()
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
handles = driver.window_handles
handles.remove(current)
driver.switch_to.window(handles[0])
with pytest.raises(WebDriverException):
driver.find_element(By.ID, "close").click()
all_handles = driver.window_handles
assert 1 == len(all_handles)
driver.find_element(By.ID, "close")
driver.switch_to.window(current)
@pytest.mark.xfail_ie
def test_should_be_able_to_create_anew_window(driver, pages):
original_handle = driver.current_window_handle
driver.switch_to.new_window(WindowTypes.TAB)
new_handle = driver.current_window_handle
driver.close()
driver.switch_to.window(original_handle)
assert new_handle != original_handle
selenium-selenium-4.18.1/test/selenium/webdriver/common/selenium_manager_tests.py 0000644 0001750 0001750 00000006643 14564764517 030351 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from unittest.mock import Mock
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.selenium_manager import SeleniumManager
def test_browser_version_is_used_for_sm(mocker):
import subprocess
mock_run = mocker.patch("subprocess.run")
mocked_result = Mock()
mocked_result.configure_mock(
**{
"stdout.decode.return_value": '{"result": {"driver_path": "driver", "browser_path": "browser"}, "logs": []}',
"returncode": 0,
}
)
mock_run.return_value = mocked_result
options = Options()
options.capabilities["browserName"] = "chrome"
options.browser_version = "110"
_ = SeleniumManager().driver_location(options)
args, kwargs = subprocess.run.call_args
assert "--browser-version" in args[0]
assert "110" in args[0]
def test_browser_path_is_used_for_sm(mocker):
import subprocess
mock_run = mocker.patch("subprocess.run")
mocked_result = Mock()
mocked_result.configure_mock(
**{
"stdout.decode.return_value": '{"result": {"driver_path": "driver", "browser_path": "browser"}, "logs": []}',
"returncode": 0,
}
)
mock_run.return_value = mocked_result
options = Options()
options.capabilities["browserName"] = "chrome"
options.binary_location = "/opt/bin/browser-bin"
_ = SeleniumManager().driver_location(options)
args, kwargs = subprocess.run.call_args
assert "--browser-path" in args[0]
assert "/opt/bin/browser-bin" in args[0]
def test_proxy_is_used_for_sm(mocker):
import subprocess
mock_run = mocker.patch("subprocess.run")
mocked_result = Mock()
mocked_result.configure_mock(
**{
"stdout.decode.return_value": '{"result": {"driver_path": "driver", "browser_path": "browser"}, "logs": []}',
"returncode": 0,
}
)
mock_run.return_value = mocked_result
options = Options()
options.capabilities["browserName"] = "chrome"
proxy = Proxy()
proxy.http_proxy = "http-proxy"
options.proxy = proxy
_ = SeleniumManager().driver_location(options)
args, kwargs = subprocess.run.call_args
assert "--proxy" in args[0]
assert "http-proxy" in args[0]
def test_stderr_is_propagated_to_exception_messages():
msg = r"Unsuccessful command executed:.*\n.* 'Invalid browser name: foo'.*"
with pytest.raises(WebDriverException, match=msg):
manager = SeleniumManager()
binary = manager.get_binary()
_ = manager.run([str(binary), "--browser", "foo"])
selenium-selenium-4.18.1/test/selenium/webdriver/common/page_load_timeout_tests.py 0000644 0001750 0001750 00000002652 14564764517 030513 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
@pytest.fixture(autouse=True)
def reset_timeouts(driver):
yield
driver.set_page_load_timeout(300)
def test_should_timeout_on_page_load_taking_too_long(driver, pages):
driver.set_page_load_timeout(0.01)
with pytest.raises(TimeoutException):
pages.load("simpleTest.html")
@pytest.mark.xfail_safari
def test_click_should_timeout(driver, pages):
pages.load("simpleTest.html")
driver.set_page_load_timeout(0.01)
with pytest.raises(TimeoutException):
driver.find_element(By.ID, "multilinelink").click()
selenium-selenium-4.18.1/test/selenium/webdriver/common/script_pinning_tests.py 0000644 0001750 0001750 00000005123 14564764517 030054 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import re
import pytest
from selenium.common.exceptions import JavascriptException
from selenium.webdriver.remote.script_key import ScriptKey
def test_should_allow_script_pinning(driver, pages):
pages.load("simpleTest.html")
driver.pinned_scripts = {}
script_key = driver.pin_script("return 'i like cheese';")
result = driver.execute_script(script_key)
assert result == "i like cheese"
def test_should_allow_pinned_scripts_to_take_arguments(driver, pages):
pages.load("simpleTest.html")
driver.pinned_scripts = {}
hello = driver.pin_script("return arguments[0]")
result = driver.execute_script(hello, "cheese")
assert result == "cheese"
def test_should_list_all_pinned_scripts(driver, pages):
pages.load("simpleTest.html")
driver.pinned_scripts = {}
expected = []
expected.append(driver.pin_script("return arguments[0];").id)
expected.append(driver.pin_script("return 'cheese';").id)
expected.append(driver.pin_script("return 42;").id)
result = driver.get_pinned_scripts()
assert expected == result
def test_should_allow_scripts_to_be_unpinned(driver, pages):
pages.load("simpleTest.html")
driver.pinned_scripts = {}
cheese = driver.pin_script("return 'cheese';")
driver.unpin(cheese)
results = driver.get_pinned_scripts()
assert cheese not in results
def test_calling_unpinned_script_causes_error(driver, pages):
pages.load("simpleTest.html")
cheese = driver.pin_script("return 'brie';")
driver.unpin(cheese)
with pytest.raises(JavascriptException):
driver.execute_script(cheese)
def test_unpinning_non_existing_script_raises(driver, pages):
pages.load("simpleTest.html")
with pytest.raises(KeyError, match=re.escape(r"No script with key: ScriptKey(id=1) existed in {}")):
driver.unpin(ScriptKey(1))
selenium-selenium-4.18.1/test/selenium/webdriver/common/__init__.py 0000644 0001750 0001750 00000001423 14564764517 025342 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
selenium-selenium-4.18.1/test/selenium/webdriver/common/conftest.py 0000644 0001750 0001750 00000001735 14564764517 025436 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
def pytest_generate_tests(metafunc):
if "driver" in metafunc.fixturenames and metafunc.config.option.drivers:
metafunc.parametrize("driver", metafunc.config.option.drivers, indirect=True)
selenium-selenium-4.18.1/test/selenium/webdriver/common/takes_screenshots_tests.py 0000644 0001750 0001750 00000003001 14564764517 030546 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import base64
import imghdr
import pytest
from selenium.webdriver.common.by import By
def test_get_screenshot_as_base64(driver, pages):
pages.load("simpleTest.html")
result = base64.b64decode(driver.get_screenshot_as_base64())
assert imghdr.what("", result) == "png"
def test_get_screenshot_as_png(driver, pages):
pages.load("simpleTest.html")
result = driver.get_screenshot_as_png()
assert imghdr.what("", result) == "png"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_get_element_screenshot(driver, pages):
pages.load("simpleTest.html")
element = driver.find_element(By.ID, "multiline")
result = base64.b64decode(element.screenshot_as_base64)
assert imghdr.what("", result) == "png"
selenium-selenium-4.18.1/test/selenium/webdriver/common/proxy_tests.py 0000644 0001750 0001750 00000011124 14564764517 026205 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.options import ArgOptions
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType
MANUAL_PROXY = {
"httpProxy": "some.url:1234",
"ftpProxy": "ftp.proxy",
"noProxy": "localhost, foo.localhost",
"sslProxy": "ssl.proxy:1234",
"socksProxy": "socks.proxy:65555",
"socksUsername": "test",
"socksPassword": "test",
"socksVersion": 5,
}
PAC_PROXY = {
"proxyAutoconfigUrl": "http://pac.url:1234",
}
AUTODETECT_PROXY = {
"autodetect": True,
}
def test_can_add_manual_proxy_to_options():
proxy = Proxy()
proxy.http_proxy = MANUAL_PROXY["httpProxy"]
proxy.ftp_proxy = MANUAL_PROXY["ftpProxy"]
proxy.no_proxy = MANUAL_PROXY["noProxy"]
proxy.sslProxy = MANUAL_PROXY["sslProxy"]
proxy.socksProxy = MANUAL_PROXY["socksProxy"]
proxy.socksUsername = MANUAL_PROXY["socksUsername"]
proxy.socksPassword = MANUAL_PROXY["socksPassword"]
proxy.socksVersion = MANUAL_PROXY["socksVersion"]
options = ArgOptions()
options.proxy = proxy
proxy_capabilities = MANUAL_PROXY.copy()
proxy_capabilities["proxyType"] = "manual"
assert proxy_capabilities == options.to_capabilities().get("proxy")
def test_can_add_autodetect_proxy_to_options():
proxy = Proxy()
proxy.auto_detect = AUTODETECT_PROXY["autodetect"]
options = ArgOptions()
options.proxy = proxy
proxy_capabilities = AUTODETECT_PROXY.copy()
proxy_capabilities["proxyType"] = "autodetect"
assert proxy_capabilities == options.to_capabilities().get("proxy")
def test_can_add_pacproxy_to_options():
proxy = Proxy()
proxy.proxy_autoconfig_url = PAC_PROXY["proxyAutoconfigUrl"]
options = ArgOptions()
options.proxy = proxy
proxy_capabilities = PAC_PROXY.copy()
proxy_capabilities["proxyType"] = "pac"
assert proxy_capabilities == options.to_capabilities().get("proxy")
def test_can_not_change_initialized_proxy_type():
proxy = Proxy(raw={"proxyType": "direct"})
with pytest.raises(Exception):
proxy.proxy_type = ProxyType.SYSTEM
proxy = Proxy(raw={"proxyType": ProxyType.DIRECT})
with pytest.raises(Exception):
proxy.proxy_type = ProxyType.SYSTEM
def test_can_init_manual_proxy():
proxy = Proxy(raw=MANUAL_PROXY)
assert ProxyType.MANUAL == proxy.proxy_type
assert MANUAL_PROXY["httpProxy"] == proxy.http_proxy
assert MANUAL_PROXY["ftpProxy"] == proxy.ftp_proxy
assert MANUAL_PROXY["noProxy"] == proxy.no_proxy
assert MANUAL_PROXY["sslProxy"] == proxy.sslProxy
assert MANUAL_PROXY["socksProxy"] == proxy.socksProxy
assert MANUAL_PROXY["socksUsername"] == proxy.socksUsername
assert MANUAL_PROXY["socksPassword"] == proxy.socksPassword
assert MANUAL_PROXY["socksVersion"] == proxy.socksVersion
def test_can_init_autodetect_proxy():
proxy = Proxy(raw=AUTODETECT_PROXY)
assert ProxyType.AUTODETECT == proxy.proxy_type
assert AUTODETECT_PROXY["autodetect"] == proxy.auto_detect
def test_can_init_pacproxy():
proxy = Proxy(raw=PAC_PROXY)
assert ProxyType.PAC == proxy.proxy_type
assert PAC_PROXY["proxyAutoconfigUrl"] == proxy.proxy_autoconfig_url
def test_can_init_empty_proxy():
proxy = Proxy()
assert ProxyType.UNSPECIFIED == proxy.proxy_type
assert "" == proxy.http_proxy
assert "" == proxy.ftp_proxy
assert "" == proxy.no_proxy
assert "" == proxy.sslProxy
assert "" == proxy.socksProxy
assert "" == proxy.socksUsername
assert "" == proxy.socksPassword
assert proxy.auto_detect is False
assert "" == proxy.proxy_autoconfig_url
assert proxy.socks_version is None
options = ArgOptions()
options.proxy = proxy
proxy_capabilities = {}
proxy_capabilities["proxyType"] = "unspecified"
assert proxy_capabilities == options.to_capabilities().get("proxy")
selenium-selenium-4.18.1/test/selenium/webdriver/common/click_tests.py 0000644 0001750 0001750 00000002641 14564764517 026115 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
@pytest.fixture(autouse=True)
def loadPage(pages):
pages.load("clicks.html")
def test_can_click_on_alink_that_overflows_and_follow_it(driver):
driver.find_element(By.ID, "overflowLink").click()
WebDriverWait(driver, 3).until(EC.title_is("XHTML Test Page"))
def test_clicking_alink_made_up_of_numbers_is_handled_correctly(driver):
driver.find_element(By.LINK_TEXT, "333333").click()
WebDriverWait(driver, 3).until(EC.title_is("XHTML Test Page"))
selenium-selenium-4.18.1/test/selenium/webdriver/common/implicit_waits_tests.py 0000644 0001750 0001750 00000005144 14564764517 030052 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
def test_should_implicitly_wait_for_asingle_element(driver, pages):
pages.load("dynamic.html")
add = driver.find_element(By.ID, "adder")
driver.implicitly_wait(3)
add.click()
driver.find_element(By.ID, "box0") # All is well if this doesn't throw.
def test_should_still_fail_to_find_an_element_when_implicit_waits_are_enabled(driver, pages):
pages.load("dynamic.html")
driver.implicitly_wait(0.5)
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "box0")
def test_should_return_after_first_attempt_to_find_one_after_disabling_implicit_waits(driver, pages):
pages.load("dynamic.html")
driver.implicitly_wait(3)
driver.implicitly_wait(0)
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "box0")
def test_should_implicitly_wait_until_at_least_one_element_is_found_when_searching_for_many(driver, pages):
pages.load("dynamic.html")
add = driver.find_element(By.ID, "adder")
driver.implicitly_wait(2)
add.click()
add.click()
elements = driver.find_elements(By.CLASS_NAME, "redbox")
assert len(elements) >= 1
def test_should_still_fail_to_find_an_elemenst_when_implicit_waits_are_enabled(driver, pages):
pages.load("dynamic.html")
driver.implicitly_wait(0.5)
elements = driver.find_elements(By.CLASS_NAME, "redbox")
assert 0 == len(elements)
def test_should_return_after_first_attempt_to_find_many_after_disabling_implicit_waits(driver, pages):
pages.load("dynamic.html")
add = driver.find_element(By.ID, "adder")
driver.implicitly_wait(1.1)
driver.implicitly_wait(0)
add.click()
elements = driver.find_elements(By.CLASS_NAME, "redbox")
assert 0 == len(elements)
selenium-selenium-4.18.1/test/selenium/webdriver/common/api_example_tests.py 0000644 0001750 0001750 00000022566 14564764517 027324 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def test_get_title(driver, pages):
pages.load("simpleTest.html")
title = driver.title
assert "Hello WebDriver" == title
def test_get_current_url(driver, pages, webserver):
pages.load("simpleTest.html")
url = driver.current_url
assert webserver.where_is("simpleTest.html") == url
def test_find_element_by_xpath(driver, pages):
pages.load("simpleTest.html")
elem = driver.find_element(By.XPATH, "//h1")
assert "Heading" == elem.text
def test_find_element_by_xpath_throw_no_such_element_exception(driver, pages):
pages.load("simpleTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.XPATH, "//h4")
def test_find_elements_by_xpath(driver, pages):
pages.load("nestedElements.html")
elems = driver.find_elements(By.XPATH, "//option")
assert 48 == len(elems)
assert "One" == elems[0].get_attribute("value")
def test_find_elements_by_name(driver, pages):
pages.load("xhtmlTest.html")
elem = driver.find_element(By.NAME, "windowOne")
assert "Open new window" == elem.text
def test_find_elements_by_name_in_element_context(driver, pages):
pages.load("nestedElements.html")
elem = driver.find_element(By.NAME, "form2")
sub_elem = elem.find_element(By.NAME, "selectomatic")
assert "2" == sub_elem.get_attribute("id")
def test_find_elements_by_link_text_in_element_context(driver, pages):
pages.load("nestedElements.html")
elem = driver.find_element(By.NAME, "div1")
sub_elem = elem.find_element(By.LINK_TEXT, "hello world")
assert "link1" == sub_elem.get_attribute("name")
def test_find_element_by_id_in_element_context(driver, pages):
pages.load("nestedElements.html")
elem = driver.find_element(By.NAME, "form2")
sub_elem = elem.find_element(By.ID, "2")
assert "selectomatic" == sub_elem.get_attribute("name")
def test_find_element_by_xpath_in_element_context(driver, pages):
pages.load("nestedElements.html")
elem = driver.find_element(By.NAME, "form2")
sub_elem = elem.find_element(By.XPATH, "select")
assert "2" == sub_elem.get_attribute("id")
def test_find_element_by_xpath_in_element_context_not_found(driver, pages):
pages.load("nestedElements.html")
elem = driver.find_element(By.NAME, "form2")
with pytest.raises(NoSuchElementException):
elem.find_element(By.XPATH, "div")
def test_should_be_able_to_enter_data_into_form_fields(driver, pages):
pages.load("xhtmlTest.html")
elem = driver.find_element(By.XPATH, "//form[@name='someForm']/input[@id='username']")
elem.clear()
elem.send_keys("some text")
elem = driver.find_element(By.XPATH, "//form[@name='someForm']/input[@id='username']")
assert "some text" == elem.get_attribute("value")
def test_find_element_by_tag_name(driver, pages):
pages.load("simpleTest.html")
elems = driver.find_elements(By.TAG_NAME, "div")
num_by_xpath = len(driver.find_elements(By.XPATH, "//div"))
assert num_by_xpath == len(elems)
elems = driver.find_elements(By.TAG_NAME, "iframe")
assert 0 == len(elems)
def test_find_element_by_tag_name_within_element(driver, pages):
pages.load("simpleTest.html")
div = driver.find_element(By.ID, "multiline")
elems = div.find_elements(By.TAG_NAME, "p")
assert len(elems) == 1
def test_switch_frame_by_name(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "third"))
checkbox = driver.find_element(By.ID, "checky")
checkbox.click()
checkbox.submit()
def test_is_enabled(driver, pages):
pages.load("formPage.html")
elem = driver.find_element(By.XPATH, "//input[@id='working']")
assert elem.is_enabled()
elem = driver.find_element(By.XPATH, "//input[@id='notWorking']")
assert not elem.is_enabled()
def test_is_selected_and_toggle(driver, pages):
pages.load("formPage.html")
elem = driver.find_element(By.ID, "multi")
option_elems = elem.find_elements(By.XPATH, "option")
assert option_elems[0].is_selected()
option_elems[0].click()
assert not option_elems[0].is_selected()
option_elems[0].click()
assert option_elems[0].is_selected()
assert option_elems[2].is_selected()
def test_navigate(driver, pages):
pages.load("formPage.html")
driver.find_element(By.ID, "imageButton").submit()
WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
driver.back()
assert "We Leave From Here" == driver.title
driver.forward()
assert "We Arrive Here" == driver.title
def test_get_attribute(driver, pages):
url = pages.url("xhtmlTest.html")
driver.get(url)
elem = driver.find_element(By.ID, "id1")
attr = elem.get_attribute("href")
assert f"{url}#" == attr
def test_get_implicit_attribute(driver, pages):
pages.load("nestedElements.html")
elems = driver.find_elements(By.XPATH, "//option")
assert len(elems) >= 3
for i, elem in enumerate(elems[:3]):
assert i == int(elem.get_attribute("index"))
def test_get_dom_attribute(driver, pages):
url = pages.url("formPage.html")
driver.get(url)
elem = driver.find_element(By.ID, "vsearchGadget")
attr = elem.get_dom_attribute("accesskey")
assert "4" == attr
def test_get_property(driver, pages):
url = pages.url("formPage.html")
driver.get(url)
elem = driver.find_element(By.ID, "withText")
prop = elem.get_property("value")
assert "Example text" == prop
def test_execute_simple_script(driver, pages):
pages.load("xhtmlTest.html")
title = driver.execute_script("return document.title;")
assert "XHTML Test Page" == title
def test_execute_script_and_return_element(driver, pages):
pages.load("xhtmlTest.html")
elem = driver.execute_script("return document.getElementById('id1');")
assert "WebElement" in str(type(elem))
def test_execute_script_with_args(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return arguments[0] == 'fish' ? 'fish' : 'not fish';", "fish")
assert "fish" == result
def test_execute_script_with_multiple_args(driver, pages):
pages.load("xhtmlTest.html")
result = driver.execute_script("return arguments[0] + arguments[1]", 1, 2)
assert 3 == result
def test_execute_script_with_element_args(driver, pages):
pages.load("javascriptPage.html")
button = driver.find_element(By.ID, "plainButton")
result = driver.execute_script(
"arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble'];", button
)
assert "plainButton" == result
def test_find_elements_by_partial_link_text(driver, pages):
pages.load("xhtmlTest.html")
elem = driver.find_element(By.PARTIAL_LINK_TEXT, "new window")
elem.click()
def test_is_element_displayed(driver, pages):
pages.load("javascriptPage.html")
visible = driver.find_element(By.ID, "displayed").is_displayed()
not_visible = driver.find_element(By.ID, "hidden").is_displayed()
assert visible
assert not not_visible
@pytest.mark.xfail_chrome
def test_move_window_position(driver, pages):
pages.load("blank.html")
loc = driver.get_window_position()
# note can't test 0,0 since some OS's dont allow that location
# because of system toolbars
new_x = 50
new_y = 50
if loc["x"] == new_x:
new_x += 10
if loc["y"] == new_y:
new_y += 10
driver.set_window_position(new_x, new_y)
loc = driver.get_window_position()
assert loc["x"] == new_x
assert loc["y"] == new_y
def test_change_window_size(driver, pages):
pages.load("blank.html")
size = driver.get_window_size()
newSize = [600, 600]
if size["width"] == 600:
newSize[0] = 500
if size["height"] == 600:
newSize[1] = 500
driver.set_window_size(newSize[0], newSize[1])
size = driver.get_window_size()
assert size["width"] == newSize[0]
assert size["height"] == newSize[1]
@pytest.mark.xfail_firefox(raises=WebDriverException)
@pytest.mark.xfail_remote
@pytest.mark.xfail_safari
def test_get_log_types(driver, pages):
pages.load("blank.html")
assert isinstance(driver.log_types, list)
@pytest.mark.xfail_firefox(raises=WebDriverException)
@pytest.mark.xfail_remote
@pytest.mark.xfail_safari
def test_get_log(driver, pages):
pages.load("blank.html")
for log_type in driver.log_types:
log = driver.get_log(log_type)
assert isinstance(log, list)
selenium-selenium-4.18.1/test/selenium/webdriver/common/clear_tests.py 0000644 0001750 0001750 00000005040 14564764517 026112 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import InvalidElementStateException
from selenium.webdriver.common.by import By
def test_writable_text_input_should_clear(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "writableTextInput")
element.clear()
assert "" == element.get_attribute("value")
def test_text_input_should_not_clear_when_disabled(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "textInputNotEnabled")
assert not element.is_enabled()
with pytest.raises(InvalidElementStateException):
element.clear()
def test_text_input_should_not_clear_when_read_only(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "readOnlyTextInput")
with pytest.raises(InvalidElementStateException):
element.clear()
def test_writable_text_area_should_clear(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "writableTextArea")
element.clear()
assert "" == element.get_attribute("value")
def test_text_area_should_not_clear_when_disabled(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "textAreaNotEnabled")
with pytest.raises(InvalidElementStateException):
element.clear()
def test_text_area_should_not_clear_when_read_only(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "textAreaReadOnly")
with pytest.raises(InvalidElementStateException):
element.clear()
def test_content_editable_area_should_clear(driver, pages):
pages.load("readOnlyPage.html")
element = driver.find_element(By.ID, "content-editable")
element.clear()
assert "" == element.text
selenium-selenium-4.18.1/test/selenium/webdriver/common/driver_element_finding_tests.py 0000644 0001750 0001750 00000062013 14564764517 031531 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import InvalidSelectorException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
# By.id positive
def test_should_be_able_to_find_asingle_element_by_id(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.ID, "linkId")
assert element.get_attribute("id") == "linkId"
def test_should_be_able_to_find_asingle_element_by_numeric_id(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.ID, "2")
assert element.get_attribute("id") == "2"
def test_should_be_able_to_find_an_element_with_css_escape(driver, pages):
pages.load("idElements.html")
element = driver.find_element(By.ID, "with.dots")
assert element.get_attribute("id") == "with.dots"
def test_should_be_able_to_find_multiple_elements_by_id(driver, pages):
pages.load("nestedElements.html")
elements = driver.find_elements(By.ID, "test_id")
assert len(elements) == 2
def test_should_be_able_to_find_multiple_elements_by_numeric_id(driver, pages):
pages.load("nestedElements.html")
elements = driver.find_elements(By.ID, "2")
assert len(elements) == 8
# By.id negative
def test_should_not_be_able_to_locate_by_id_asingle_element_that_does_not_exist(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "non_Existent_Button")
def test_should_not_be_able_to_locate_by_id_multiple_elements_that_do_not_exist(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.ID, "non_Existent_Button")
assert len(elements) == 0
def test_finding_asingle_element_by_empty_id_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "")
def test_finding_multiple_elements_by_empty_id_should_return_empty_list(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.ID, "")
assert len(elements) == 0
def test_finding_asingle_element_by_id_with_space_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.ID, "nonexistent button")
def test_finding_multiple_elements_by_id_with_space_should_return_empty_list(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.ID, "nonexistent button")
assert len(elements) == 0
def test_no_such_element_error(driver, pages):
pages.load("formPage.html")
msg = r"\/errors#no-such-element-exception"
with pytest.raises(NoSuchElementException, match=msg):
driver.find_element(By.ID, "non_Existent_Button")
# By.name positive
def test_should_be_able_to_find_asingle_element_by_name(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.NAME, "checky")
assert element.get_attribute("value") == "furrfu"
def test_should_be_able_to_find_multiple_elements_by_name(driver, pages):
pages.load("nestedElements.html")
elements = driver.find_elements(By.NAME, "checky")
assert len(elements) > 1
def test_should_be_able_to_find_an_element_that_does_not_support_the_name_property(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "div1")
assert element.get_attribute("name") == "div1"
# By.name negative
def test_should_not_be_able_to_locate_by_name_asingle_element_that_does_not_exist(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.NAME, "non_Existent_Button")
def test_should_not_be_able_to_locate_by_name_multiple_elements_that_do_not_exist(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.NAME, "non_Existent_Button")
assert len(elements) == 0
def test_finding_asingle_element_by_empty_name_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.NAME, "")
def test_finding_multiple_elements_by_empty_name_should_return_empty_list(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.NAME, "")
assert len(elements) == 0
def test_finding_asingle_element_by_name_with_space_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.NAME, "nonexistent button")
def test_finding_multiple_elements_by_name_with_space_should_return_empty_list(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.NAME, "nonexistent button")
assert len(elements) == 0
# By.tag_Name positive
def test_should_be_able_to_find_asingle_element_by_tag_name(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.TAG_NAME, "input")
assert element.tag_name.lower() == "input"
def test_should_be_able_to_find_multiple_elements_by_tag_name(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.TAG_NAME, "input")
assert len(elements) > 1
# By.tag_Name negative
def test_should_not_be_able_to_locate_by_tag_name_asingle_element_that_does_not_exist(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.TAG_NAME, "non_Existent_Button")
def test_should_not_be_able_to_locate_by_tag_name_multiple_elements_that_do_not_exist(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.TAG_NAME, "non_Existent_Button")
assert len(elements) == 0
@pytest.mark.xfail_firefox(reason="https://github.com/mozilla/geckodriver/issues/2007")
@pytest.mark.xfail_remote(reason="https://github.com/mozilla/geckodriver/issues/2007")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises NoSuchElementException")
def test_finding_asingle_element_by_empty_tag_name_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.TAG_NAME, "")
@pytest.mark.xfail_firefox(reason="https://github.com/mozilla/geckodriver/issues/2007")
@pytest.mark.xfail_remote(reason="https://github.com/mozilla/geckodriver/issues/2007")
@pytest.mark.xfail_safari(reason="unlike chrome, safari returns an empty list")
def test_finding_multiple_elements_by_empty_tag_name_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.TAG_NAME, "")
def test_finding_asingle_element_by_tag_name_with_space_should_throw(driver, pages):
pages.load("formPage.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.TAG_NAME, "nonexistent button")
def test_finding_multiple_elements_by_tag_name_with_space_should_return_empty_list(driver, pages):
pages.load("formPage.html")
elements = driver.find_elements(By.TAG_NAME, "nonexistent button")
assert len(elements) == 0
# By.class_Name positive
def test_should_be_able_to_find_asingle_element_by_class(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CLASS_NAME, "extraDiv")
assert "Another div starts here." in element.text
def test_should_be_able_to_find_multiple_elements_by_class_name(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.CLASS_NAME, "nameC")
assert len(elements) > 1
def test_should_find_element_by_class_when_it_is_the_first_name_among_many(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CLASS_NAME, "nameA")
assert element.text == "An H2 title"
def test_should_find_element_by_class_when_it_is_the_last_name_among_many(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CLASS_NAME, "nameC")
assert element.text == "An H2 title"
def test_should_find_element_by_class_when_it_is_in_the_middle_among_many(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CLASS_NAME, "nameBnoise")
assert element.text == "An H2 title"
def test_should_find_element_by_class_when_its_name_is_surrounded_by_whitespace(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CLASS_NAME, "spaceAround")
assert element.text == "Spaced out"
def test_should_find_elements_by_class_when_its_name_is_surrounded_by_whitespace(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.CLASS_NAME, "spaceAround")
assert len(elements) == 1
assert elements[0].text == "Spaced out"
# By.class_Name negative
def test_should_not_find_element_by_class_when_the_name_queried_is_shorter_than_candidate_name(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.CLASS_NAME, "name_B")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_asingle_element_by_empty_class_name_should_throw(driver, pages):
pages.load("xhtmlTest.html")
msg = r"\/errors#invalid-selector-exception"
with pytest.raises(InvalidSelectorException, match=msg):
driver.find_element(By.CLASS_NAME, "")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_multiple_elements_by_empty_class_name_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.CLASS_NAME, "")
def test_finding_asingle_element_by_compound_class_name_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.CLASS_NAME, "a b")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_asingle_element_by_invalid_class_name_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.CLASS_NAME, "!@#$%^&*")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_multiple_elements_by_invalid_class_name_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.CLASS_NAME, "!@#$%^&*")
# By.xpath positive
def test_should_be_able_to_find_asingle_element_by_xpath(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.XPATH, "//h1")
assert element.text == "XHTML Might Be The Future"
def test_should_be_able_to_find_multiple_elements_by_xpath(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.XPATH, "//div")
assert len(elements) == 13
def test_should_be_able_to_find_many_elements_repeatedly_by_xpath(driver, pages):
pages.load("xhtmlTest.html")
xpath = "//node()[contains(@id,'id')]"
assert len(driver.find_elements(By.XPATH, xpath)) == 3
xpath = "//node()[contains(@id,'nope')]"
assert len(driver.find_elements(By.XPATH, xpath)) == 0
def test_should_be_able_to_identify_elements_by_class(driver, pages):
pages.load("xhtmlTest.html")
header = driver.find_element(By.XPATH, "//h1[@class='header']")
assert header.text == "XHTML Might Be The Future"
def test_should_be_able_to_find_an_element_by_xpath_with_multiple_attributes(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.XPATH, "//form[@name='optional']/input[@type='submit' and @value='Click!']")
assert element.tag_name.lower() == "input"
assert element.get_attribute("value") == "Click!"
def test_finding_alink_by_xpath_should_locate_an_element_with_the_given_text(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.XPATH, "//a[text()='click me']")
assert element.text == "click me"
def test_finding_alink_by_xpath_using_contains_keyword_should_work(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.XPATH, "//a[contains(.,'hello world')]")
assert "hello world" in element.text
# @pytest.mark.xfail_chrome(raises=InvalidSelectorException)
# @pytest.mark.xfail_chromiumedge(raises=InvalidSelectorException)
# @pytest.mark.xfail_firefox(raises=InvalidSelectorException)
# @pytest.mark.xfail_remote(raises=InvalidSelectorException)
# @pytest.mark.xfail_safari(raises=NoSuchElementException)
# @pytest.mark.xfail_webkitgtk(raises=InvalidSelectorException)
# def test_Should_Be_Able_To_Find_Element_By_XPath_With_Namespace(driver, pages):
# pages.load("svgPage.html")
# element = driver.find_element(By.XPATH, "//svg:svg//svg:text")
# assert element.text == "Test Chart"
def test_should_be_able_to_find_element_by_xpath_in_xml_document(driver, pages):
pages.load("simple.xml")
element = driver.find_element(By.XPATH, "//foo")
assert "baz" in element.text
# By.xpath negative
def test_should_throw_an_exception_when_there_is_no_link_to_click(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.XPATH, "//a[@id='Not here']")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_is_syntactically_invalid_in_driver_find_element(
driver, pages
):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.XPATH, "this][isnot][valid")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_is_syntactically_invalid_in_driver_find_elements(
driver, pages
):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.XPATH, "this][isnot][valid")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_is_syntactically_invalid_in_element_find_element(
driver, pages
):
pages.load("formPage.html")
body = driver.find_element(By.TAG_NAME, "body")
with pytest.raises(InvalidSelectorException):
body.find_element(By.XPATH, "this][isnot][valid")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_is_syntactically_invalid_in_element_find_elements(
driver, pages
):
pages.load("formPage.html")
body = driver.find_element(By.TAG_NAME, "body")
with pytest.raises(InvalidSelectorException):
body.find_elements(By.XPATH, "this][isnot][valid")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_returns_wrong_type_in_driver_find_element(driver, pages):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.XPATH, "count(//input)")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_returns_wrong_type_in_driver_find_elements(driver, pages):
pages.load("formPage.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.XPATH, "count(//input)")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_returns_wrong_type_in_element_find_element(driver, pages):
pages.load("formPage.html")
body = driver.find_element(By.TAG_NAME, "body")
with pytest.raises(InvalidSelectorException):
body.find_element(By.XPATH, "count(//input)")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_should_throw_invalid_selector_exception_when_xpath_returns_wrong_type_in_element_find_elements(driver, pages):
pages.load("formPage.html")
body = driver.find_element(By.TAG_NAME, "body")
with pytest.raises(InvalidSelectorException):
body.find_elements(By.XPATH, "count(//input)")
# By.css_Selector positive
def test_should_be_able_to_find_asingle_element_by_css_selector(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CSS_SELECTOR, "div.content")
assert element.tag_name.lower() == "div"
assert element.get_attribute("class") == "content"
def test_should_be_able_to_find_multiple_elements_by_css_selector(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.CSS_SELECTOR, "p")
assert len(elements) > 1
def test_should_be_able_to_find_asingle_element_by_compound_css_selector(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.CSS_SELECTOR, "div.extraDiv, div.content")
assert element.tag_name.lower() == "div"
assert element.get_attribute("class") == "content"
def test_should_be_able_to_find_multiple_elements_by_compound_css_selector(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.CSS_SELECTOR, "div.extraDiv, div.content")
assert len(elements) > 1
assert elements[0].get_attribute("class") == "content"
assert elements[1].get_attribute("class") == "extraDiv"
def test_should_be_able_to_find_an_element_by_boolean_attribute_using_css_selector(driver, pages):
pages.load("locators_tests/boolean_attribute_selected.html")
element = driver.find_element(By.CSS_SELECTOR, "option[selected='selected']")
assert element.get_attribute("value") == "two"
def test_should_be_able_to_find_an_element_by_boolean_attribute_using_short_css_selector(driver, pages):
pages.load("locators_tests/boolean_attribute_selected.html")
element = driver.find_element(By.CSS_SELECTOR, "option[selected]")
assert element.get_attribute("value") == "two"
def test_should_be_able_to_find_an_element_by_boolean_attribute_using_short_css_selector_on_html_4_page(driver, pages):
pages.load("locators_tests/boolean_attribute_selected_html4.html")
element = driver.find_element(By.CSS_SELECTOR, "option[selected]")
assert element.get_attribute("value") == "two"
# By.css_Selector negative
def test_should_not_find_element_by_css_selector_when_there_is_no_such_element(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.CSS_SELECTOR, ".there-is-no-such-class")
def test_should_not_find_elements_by_css_selector_when_there_is_no_such_element(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.CSS_SELECTOR, ".there-is-no-such-class")
assert len(elements) == 0
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_asingle_element_by_empty_css_selector_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.CSS_SELECTOR, "")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_multiple_elements_by_empty_css_selector_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.CSS_SELECTOR, "")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_asingle_element_by_invalid_css_selector_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_element(By.CSS_SELECTOR, "//a/b/c[@id='1']")
@pytest.mark.xfail_safari(reason="unlike chrome, safari raises TimeoutException")
def test_finding_multiple_elements_by_invalid_css_selector_should_throw(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(InvalidSelectorException):
driver.find_elements(By.CSS_SELECTOR, "//a/b/c[@id='1']")
# By.link_Text positive
def test_should_be_able_to_find_alink_by_text(driver, pages):
pages.load("xhtmlTest.html")
link = driver.find_element(By.LINK_TEXT, "click me")
assert link.text == "click me"
def test_should_be_able_to_find_multiple_links_by_text(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.LINK_TEXT, "click me")
assert len(elements) == 2
def test_should_find_element_by_link_text_containing_equals_sign(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.LINK_TEXT, "Link=equalssign")
assert element.get_attribute("id") == "linkWithEqualsSign"
def test_should_find_multiple_elements_by_link_text_containing_equals_sign(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.LINK_TEXT, "Link=equalssign")
assert 1 == len(elements)
assert elements[0].get_attribute("id") == "linkWithEqualsSign"
def test_finds_by_link_text_on_xhtml_page(driver, pages):
pages.load("actualXhtmlPage.xhtml")
link_Text = "Foo"
element = driver.find_element(By.LINK_TEXT, link_Text)
assert element.text == link_Text
def test_link_with_formatting_tags(driver, pages):
pages.load("simpleTest.html")
elem = driver.find_element(By.ID, "links")
res = elem.find_element(By.PARTIAL_LINK_TEXT, "link with formatting tags")
assert res.text == "link with formatting tags"
@pytest.mark.xfail_safari
def test_driver_can_get_link_by_link_test_ignoring_trailing_whitespace(driver, pages):
pages.load("simpleTest.html")
link = driver.find_element(By.LINK_TEXT, "link with trailing space")
assert link.get_attribute("id") == "linkWithTrailingSpace"
assert link.text == "link with trailing space"
# By.link_Text negative
def test_should_not_be_able_to_locate_by_link_text_asingle_element_that_does_not_exist(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.find_element(By.LINK_TEXT, "Not here either")
def test_should_not_be_able_to_locate_by_link_text_multiple_elements_that_do_not_exist(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.LINK_TEXT, "Not here either")
assert len(elements) == 0
# By.partial_Link_Text positive
def test_should_be_able_to_find_multiple_elements_by_partial_link_text(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.PARTIAL_LINK_TEXT, "ick me")
assert len(elements) == 2
def test_should_be_able_to_find_asingle_element_by_partial_link_text(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "anon")
assert "anon" in element.text
def test_should_find_element_by_partial_link_text_containing_equals_sign(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Link=")
assert element.get_attribute("id") == "linkWithEqualsSign"
def test_should_find_multiple_elements_by_partial_link_text_containing_equals_sign(driver, pages):
pages.load("xhtmlTest.html")
elements = driver.find_elements(By.PARTIAL_LINK_TEXT, "Link=")
assert len(elements) == 1
assert elements[0].get_attribute("id") == "linkWithEqualsSign"
# Misc tests
def test_driver_should_be_able_to_find_elements_after_loading_more_than_one_page_at_atime(driver, pages):
pages.load("formPage.html")
pages.load("xhtmlTest.html")
link = driver.find_element(By.LINK_TEXT, "click me")
assert link.text == "click me"
# You don't want to ask why this is here
def test_when_finding_by_name_should_not_return_by_id(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.NAME, "id-name1")
assert element.get_attribute("value") == "name"
element = driver.find_element(By.ID, "id-name1")
assert element.get_attribute("value") == "id"
element = driver.find_element(By.NAME, "id-name2")
assert element.get_attribute("value") == "name"
element = driver.find_element(By.ID, "id-name2")
assert element.get_attribute("value") == "id"
def test_should_be_able_to_find_ahidden_elements_by_name(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.NAME, "hidden")
assert element.get_attribute("name") == "hidden"
def test_should_not_be_able_to_find_an_element_on_a_blank_page(driver, pages):
driver.get("about:blank")
with pytest.raises(NoSuchElementException):
driver.find_element(By.TAG_NAME, "a")
selenium-selenium-4.18.1/test/selenium/webdriver/common/rendered_webelement_tests.py 0000644 0001750 0001750 00000004701 14564764517 031026 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.color import Color
def test_should_pick_up_style_of_an_element(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="green-parent")
backgroundColour = Color.from_string(element.value_of_css_property("background-color"))
assert Color.from_string("rgba(0, 128, 0, 1)") == backgroundColour
element = driver.find_element(by=By.ID, value="red-item")
backgroundColour = Color.from_string(element.value_of_css_property("background-color"))
assert Color.from_string("rgba(255, 0, 0, 1)") == backgroundColour
def test_should_allow_inherited_styles_to_be_used(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="green-item")
backgroundColour = Color.from_string(element.value_of_css_property("background-color"))
assert backgroundColour == Color.from_string("transparent")
def test_should_correctly_identify_that_an_element_has_width(driver, pages):
pages.load("xhtmlTest.html")
shrinko = driver.find_element(by=By.ID, value="linkId")
size = shrinko.size
assert size["width"] > 0
assert size["height"] > 0
@pytest.mark.xfail_safari(reason="Get Element Rect command not implemented", raises=WebDriverException)
def test_should_be_able_to_determine_the_rect_of_an_element(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.ID, "username")
rect = element.rect
assert rect["x"] > 0
assert rect["y"] > 0
assert rect["width"] > 0
assert rect["height"] > 0
selenium-selenium-4.18.1/test/selenium/webdriver/common/upload_tests.py 0000644 0001750 0001750 00000005505 14564764517 026316 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
@pytest.fixture
def get_local_path():
current_dir = os.path.dirname(os.path.realpath(__file__))
def wrapped(filename):
return os.path.join(current_dir, filename)
return wrapped
def test_can_upload_file(driver, pages, get_local_path):
pages.load("upload.html")
driver.find_element(By.ID, "upload").send_keys(get_local_path("test_file.txt"))
driver.find_element(By.ID, "go").click()
driver.switch_to.frame(driver.find_element(By.ID, "upload_target"))
body = driver.find_element(By.CSS_SELECTOR, "body").text
assert "test_file.txt" in body
def test_can_upload_two_files(driver, pages, get_local_path):
pages.load("upload.html")
two_file_paths = get_local_path("test_file.txt") + "\n" + get_local_path("test_file2.txt")
driver.find_element(By.ID, "upload").send_keys(two_file_paths)
driver.find_element(By.ID, "go").click()
driver.switch_to.frame(driver.find_element(By.ID, "upload_target"))
body = driver.find_element(By.CSS_SELECTOR, "body").text
assert "test_file.txt" in body
assert "test_file2.txt" in body
@pytest.mark.xfail_firefox
@pytest.mark.xfail_chrome
@pytest.mark.xfail_safari
def test_file_is_uploaded_to_remote_machine_on_select(driver, pages, get_local_path):
uploaded_files = []
original_upload_func = WebElement._upload
def mocked_upload_func(self, filename):
uploaded_files.append(filename)
return original_upload_func(self, filename)
WebElement._upload = mocked_upload_func
try:
pages.load("upload.html")
two_file_paths = get_local_path("test_file.txt") + "\n" + get_local_path("test_file2.txt")
driver.find_element(By.ID, "upload").send_keys(two_file_paths)
assert len(uploaded_files) == 2
assert uploaded_files[0] == get_local_path("test_file.txt")
assert uploaded_files[1] == get_local_path("test_file2.txt")
finally:
WebElement._upload = original_upload_func
selenium-selenium-4.18.1/test/selenium/webdriver/common/frame_switching_tests.py 0000644 0001750 0001750 00000044224 14564764517 030204 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# ----------------------------------------------------------------------------------------------
#
# Tests that WebDriver doesn't do anything fishy when it navigates to a page with frames.
#
# ----------------------------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def restore_default_context(driver):
yield
driver.switch_to.default_content()
def test_should_always_focus_on_the_top_most_frame_after_anavigation_event(driver, pages):
pages.load("frameset.html")
driver.find_element(By.TAG_NAME, "frameset") # Test passes if this does not throw.
def test_should_not_automatically_switch_focus_to_an_iframe_when_apage_containing_them_is_loaded(driver, pages):
pages.load("iframes.html")
driver.find_element(By.ID, "iframe_page_heading")
def test_should_open_page_with_broken_frameset(driver, pages):
pages.load("framesetPage3.html")
frame1 = driver.find_element(By.ID, "first")
driver.switch_to.frame(frame1)
driver.switch_to.default_content()
frame2 = driver.find_element(By.ID, "second")
driver.switch_to.frame(frame2) # IE9 can not switch to this broken frame - it has no window.
# ----------------------------------------------------------------------------------------------
#
# Tests that WebDriver can switch to frames as expected.
#
# ----------------------------------------------------------------------------------------------
def test_should_be_able_to_switch_to_aframe_by_its_index(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(1)
assert driver.find_element(By.ID, "pageNumber").text == "2"
def test_should_be_able_to_switch_to_an_iframe_by_its_index(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame(0)
assert driver.find_element(By.NAME, "id-name1").get_attribute("value") == "name"
def test_should_be_able_to_switch_to_aframe_by_its_name(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame("fourth")
assert driver.find_element(By.TAG_NAME, "frame").get_attribute("name") == "child1"
def test_should_be_able_to_switch_to_an_iframe_by_its_name(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame("iframe1-name")
assert driver.find_element(By.NAME, "id-name1").get_attribute("value") == "name"
def test_should_be_able_to_switch_to_aframe_by_its_id(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame("fifth")
assert driver.find_element(By.NAME, "windowOne").text == "Open new window"
def test_should_be_able_to_switch_to_an_iframe_by_its_id(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame("iframe1")
assert driver.find_element(By.NAME, "id-name1").get_attribute("value") == "name"
def test_should_be_able_to_switch_to_frame_with_name_containing_dot(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame("sixth.iframe1")
assert "Page number 3" in driver.find_element(By.TAG_NAME, "body").text
def test_should_be_able_to_switch_to_aframe_using_apreviously_located_web_element(driver, pages):
pages.load("frameset.html")
frame = driver.find_element(By.TAG_NAME, "frame")
driver.switch_to.frame(frame)
assert driver.find_element(By.ID, "pageNumber").text == "1"
def test_should_be_able_to_switch_to_an_iframe_using_apreviously_located_web_element(driver, pages):
pages.load("iframes.html")
frame = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(frame)
element = driver.find_element(By.NAME, "id-name1")
assert element.get_attribute("value") == "name"
def test_should_ensure_element_is_aframe_before_switching(driver, pages):
pages.load("frameset.html")
frame = driver.find_element(By.TAG_NAME, "frameset")
with pytest.raises(NoSuchFrameException):
driver.switch_to.frame(frame)
def test_frame_searches_should_be_relative_to_the_currently_selected_frame(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame("second")
assert driver.find_element(By.ID, "pageNumber").text == "2"
with pytest.raises(NoSuchElementException):
driver.switch_to.frame(driver.find_element(By.NAME, "third"))
driver.switch_to.default_content()
driver.switch_to.frame(driver.find_element(By.NAME, "third"))
with pytest.raises(NoSuchFrameException):
driver.switch_to.frame("second")
driver.switch_to.default_content()
driver.switch_to.frame(driver.find_element(By.NAME, "second"))
assert driver.find_element(By.ID, "pageNumber").text == "2"
def test_should_select_child_frames_by_chained_calls(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "fourth"))
driver.switch_to.frame(driver.find_element(By.NAME, "child2"))
assert driver.find_element(By.ID, "pageNumber").text == "11"
def test_should_throw_frame_not_found_exception_looking_up_sub_frames_with_super_frame_names(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "fourth"))
with pytest.raises(NoSuchElementException):
driver.switch_to.frame(driver.find_element(By.NAME, "second"))
def test_should_throw_an_exception_when_aframe_cannot_be_found(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchElementException):
driver.switch_to.frame(driver.find_element(By.NAME, "Nothing here"))
def test_should_throw_an_exception_when_aframe_cannot_be_found_by_index(driver, pages):
pages.load("xhtmlTest.html")
with pytest.raises(NoSuchFrameException):
driver.switch_to.frame(27)
def test_should_be_able_to_switch_to_parent_frame(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "fourth"))
driver.switch_to.parent_frame()
driver.switch_to.frame(driver.find_element(By.NAME, "first"))
assert driver.find_element(By.ID, "pageNumber").text == "1"
@pytest.mark.xfail_safari
def test_should_be_able_to_switch_to_parent_frame_from_asecond_level_frame(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "fourth"))
driver.switch_to.frame(driver.find_element(By.NAME, "child1"))
driver.switch_to.parent_frame()
driver.switch_to.frame(driver.find_element(By.NAME, "child2"))
assert driver.find_element(By.ID, "pageNumber").text == "11"
def test_switching_to_parent_frame_from_default_context_is_no_op(driver, pages):
pages.load("xhtmlTest.html")
driver.switch_to.parent_frame()
assert driver.title == "XHTML Test Page"
def test_should_be_able_to_switch_to_parent_from_an_iframe(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame(0)
driver.switch_to.parent_frame()
driver.find_element(By.ID, "iframe_page_heading")
# ----------------------------------------------------------------------------------------------
#
# General frame handling behavior tests
#
# ----------------------------------------------------------------------------------------------
def test_should_continue_to_refer_to_the_same_frame_once_it_has_been_selected(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(2)
checkbox = driver.find_element(By.XPATH, "//input[@name='checky']")
checkbox.click()
checkbox.submit()
# TODO(simon): this should not be needed, and is only here because IE's submit returns too
# soon.
WebDriverWait(driver, 3).until(EC.text_to_be_present_in_element((By.XPATH, "//p"), "Success!"))
@pytest.mark.xfail_firefox(raises=WebDriverException, reason="https://github.com/mozilla/geckodriver/issues/610")
@pytest.mark.xfail_remote(raises=WebDriverException, reason="https://github.com/mozilla/geckodriver/issues/610")
@pytest.mark.xfail_safari
@pytest.mark.xfail_chrome
def test_should_focus_on_the_replacement_when_aframe_follows_alink_to_a_top_targeted_page(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(0)
driver.find_element(By.LINK_TEXT, "top").click()
expectedTitle = "XHTML Test Page"
WebDriverWait(driver, 3).until(EC.title_is(expectedTitle))
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "only-exists-on-xhtmltest")))
def test_should_allow_auser_to_switch_from_an_iframe_back_to_the_main_content_of_the_page(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame(0)
driver.switch_to.default_content()
driver.find_element(By.ID, "iframe_page_heading")
def test_should_allow_the_user_to_switch_to_an_iframe_and_remain_focused_on_it(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame(0)
driver.find_element(By.ID, "submitButton").click()
assert get_text_of_greeting_element(driver) == "Success!"
def get_text_of_greeting_element(driver):
return WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "greeting"))).text
def test_should_be_able_to_click_in_aframe(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame("third")
# This should replace frame "third" ...
driver.find_element(By.ID, "submitButton").click()
# driver should still be focused on frame "third" ...
assert get_text_of_greeting_element(driver) == "Success!"
# Make sure it was really frame "third" which was replaced ...
driver.switch_to.default_content()
driver.switch_to.frame("third")
assert get_text_of_greeting_element(driver) == "Success!"
def test_should_be_able_to_click_in_aframe_that_rewrites_top_window_location(driver, pages):
pages.load("click_tests/issue5237.html")
driver.switch_to.frame(driver.find_element(By.ID, "search"))
driver.find_element(By.ID, "submit").click()
driver.switch_to.default_content()
WebDriverWait(driver, 3).until(EC.title_is("Target page for issue 5237"))
def test_should_be_able_to_click_in_asub_frame(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.ID, "sixth"))
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
# This should replace frame "iframe1" inside frame "sixth" ...
driver.find_element(By.ID, "submitButton").click()
# driver should still be focused on frame "iframe1" inside frame "sixth" ...
assert get_text_of_greeting_element(driver), "Success!"
# Make sure it was really frame "iframe1" inside frame "sixth" which was replaced ...
driver.switch_to.default_content()
driver.switch_to.frame(driver.find_element(By.ID, "sixth"))
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
assert driver.find_element(By.ID, "greeting").text == "Success!"
def test_should_be_able_to_find_elements_in_iframes_by_xpath(driver, pages):
pages.load("iframes.html")
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
element = driver.find_element(By.XPATH, "//*[@id = 'changeme']")
assert element is not None
def test_get_current_url_returns_top_level_browsing_context_url(driver, pages):
pages.load("frameset.html")
assert "frameset.html" in driver.current_url
driver.switch_to.frame(driver.find_element(By.NAME, "second"))
assert "frameset.html" in driver.current_url
def test_get_current_url_returns_top_level_browsing_context_url_for_iframes(driver, pages):
pages.load("iframes.html")
assert "iframes.html" in driver.current_url
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
assert "iframes.html" in driver.current_url
def test_should_be_able_to_switch_to_the_top_if_the_frame_is_deleted_from_under_us(driver, pages):
pages.load("frame_switching_tests/deletingFrame.html")
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
killIframe = driver.find_element(By.ID, "killIframe")
killIframe.click()
driver.switch_to.default_content()
WebDriverWait(driver, 3).until_not(EC.presence_of_element_located((By.ID, "iframe1")))
addIFrame = driver.find_element(By.ID, "addBackFrame")
addIFrame.click()
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "iframe1")))
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "success")))
def test_should_be_able_to_switch_to_the_top_if_the_frame_is_deleted_from_under_us_with_frame_index(driver, pages):
pages.load("frame_switching_tests/deletingFrame.html")
iframe = 0
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
# we should be in the frame now
killIframe = driver.find_element(By.ID, "killIframe")
killIframe.click()
driver.switch_to.default_content()
addIFrame = driver.find_element(By.ID, "addBackFrame")
addIFrame.click()
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "success")))
def test_frame_to_be_available_and_switch_to_it_using_string_inputs(driver, pages):
# Similar to above test, but using `iframe = "iframe1"` instead of `iframe = 0`
pages.load("frame_switching_tests/deletingFrame.html")
iframe = "iframe1"
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
# we should be in the frame now
killIframe = driver.find_element(By.ID, "killIframe")
killIframe.click()
driver.switch_to.default_content()
addIFrame = driver.find_element(By.ID, "addBackFrame")
addIFrame.click()
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "success")))
def test_should_be_able_to_switch_to_the_top_if_the_frame_is_deleted_from_under_us_with_webelement(driver, pages):
pages.load("frame_switching_tests/deletingFrame.html")
iframe = driver.find_element(By.ID, "iframe1")
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
# we should be in the frame now
killIframe = driver.find_element(By.ID, "killIframe")
killIframe.click()
driver.switch_to.default_content()
addIFrame = driver.find_element(By.ID, "addBackFrame")
addIFrame.click()
iframe = driver.find_element(By.ID, "iframe1")
WebDriverWait(driver, 3).until(EC.frame_to_be_available_and_switch_to_it(iframe))
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "success")))
# @pytest.mark.xfail_chrome(raises=NoSuchElementException)
# @pytest.mark.xfail_chromiumedge(raises=NoSuchElementException)
# @pytest.mark.xfail_firefox(raises=WebDriverException,
# reason='https://github.com/mozilla/geckodriver/issues/614')
# @pytest.mark.xfail_remote(raises=WebDriverException,
# reason='https://github.com/mozilla/geckodriver/issues/614')
# @pytest.mark.xfail_webkitgtk(raises=NoSuchElementException)
# @pytest.mark.xfail_safari
# def test_should_not_be_able_to_do_anything_the_frame_is_deleted_from_under_us(driver, pages):
# pages.load("frame_switching_tests/deletingFrame.html")
# driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
# killIframe = driver.find_element(By.ID, "killIframe")
# killIframe.click()
# with pytest.raises(NoSuchFrameException):
# driver.find_element(By.ID, "killIframe").click()
def test_should_return_window_title_in_aframeset(driver, pages):
pages.load("frameset.html")
driver.switch_to.frame(driver.find_element(By.NAME, "third"))
assert "Unique title" == driver.title
def test_java_script_should_execute_in_the_context_of_the_current_frame(driver, pages):
pages.load("frameset.html")
assert driver.execute_script("return window == window.top")
driver.switch_to.frame(driver.find_element(By.NAME, "third"))
assert driver.execute_script("return window != window.top")
@pytest.mark.xfail_chrome(reason="Fails on Travis")
@pytest.mark.xfail_safari
def test_should_not_switch_magically_to_the_top_window(driver, pages):
pages.load("frame_switching_tests/bug4876.html")
driver.switch_to.frame(0)
WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "inputText")))
for i in range(20):
try:
input = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "inputText")))
submit = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "submitButton")))
input.clear()
import random
input.send_keys("rand%s" % int(random.random()))
submit.click()
finally:
url = driver.execute_script("return window.location.href")
# IE6 and Chrome add "?"-symbol to the end of the URL
if url.endswith("?"):
url = url[: len(url) - 1]
assert pages.url("frame_switching_tests/bug4876_iframe.html") == url
def test_get_should_switch_to_default_context(driver, pages):
pages.load("iframes.html")
driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(driver.find_element(By.ID, "iframe1"))
driver.find_element(By.ID, "cheese") # Found on formPage.html but not on iframes.html.
pages.load("iframes.html") # This must effectively switch_to.default_content(), too.
driver.find_element(By.ID, "iframe1")
selenium-selenium-4.18.1/test/selenium/webdriver/common/form_handling_tests.py 0000644 0001750 0001750 00000017543 14564764517 027646 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def test_should_click_on_submit_input_elements(driver, pages):
pages.load("formPage.html")
driver.find_element(By.ID, "submitButton").click()
WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
def test_clicking_on_unclickable_elements_does_nothing(driver, pages):
pages.load("formPage.html")
driver.find_element(By.XPATH, "//body").click()
def test_should_be_able_to_click_image_buttons(driver, pages):
pages.load("formPage.html")
driver.find_element(By.ID, "imageButton").click()
WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
def test_should_submit_input_in_form(driver, pages):
pages.load("formPage.html")
driver.find_element(By.NAME, "login").submit()
WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
def test_should_submit_any_input_element_within_form(driver, pages):
pages.load("formPage.html")
driver.find_element(By.ID, "checky").submit()
WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
def test_should_submit_any_element_within_form(driver, pages):
pages.load("formPage.html")
driver.find_element(By.XPATH, "//form/p").submit()
WebDriverWait(driver, 5).until(EC.title_is("We Arrive Here"))
def test_should_submit_element_with_id_submit(driver, pages):
pages.load("formPage.html")
driver.find_element(By.ID, "submit").submit()
WebDriverWait(driver, 5).until(EC.title_is("We Arrive Here"))
def test_should_submit_element_with_name_submit(driver, pages):
pages.load("formPage.html")
driver.find_element(By.NAME, "submit").submit()
WebDriverWait(driver, 5).until(EC.title_is("We Arrive Here"))
def test_should_not_submit_button_outside_form(driver, pages):
pages.load("formPage.html")
with pytest.raises(WebDriverException):
driver.find_element(By.NAME, "SearchableText").submit()
def test_should_be_able_to_enter_text_into_atext_area_by_setting_its_value(driver, pages):
pages.load("javascriptPage.html")
textarea = driver.find_element(By.ID, "keyUpArea")
cheesey = "Brie and cheddar"
textarea.send_keys(cheesey)
assert textarea.get_attribute("value") == cheesey
def test_should_enter_data_into_form_fields(driver, pages):
pages.load("xhtmlTest.html")
element = driver.find_element(By.XPATH, "//form[@name='someForm']/input[@id='username']")
originalValue = element.get_attribute("value")
assert originalValue == "change"
element.clear()
element.send_keys("some text")
element = driver.find_element(By.XPATH, "//form[@name='someForm']/input[@id='username']")
newFormValue = element.get_attribute("value")
assert newFormValue == "some text"
def test_should_be_able_to_select_acheck_box(driver, pages):
pages.load("formPage.html")
checkbox = driver.find_element(By.ID, "checky")
assert checkbox.is_selected() is False
checkbox.click()
assert checkbox.is_selected() is True
checkbox.click()
assert checkbox.is_selected() is False
def test_should_toggle_the_checked_state_of_acheckbox(driver, pages):
pages.load("formPage.html")
checkbox = driver.find_element(By.ID, "checky")
assert checkbox.is_selected() is False
checkbox.click()
assert checkbox.is_selected() is True
checkbox.click()
assert checkbox.is_selected() is False
def test_toggling_acheckbox_should_return_its_current_state(driver, pages):
pages.load("formPage.html")
checkbox = driver.find_element(By.ID, "checky")
assert checkbox.is_selected() is False
checkbox.click()
assert checkbox.is_selected() is True
checkbox.click()
assert checkbox.is_selected() is False
def test_should_be_able_to_select_aradio_button(driver, pages):
pages.load("formPage.html")
radioButton = driver.find_element(By.ID, "peas")
assert radioButton.is_selected() is False
radioButton.click()
assert radioButton.is_selected() is True
def test_should_be_able_to_select_aradio_button_by_clicking_on_it(driver, pages):
pages.load("formPage.html")
radioButton = driver.find_element(By.ID, "peas")
assert radioButton.is_selected() is False
radioButton.click()
assert radioButton.is_selected() is True
def test_should_return_state_of_radio_buttons_before_interaction(driver, pages):
pages.load("formPage.html")
radioButton = driver.find_element(By.ID, "cheese_and_peas")
assert radioButton.is_selected() is True
radioButton = driver.find_element(By.ID, "cheese")
assert radioButton.is_selected() is False
def test_toggling_an_option_should_toggle_options_in_amulti_select(driver, pages):
pages.load("formPage.html")
select = driver.find_element(By.NAME, "multi")
option = select.find_elements(By.TAG_NAME, "option")[0]
selected = option.is_selected()
option.click()
assert not selected == option.is_selected()
option.click()
assert selected == option.is_selected()
def test_should_throw_an_exception_when_selecting_an_unselectable_element(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.XPATH, "//title")
with pytest.raises(WebDriverException):
element.click()
def test_sending_keyboard_events_should_append_text_in_inputs(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "working")
element.send_keys("Some")
value = element.get_attribute("value")
assert value == "Some"
element.send_keys(" text")
value = element.get_attribute("value")
assert value == "Some text"
def test_should_be_able_to_clear_text_from_input_elements(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "working")
element.send_keys("Some text")
value = element.get_attribute("value")
assert len(value) > 0
element.clear()
value = element.get_attribute("value")
assert len(value) == 0
def test_empty_text_boxes_should_return_an_empty_string_not_null(driver, pages):
pages.load("formPage.html")
emptyTextBox = driver.find_element(By.ID, "working")
assert emptyTextBox.get_attribute("value") == ""
emptyTextArea = driver.find_element(By.ID, "emptyTextArea")
assert emptyTextArea.get_attribute("value") == ""
def test_should_be_able_to_clear_text_from_text_areas(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "withText")
element.send_keys("Some text")
value = element.get_attribute("value")
assert len(value) > 0
element.clear()
value = element.get_attribute("value")
assert len(value) == 0
def test_radio_should_not_be_selected_after_selecting_sibling(driver, pages):
pages.load("formPage.html")
cheese = driver.find_element(By.ID, "cheese")
peas = driver.find_element(By.ID, "peas")
cheese.click()
assert cheese.is_selected() is True
assert peas.is_selected() is False
peas.click()
assert cheese.is_selected() is False
assert peas.is_selected() is True
selenium-selenium-4.18.1/test/selenium/webdriver/common/cookie_tests.py 0000644 0001750 0001750 00000011775 14564764517 026311 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import calendar
import random
import time
import pytest
@pytest.fixture
def cookie(webserver):
cookie = {"name": "foo", "value": "bar", "domain": webserver.host, "path": "/", "secure": False}
return cookie
@pytest.fixture
def same_site_cookie_strict(webserver):
same_site_cookie_strict = {
"name": "foo",
"value": "bar",
"path": "/",
"domain": webserver.host,
"sameSite": "Strict",
"secure": False,
}
return same_site_cookie_strict
@pytest.fixture
def same_site_cookie_lax(webserver):
same_site_cookie_lax = {
"name": "foo",
"value": "bar",
"path": "/",
"domain": webserver.host,
"sameSite": "Lax",
"secure": False,
}
return same_site_cookie_lax
@pytest.fixture
def same_site_cookie_none(webserver):
same_site_cookie_none = {
"name": "foo",
"value": "bar",
"path": "/",
"domain": webserver.host,
"sameSite": "None",
"secure": True,
}
return same_site_cookie_none
@pytest.fixture(autouse=True)
def pages(request, driver, pages):
pages.load("simpleTest.html")
yield pages
driver.delete_all_cookies()
def test_add_cookie(cookie, driver):
driver.add_cookie(cookie)
returned = driver.execute_script("return document.cookie")
assert cookie["name"] in returned
@pytest.mark.xfail_firefox(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_remote(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_safari
def test_add_cookie_same_site_strict(same_site_cookie_strict, driver):
driver.add_cookie(same_site_cookie_strict)
returned = driver.get_cookie("foo")
assert "sameSite" in returned and returned["sameSite"] == "Strict"
@pytest.mark.xfail_firefox(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_remote(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_safari
def test_add_cookie_same_site_lax(same_site_cookie_lax, driver):
driver.add_cookie(same_site_cookie_lax)
returned = driver.get_cookie("foo")
assert "sameSite" in returned and returned["sameSite"] == "Lax"
@pytest.mark.xfail_firefox(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_remote(reason="sameSite cookie attribute not implemented")
@pytest.mark.xfail_safari
def test_add_cookie_same_site_none(same_site_cookie_none, driver):
driver.add_cookie(same_site_cookie_none)
# Note that insecure sites (http:) can't set cookies with the Secure directive.
# driver.get_cookie would return None
@pytest.mark.xfail_ie
@pytest.mark.xfail_safari
def test_adding_acookie_that_expired_in_the_past(cookie, driver):
expired = cookie.copy()
expired["expiry"] = calendar.timegm(time.gmtime()) - 1
driver.add_cookie(expired)
assert 0 == len(driver.get_cookies())
def test_delete_all_cookie(cookie, driver):
driver.add_cookie(cookie)
driver.delete_all_cookies()
assert not driver.get_cookies()
def test_delete_cookie(cookie, driver):
driver.add_cookie(cookie)
driver.delete_cookie("foo")
assert not driver.get_cookies()
def test_should_get_cookie_by_name(driver):
key = f"key_{int(random.random() * 10000000)}"
driver.execute_script("document.cookie = arguments[0] + '=set';", key)
cookie = driver.get_cookie(key)
assert "set" == cookie["value"]
def test_should_return_none_when_cookie_does_not_exist(driver):
key = f"key_{int(random.random() * 10000000)}"
cookie = driver.get_cookie(key)
assert cookie is None
def test_get_all_cookies(cookie, driver, pages, webserver):
cookies = driver.get_cookies()
count = len(cookies)
for i in range(2):
cookie["name"] = f"key_{int(random.random() * 10000000)}"
driver.add_cookie(cookie)
pages.load("simpleTest.html")
assert count + 2 == len(driver.get_cookies())
def test_should_not_delete_cookies_with_asimilar_name(cookie, driver, webserver):
cookie2 = cookie.copy()
cookie2["name"] = "{}x".format(cookie["name"])
driver.add_cookie(cookie)
driver.add_cookie(cookie2)
driver.delete_cookie(cookie["name"])
cookies = driver.get_cookies()
assert cookie["name"] != cookies[0]["name"]
assert cookie2["name"] == cookies[0]["name"]
selenium-selenium-4.18.1/test/selenium/webdriver/common/page_loader.py 0000644 0001750 0001750 00000002574 14564764517 026055 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module contains some decorators that can be used to support
the page models. For example for an action that needs a page to be fully
loaded, the @require_loaded decorator will make sure the page is loaded
before the call is invoked.
This pattern is also useful for waiting for certain asynchronous events
to happen before executing certain actions."""
def require_loaded(func):
def load_page(page, *params, **kwds):
if not page.is_loaded():
page.load()
assert page.is_loaded(), "page should be loaded by now"
return func(page, *params, **kwds)
return load_page
selenium-selenium-4.18.1/test/selenium/webdriver/common/page_loading_tests.py 0000644 0001750 0001750 00000011577 14564764517 027451 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# import pytest
#
# from selenium.common.exceptions import WebDriverException
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support.wait import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
def test_should_wait_for_document_to_be_loaded(driver, pages):
pages.load("simpleTest.html")
assert driver.title == "Hello WebDriver"
# Disabled till Java WebServer is used
# def test_should_follow_redirects_sent_in_the_http_response_headers(driver, pages):
# pages.load("redirect.html")
# assert driver.title == "We Arrive Here"
# Disabled till the Java WebServer is used
# def test_should_follow_meta_redirects(driver, pages):
# pages.load("metaRedirect.html")
# assert driver.title == "We Arrive Here"
# def test_should_be_able_to_get_afragment_on_the_current_page(driver, pages):
# pages.load("xhtmlTest.html")
# location = driver.current_url
# driver.get(location + "#text")
# driver.find_element(by=By.ID, value="id1")
# @pytest.mark.xfail_firefox(raises=WebDriverException)
# @pytest.mark.xfail_remote(raises=WebDriverException)
# def test_should_return_when_getting_aurl_that_does_not_resolve(driver):
# # Of course, we're up the creek if this ever does get registered
# driver.get("http://www.thisurldoesnotexist.comx/")
# @pytest.mark.xfail_firefox(raises=WebDriverException)
# @pytest.mark.xfail_remote(raises=WebDriverException)
# def test_should_return_when_getting_aurl_that_does_not_connect(driver):
# # Here's hoping that there's nothing here. There shouldn't be
# driver.get("http://localhost:3001")
# def test_should_be_able_to_load_apage_with_framesets_and_wait_until_all_frames_are_loaded() {
# driver.get(pages.framesetPage)
#
# driver.switchTo().frame(0)
# WebElement pageNumber = driver.findElement(By.xpath("#span[@id='pageNumber']"))
# self.assertEqual((pageNumber.getText().trim(), equalTo("1"))
#
# driver.switchTo().defaultContent().switchTo().frame(1)
# pageNumber = driver.findElement(By.xpath("#span[@id='pageNumber']"))
# self.assertEqual((pageNumber.getText().trim(), equalTo("2"))
# Need to implement this decorator
# @NeedsFreshDriver
# def test_sould_do_nothing_if_there_is_nothing_to_go_back_to() {
# originalTitle = driver.getTitle();
# driver.get(pages.formPage);
# driver.back();
# # We may have returned to the browser's home page
# self.assertEqual(driver.title, anyOf(equalTo(originalTitle), equalTo("We Leave From Here")));
# @pytest.mark.xfail_safari
# def test_should_be_able_to_navigate_back_in_the_browser_history(driver, pages):
# pages.load("formPage.html")
# driver.find_element(by=By.ID, value="imageButton").submit()
# WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
# driver.back()
# assert driver.title == "We Leave From Here"
# @pytest.mark.xfail_safari
# def test_should_be_able_to_navigate_back_in_the_browser_history_in_presence_of_iframes(driver, pages):
# pages.load("xhtmlTest.html")
# driver.find_element(by=By.NAME, value="sameWindow").click()
# assert driver.title == "This page has iframes"
# driver.back()
# assert driver.title == "XHTML Test Page"
# def test_should_be_able_to_navigate_forwards_in_the_browser_history(driver, pages):
# pages.load("formPage.html")
# driver.find_element(by=By.ID, value="imageButton").submit()
# WebDriverWait(driver, 3).until(EC.title_is("We Arrive Here"))
# driver.back()
# assert driver.title == "We Leave From Here"
# driver.forward()
# assert driver.title == "We Arrive Here"
# @pytest.mark.xfail_ie
# @pytest.mark.xfail_firefox(run=False)
# @pytest.mark.xfail_remote(run=False)
# @pytest.mark.xfail_chrome(run=False)
# @pytest.mark.xfail_chromiumedge(run=False)
# def test_should_not_hang_if_document_open_call_is_never_followed_by_document_close_call(driver, pages):
# pages.load("document_write_in_onload.html")
# driver.find_element(By.XPATH, "//body")
# def test_should_be_able_to_refresh_apage(driver, pages):
# pages.load("xhtmlTest.html")
# driver.refresh()
# assert driver.title == "XHTML Test Page"
selenium-selenium-4.18.1/test/selenium/webdriver/common/children_finding_tests.py 0000644 0001750 0001750 00000015312 14564764517 030315 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
def test_should_find_element_by_xpath(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
child = element.find_element(By.XPATH, "select")
assert child.get_attribute("id") == "2"
def test_should_not_find_element_by_xpath(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
with pytest.raises(NoSuchElementException):
element.find_element(By.XPATH, "select/x")
def test_finding_dot_slash_elements_on_element_by_xpath_should_find_not_top_level_elements(driver, pages):
pages.load("simpleTest.html")
parent = driver.find_element(By.ID, "multiline")
children = parent.find_elements(By.XPATH, "./p")
assert 1 == len(children)
assert "A div containing" == children[0].text
def test_should_find_elements_by_xpath(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
children = element.find_elements(By.XPATH, "select/option")
assert len(children) == 8
assert children[0].text == "One"
assert children[1].text == "Two"
def test_should_not_find_elements_by_xpath(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
children = element.find_elements(By.XPATH, "select/x")
assert len(children) == 0
def test_finding_elements_on_element_by_xpath_should_find_top_level_elements(driver, pages):
pages.load("simpleTest.html")
parent = driver.find_element(By.ID, "multiline")
all_para_elements = driver.find_elements(By.XPATH, "//p")
children = parent.find_elements(By.XPATH, "//p")
assert len(all_para_elements) == len(children)
def test_should_find_element_by_name(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
child = element.find_element(By.NAME, "selectomatic")
assert child.get_attribute("id") == "2"
def test_should_find_elements_by_name(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
children = element.find_elements(By.NAME, "selectomatic")
assert len(children) == 2
def test_should_find_element_by_id(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
child = element.find_element(By.ID, "2")
assert child.get_attribute("name") == "selectomatic"
def test_should_find_elements_by_id(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
child = element.find_elements(By.ID, "2")
assert len(child) == 2
def test_should_find_element_by_id_when_multiple_matches_exist(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.ID, "test_id_div")
child = element.find_element(By.ID, "test_id")
assert child.text == "inside"
def test_should_find_element_by_id_when_no_match_in_context(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.ID, "test_id_div")
with pytest.raises(NoSuchElementException):
element.find_element(By.ID, "test_id_out")
def test_should_find_element_by_link_text(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "div1")
child = element.find_element(By.LINK_TEXT, "hello world")
assert child.get_attribute("name") == "link1"
def test_should_find_elements_by_link_text(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "div1")
children = element.find_elements(By.LINK_TEXT, "hello world")
assert len(children) == 2
assert "link1" == children[0].get_attribute("name")
assert "link2" == children[1].get_attribute("name")
def test_should_find_element_by_class_name(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "classes")
element = parent.find_element(By.CLASS_NAME, "one")
assert "Find me" == element.text
def test_should_find_elements_by_class_name(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "classes")
elements = parent.find_elements(By.CLASS_NAME, "one")
assert 2 == len(elements)
def test_should_find_element_by_tag_name(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "div1")
element = parent.find_element(By.TAG_NAME, "a")
assert "link1" == element.get_attribute("name")
def test_should_find_elements_by_tag_name(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "div1")
elements = parent.find_elements(By.TAG_NAME, "a")
assert 2 == len(elements)
def test_should_be_able_to_find_an_element_by_css_selector(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "form2")
element = parent.find_element(By.CSS_SELECTOR, '*[name="selectomatic"]')
assert "2" == element.get_attribute("id")
def test_should_be_able_to_find_multiple_elements_by_css_selector(driver, pages):
pages.load("nestedElements.html")
parent = driver.find_element(By.NAME, "form2")
elements = parent.find_elements(By.CSS_SELECTOR, '*[name="selectomatic"]')
assert 2 == len(elements)
def test_should_throw_an_error_if_user_passes_in_invalid_by(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
with pytest.raises(WebDriverException):
element.find_element("foo", "bar")
def test_should_throw_an_error_if_user_passes_in_invalid_by_when_find_elements(driver, pages):
pages.load("nestedElements.html")
element = driver.find_element(By.NAME, "form2")
with pytest.raises(WebDriverException):
element.find_elements("foo", "bar")
selenium-selenium-4.18.1/test/selenium/webdriver/common/correct_event_firing_tests.py 0000644 0001750 0001750 00000011511 14564764517 031224 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
@pytest.mark.xfail_safari
def test_should_fire_click_event_when_clicking(driver, pages):
pages.load("javascriptPage.html")
_click_on_element_which_records_events(driver)
_assert_event_fired(driver, "click")
@pytest.mark.xfail_safari
def test_should_fire_mouse_down_event_when_clicking(driver, pages):
pages.load("javascriptPage.html")
_click_on_element_which_records_events(driver)
_assert_event_fired(driver, "mousedown")
@pytest.mark.xfail_safari
def test_should_fire_mouse_up_event_when_clicking(driver, pages):
pages.load("javascriptPage.html")
_click_on_element_which_records_events(driver)
_assert_event_fired(driver, "mouseup")
@pytest.mark.xfail_safari
def test_should_issue_mouse_down_events(driver, pages):
pages.load("javascriptPage.html")
driver.find_element(By.ID, "mousedown").click()
result = driver.find_element(By.ID, "result").text
assert result == "mouse down"
@pytest.mark.xfail_safari
def test_should_issue_click_events(driver, pages):
pages.load("javascriptPage.html")
driver.find_element(By.ID, "mouseclick").click()
result = driver.find_element(By.ID, "result").text
assert result == "mouse click"
@pytest.mark.xfail_safari
def test_should_issue_mouse_up_events(driver, pages):
pages.load("javascriptPage.html")
driver.find_element(By.ID, "mouseup").click()
result = driver.find_element(By.ID, "result").text
assert result == "mouse up"
@pytest.mark.xfail_safari
def test_mouse_events_should_bubble_up_to_containing_elements(driver, pages):
pages.load("javascriptPage.html")
driver.find_element(By.ID, "child").click()
result = driver.find_element(By.ID, "result").text
assert result == "mouse down"
@pytest.mark.xfail_safari
def test_should_emit_on_change_events_when_selecting_elements(driver, pages):
pages.load("javascriptPage.html")
select = driver.find_element(By.ID, "selector")
options = select.find_elements(By.TAG_NAME, "option")
initialTextValue = driver.find_element(By.ID, "result").text
select.click()
assert driver.find_element(By.ID, "result").text == initialTextValue
options[1].click()
assert driver.find_element(By.ID, "result").text == "bar"
@pytest.mark.xfail_safari
def test_should_emit_on_change_events_when_changing_the_state_of_acheckbox(driver, pages):
pages.load("javascriptPage.html")
checkbox = driver.find_element(By.ID, "checkbox")
checkbox.click()
assert driver.find_element(By.ID, "result").text == "checkbox thing"
def test_should_emit_click_event_when_clicking_on_atext_input_element(driver, pages):
pages.load("javascriptPage.html")
clicker = driver.find_element(By.ID, "clickField")
clicker.click()
assert clicker.get_attribute("value") == "Clicked"
@pytest.mark.xfail_safari
def test_clearing_an_element_should_cause_the_on_change_handler_to_fire(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(By.ID, "clearMe")
element.clear()
result = driver.find_element(By.ID, "result")
assert result.text == "Cleared"
# TODO Currently Failing and needs fixing
# def test_sending_keys_to_another_element_should_cause_the_blur_event_to_fire(driver, pages):
# pages.load("javascriptPage.html")
# element = driver.find_element(By.ID, "theworks")
# element.send_keys("foo")
# element2 = driver.find_element(By.ID, "changeable")
# element2.send_keys("bar")
# _assertEventFired(driver, "blur")
# TODO Currently Failing and needs fixing
# def test_sending_keys_to_an_element_should_cause_the_focus_event_to_fire(driver, pages):
# pages.load("javascriptPage.html")
# element = driver.find_element(By.ID, "theworks")
# element.send_keys("foo")
# _assertEventFired(driver, "focus")
def _click_on_element_which_records_events(driver):
driver.find_element(By.ID, "plainButton").click()
def _assert_event_fired(driver, eventName):
result = driver.find_element(By.ID, "result")
text = result.text
assert eventName in text, "No " + eventName + " fired: " + text
selenium-selenium-4.18.1/test/selenium/webdriver/common/select_class_tests.py 0000644 0001750 0001750 00000031445 14564764517 027500 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import UnexpectedTagNameException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
disabledSelect = {"name": "no-select", "values": ["Foo"]}
disabledSingleSelect = {"name": "single_disabled", "values": ["Enabled", "Disabled"]}
disabledMultiSelect = {"name": "multi_disabled", "values": ["Enabled", "Disabled"]}
singleSelectValues1 = {
"name": "selectomatic",
"values": ["One", "Two", "Four", "Still learning how to count, apparently"],
}
singleSelectValues2 = {"name": "redirect", "values": ["One", "Two"]}
singleSelectValuesWithSpaces = {
"name": "select_with_spaces",
"values": ["One", "Two", "Four", "Still learning how to count, apparently"],
}
multiSelectValues1 = {"name": "multi", "values": ["Eggs", "Ham", "Sausages", "Onion gravy"]}
multiSelectValues2 = {"name": "select_empty_multiple", "values": ["select_1", "select_2", "select_3", "select_4"]}
def test_select_by_index_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1]:
sel = Select(driver.find_element(By.NAME, select["name"]))
for x in range(len(select["values"])):
sel.select_by_index(x)
assert sel.first_selected_option.text == select["values"][x]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_index_single_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledSingleSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_index(1)
def test_select_by_value_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1]:
sel = Select(driver.find_element(By.NAME, select["name"]))
for x in range(len(select["values"])):
sel.select_by_value(select["values"][x].lower())
assert sel.first_selected_option.text == select["values"][x]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_value_single_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledSingleSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_value(disabledSingleSelect["values"][1].lower())
def test_select_by_visible_text_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1]:
sel = Select(driver.find_element(By.NAME, select["name"]))
for x in range(len(select["values"])):
print(select["values"][x])
sel.select_by_visible_text(select["values"][x])
assert sel.first_selected_option.text == select["values"][x]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_text_single_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledSingleSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_visible_text(disabledSingleSelect["values"][1])
def test_select_by_index_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
for x in range(len(select["values"])):
sel.select_by_index(x)
selected = sel.all_selected_options
assert len(selected) == x + 1
for j in range(len(selected)):
assert selected[j].text == select["values"][j]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_index_multiple_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledMultiSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_index(1)
def test_select_by_value_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
for x in range(len(select["values"])):
sel.select_by_value(select["values"][x].lower())
selected = sel.all_selected_options
assert len(selected) == x + 1
for j in range(len(selected)):
assert selected[j].text == select["values"][j]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_value_multiple_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledMultiSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_value(disabledMultiSelect["values"][1].lower())
def test_select_by_visible_text_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
for x in range(len(select["values"])):
sel.select_by_visible_text(select["values"][x])
selected = sel.all_selected_options
assert len(selected) == x + 1
for j in range(len(selected)):
assert selected[j].text == select["values"][j]
@pytest.mark.xfail_safari(reason="options incorrectly reported as enabled")
def test_raises_exception_select_by_text_multiple_disabled(driver, pages):
pages.load("formPage.html")
sel = Select(driver.find_element(By.NAME, disabledMultiSelect["name"]))
with pytest.raises(NotImplementedError):
sel.select_by_visible_text(disabledMultiSelect["values"][1])
def test_deselect_all_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2]:
with pytest.raises(NotImplementedError):
Select(driver.find_element(By.NAME, select["name"])).deselect_all()
def test_deselect_all_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
assert len(sel.all_selected_options) == 0
def test_deselect_by_index_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2]:
with pytest.raises(NotImplementedError):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_index(0)
def test_deselect_by_value_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2]:
with pytest.raises(NotImplementedError):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_value(select["values"][0].lower())
def test_deselect_by_visible_text_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2]:
with pytest.raises(NotImplementedError):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_visible_text(select["values"][0])
def test_deselect_by_index_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
sel.select_by_index(0)
sel.select_by_index(1)
sel.select_by_index(2)
sel.select_by_index(3)
sel.deselect_by_index(1)
sel.deselect_by_index(3)
selected = sel.all_selected_options
assert len(selected) == 2
assert selected[0].text == select["values"][0]
assert selected[1].text == select["values"][2]
def test_deselect_by_value_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
sel.select_by_index(0)
sel.select_by_index(1)
sel.select_by_index(2)
sel.select_by_index(3)
sel.deselect_by_value(select["values"][1].lower())
sel.deselect_by_value(select["values"][3].lower())
selected = sel.all_selected_options
assert len(selected) == 2
assert selected[0].text == select["values"][0]
assert selected[1].text == select["values"][2]
def test_deselect_by_visible_text_multiple(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
sel = Select(driver.find_element(By.NAME, select["name"]))
sel.deselect_all()
sel.select_by_index(0)
sel.select_by_index(1)
sel.select_by_index(2)
sel.select_by_index(3)
sel.deselect_by_visible_text(select["values"][1])
sel.deselect_by_visible_text(select["values"][3])
selected = sel.all_selected_options
assert len(selected) == 2
assert selected[0].text == select["values"][0]
assert selected[1].text == select["values"][2]
def test_get_options(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2, multiSelectValues1, multiSelectValues2]:
opts = Select(driver.find_element(By.NAME, select["name"])).options
assert len(opts) == len(select["values"])
for i in range(len(opts)):
assert opts[i].text == select["values"][i]
def test_get_all_selected_options_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2, disabledSelect]:
opts = Select(driver.find_element(By.NAME, select["name"])).all_selected_options
assert len(opts) == 1
assert opts[0].text == select["values"][0]
def test_get_all_selected_options_multiple(driver, pages):
pages.load("formPage.html")
opts = Select(driver.find_element(By.NAME, multiSelectValues1["name"])).all_selected_options
assert len(opts) == 2
assert opts[0].text, multiSelectValues1["values"][0]
assert opts[1].text, multiSelectValues1["values"][2]
opts = Select(driver.find_element(By.NAME, multiSelectValues2["name"])).all_selected_options
assert len(opts) == 0
def test_get_first_selected_option_single(driver, pages):
pages.load("formPage.html")
for select in [singleSelectValues1, singleSelectValues2]:
opt = Select(driver.find_element(By.NAME, select["name"])).first_selected_option
assert opt.text == select["values"][0]
def test_get_first_selected_option_multiple(driver, pages):
pages.load("formPage.html")
opt = Select(driver.find_element(By.NAME, multiSelectValues1["name"])).first_selected_option
assert opt.text == multiSelectValues1["values"][0]
opt = Select(driver.find_element(By.NAME, multiSelectValues2["name"])).all_selected_options
assert len(opt) == 0
def test_raises_exception_for_invalid_tag_name(driver, pages):
pages.load("formPage.html")
with pytest.raises(UnexpectedTagNameException):
Select(driver.find_element(By.TAG_NAME, "div"))
def test_deselect_by_index_non_existent(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
with pytest.raises(NoSuchElementException):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_index(10)
def test_deselect_by_value_non_existent(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
with pytest.raises(NoSuchElementException):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_value("not there")
def test_deselect_by_text_non_existent(driver, pages):
pages.load("formPage.html")
for select in [multiSelectValues1, multiSelectValues2]:
with pytest.raises(NoSuchElementException):
Select(driver.find_element(By.NAME, select["name"])).deselect_by_visible_text("not there")
selenium-selenium-4.18.1/test/selenium/webdriver/common/network.py 0000644 0001750 0001750 00000004076 14564764517 025303 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
def _bytes(value, encoding):
try:
return bytes(value, encoding) # Python 3
except TypeError:
return value # Python 2
sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(sckt.fileno(), 0x8915, struct.pack("256s", _bytes(ifname[:15], "utf-8")))[20:24] # SIOCGIFADDR
)
def get_lan_ip():
if os.environ.get("CI") == "true":
return "0.0.0.0"
try:
ip = socket.gethostbyname(socket.gethostname())
except Exception:
return "0.0.0.0"
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"en0",
"en1",
"en2",
"en3",
"en4",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except OSError:
pass
return ip
selenium-selenium-4.18.1/test/selenium/webdriver/common/element_attribute_tests.py 0000644 0001750 0001750 00000026012 14564764517 030542 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
def test_should_return_null_when_getting_the_value_of_an_attribute_that_is_not_listed(driver, pages):
pages.load("simpleTest.html")
head = driver.find_element(By.XPATH, "/html")
attribute = head.get_attribute("cheese")
assert attribute is None
def test_should_return_null_when_getting_src_attribute_of_invalid_img_tag(driver, pages):
pages.load("simpleTest.html")
img = driver.find_element(By.ID, "invalidImgTag")
img_attr = img.get_attribute("src")
assert img_attr is None
def test_should_return_an_absolute_url_when_getting_src_attribute_of_avalid_img_tag(driver, pages):
pages.load("simpleTest.html")
img = driver.find_element(By.ID, "validImgTag")
img_attr = img.get_attribute("src")
assert "icon.gif" in img_attr
def test_should_return_an_absolute_url_when_getting_href_attribute_of_avalid_anchor_tag(driver, pages):
pages.load("simpleTest.html")
img = driver.find_element(By.ID, "validAnchorTag")
img_attr = img.get_attribute("href")
assert "icon.gif" in img_attr
def test_should_return_empty_attribute_values_when_present_and_the_value_is_actually_empty(driver, pages):
pages.load("simpleTest.html")
body = driver.find_element(By.XPATH, "//body")
assert "" == body.get_attribute("style")
def test_should_return_the_value_of_the_disabled_attribute_as_false_if_not_set(driver, pages):
pages.load("formPage.html")
inputElement = driver.find_element(By.XPATH, "//input[@id='working']")
assert inputElement.get_attribute("disabled") is None
assert inputElement.is_enabled()
pElement = driver.find_element(By.ID, "peas")
assert pElement.get_attribute("disabled") is None
assert pElement.is_enabled()
def test_should_return_the_value_of_the_index_attribute_even_if_it_is_missing(driver, pages):
pages.load("formPage.html")
multiSelect = driver.find_element(By.ID, "multi")
options = multiSelect.find_elements(By.TAG_NAME, "option")
assert "1" == options[1].get_attribute("index")
def test_should_indicate_the_elements_that_are_disabled_are_not_is_enabled(driver, pages):
pages.load("formPage.html")
inputElement = driver.find_element(By.XPATH, "//input[@id='notWorking']")
assert not inputElement.is_enabled()
inputElement = driver.find_element(By.XPATH, "//input[@id='working']")
assert inputElement.is_enabled()
def test_elements_should_be_disabled_if_they_are_disabled_using_random_disabled_strings(driver, pages):
pages.load("formPage.html")
disabledTextElement1 = driver.find_element(By.ID, "disabledTextElement1")
assert not disabledTextElement1.is_enabled()
disabledTextElement2 = driver.find_element(By.ID, "disabledTextElement2")
assert not disabledTextElement2.is_enabled()
disabledSubmitElement = driver.find_element(By.ID, "disabledSubmitElement")
assert not disabledSubmitElement.is_enabled()
def test_should_indicate_when_atext_area_is_disabled(driver, pages):
pages.load("formPage.html")
textArea = driver.find_element(By.XPATH, "//textarea[@id='notWorkingArea']")
assert not textArea.is_enabled()
@pytest.mark.xfail_safari
def test_should_throw_exception_if_sending_keys_to_element_disabled_using_random_disabled_strings(driver, pages):
pages.load("formPage.html")
disabledTextElement1 = driver.find_element(By.ID, "disabledTextElement1")
with pytest.raises(WebDriverException):
disabledTextElement1.send_keys("foo")
assert "" == disabledTextElement1.text
disabledTextElement2 = driver.find_element(By.ID, "disabledTextElement2")
with pytest.raises(WebDriverException):
disabledTextElement2.send_keys("bar")
assert "" == disabledTextElement2.text
def test_should_indicate_when_aselect_is_disabled(driver, pages):
pages.load("formPage.html")
enabled = driver.find_element(By.NAME, "selectomatic")
disabled = driver.find_element(By.NAME, "no-select")
assert enabled.is_enabled()
assert not disabled.is_enabled()
def test_should_return_the_value_of_checked_for_acheckbox_even_if_it_lacks_that_attribute(driver, pages):
pages.load("formPage.html")
checkbox = driver.find_element(By.XPATH, "//input[@id='checky']")
assert checkbox.get_attribute("checked") is None
checkbox.click()
assert "true" == checkbox.get_attribute("checked")
def test_should_return_the_value_of_selected_for_radio_buttons_even_if_they_lack_that_attribute(driver, pages):
pages.load("formPage.html")
neverSelected = driver.find_element(By.ID, "cheese")
initiallyNotSelected = driver.find_element(By.ID, "peas")
initiallySelected = driver.find_element(By.ID, "cheese_and_peas")
assert neverSelected.get_attribute("checked") is None
assert initiallyNotSelected.get_attribute("checked") is None
assert "true" == initiallySelected.get_attribute("checked")
initiallyNotSelected.click()
assert neverSelected.get_attribute("selected") is None
assert "true" == initiallyNotSelected.get_attribute("checked")
assert initiallySelected.get_attribute("checked") is None
def test_should_return_the_value_of_selected_for_options_in_selects_even_if_they_lack_that_attribute(driver, pages):
pages.load("formPage.html")
selectBox = driver.find_element(By.XPATH, "//select[@name='selectomatic']")
options = selectBox.find_elements(By.TAG_NAME, "option")
one = options[0]
two = options[1]
assert one.is_selected()
assert not two.is_selected()
assert "true" == one.get_attribute("selected")
assert two.get_attribute("selected") is None
def test_should_return_value_of_class_attribute_of_an_element(driver, pages):
pages.load("xhtmlTest.html")
heading = driver.find_element(By.XPATH, "//h1")
classname = heading.get_attribute("class")
assert "header" == classname
# Disabled due to issues with Frames
# def test_should_return_value_of_class_attribute_of_an_element_after_switching_iframe(driver, pages):
# pages.load("iframes.html")
# driver.switch_to.frame("iframe1")
#
# wallace = driver.find_element(By.XPATH, "//div[@id='wallace']")
# classname = wallace.get_attribute("class")
# assert "gromit" == classname
def test_should_return_the_contents_of_atext_area_as_its_value(driver, pages):
pages.load("formPage.html")
value = driver.find_element(By.ID, "withText").get_attribute("value")
assert "Example text" == value
def test_should_return_the_contents_of_atext_area_as_its_value_when_set_to_non_norminal_true(driver, pages):
pages.load("formPage.html")
e = driver.find_element(By.ID, "withText")
driver.execute_script("arguments[0].value = 'tRuE'", e)
value = e.get_attribute("value")
assert "tRuE" == value
def test_should_treat_readonly_as_avalue(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.NAME, "readonly")
readOnlyAttribute = element.get_attribute("readonly")
textInput = driver.find_element(By.NAME, "x")
notReadOnly = textInput.get_attribute("readonly")
assert readOnlyAttribute != notReadOnly
def test_should_get_numeric_attribute(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "withText")
assert "5" == element.get_attribute("rows")
def test_can_return_atext_approximation_of_the_style_attribute(driver, pages):
pages.load("javascriptPage.html")
style = driver.find_element(By.ID, "red-item").get_attribute("style")
assert "background-color" in style.lower()
def test_should_correctly_report_value_of_colspan(driver, pages):
pages.load("tables.html")
th1 = driver.find_element(By.ID, "th1")
td2 = driver.find_element(By.ID, "td2")
assert "th1" == th1.get_attribute("id")
assert "3" == th1.get_attribute("colspan")
assert "td2" == td2.get_attribute("id")
assert "2" == td2.get_attribute("colspan")
def test_can_retrieve_the_current_value_of_atext_form_field_text_input(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "working")
assert "" == element.get_attribute("value")
element.send_keys("hello world")
assert "hello world" == element.get_attribute("value")
def test_can_retrieve_the_current_value_of_atext_form_field_email_input(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "email")
assert "" == element.get_attribute("value")
element.send_keys("hello@example.com")
assert "hello@example.com" == element.get_attribute("value")
def test_can_retrieve_the_current_value_of_atext_form_field_text_area(driver, pages):
pages.load("formPage.html")
element = driver.find_element(By.ID, "emptyTextArea")
assert "" == element.get_attribute("value")
element.send_keys("hello world")
assert "hello world" == element.get_attribute("value")
def test_should_return_null_for_non_present_boolean_attributes(driver, pages):
pages.load("booleanAttributes.html")
element1 = driver.find_element(By.ID, "working")
assert element1.get_attribute("required") is None
@pytest.mark.xfail_ie
def test_should_return_true_for_present_boolean_attributes(driver, pages):
pages.load("booleanAttributes.html")
element1 = driver.find_element(By.ID, "emailRequired")
assert "true" == element1.get_attribute("required")
element2 = driver.find_element(By.ID, "emptyTextAreaRequired")
assert "true" == element2.get_attribute("required")
element3 = driver.find_element(By.ID, "inputRequired")
assert "true" == element3.get_attribute("required")
element4 = driver.find_element(By.ID, "textAreaRequired")
assert "true" == element4.get_attribute("required")
@pytest.mark.xfail_chrome
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_get_unicode_chars_from_attribute(driver, pages):
pages.load("formPage.html")
title = driver.find_element(By.ID, "vsearchGadget").get_attribute("title")
assert "Hvad s\xf8ger du?" == title
@pytest.mark.xfail_chrome
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_get_values_and_not_miss_items(driver, pages):
pages.load("attributes.html")
expected = "4b273a33fbbd29013nN93dy4F1A~"
result = driver.find_element(By.CSS_SELECTOR, "li").get_attribute("value")
assert expected == result
selenium-selenium-4.18.1/test/selenium/webdriver/common/web_components_tests.py 0000644 0001750 0001750 00000005527 14564764517 030060 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.common.exceptions import NoSuchShadowRootException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.shadowroot import ShadowRoot
from selenium.webdriver.remote.webelement import WebElement
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_can_get_the_shadow_root_of_an_element(driver, pages):
pages.load("webComponents.html")
shadow_root = driver.find_element(By.CSS_SELECTOR, "custom-checkbox-element").shadow_root
assert isinstance(shadow_root, ShadowRoot)
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_no_such_shadow_root_thrown_when_no_shadow_root(driver, pages):
with pytest.raises(NoSuchShadowRootException):
pages.load("simpleTest.html")
driver.find_element(By.CSS_SELECTOR, "div").shadow_root
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_returns_shadow_root_via_execute_script(driver, pages):
pages.load("webComponents.html")
custom_element = driver.find_element(By.CSS_SELECTOR, "custom-checkbox-element")
shadow_root = custom_element.shadow_root
execute_shadow_root = driver.execute_script("return arguments[0].shadowRoot", custom_element)
assert shadow_root == execute_shadow_root
@pytest.mark.xfail_safari
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_find_element_in_a_shadowroot(driver, pages):
pages.load("webComponents.html")
custom_element = driver.find_element(By.CSS_SELECTOR, "custom-checkbox-element")
shadow_root = custom_element.shadow_root
element = shadow_root.find_element(By.CSS_SELECTOR, "input")
assert isinstance(element, WebElement)
@pytest.mark.xfail_safari
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
def test_can_find_elements_in_a_shadow_root(driver, pages):
pages.load("webComponents.html")
custom_element = driver.find_element(By.CSS_SELECTOR, "custom-checkbox-element")
shadow_root = custom_element.shadow_root
elements = shadow_root.find_elements(By.CSS_SELECTOR, "input")
assert len(elements) == 1
assert isinstance(elements[0], WebElement)
selenium-selenium-4.18.1/test/selenium/webdriver/common/element_aria_tests.py 0000644 0001750 0001750 00000003415 14564764517 027455 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_return_explicitly_specified_role(driver):
driver.get("data:text/html,Level 1 Header
")
header1 = driver.find_element(By.CSS_SELECTOR, "div")
assert header1.aria_role == "heading"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_return_implicit_role_defined_by_tag_name(driver):
driver.get("data:text/html,Level 1 Header
")
header1 = driver.find_element(By.CSS_SELECTOR, "h1")
assert header1.aria_role == "heading"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
def test_should_return_explicit_role_even_if_it_contradicts_tag_name(driver):
driver.get("data:text/html,Level 1 Header
")
header1 = driver.find_element(By.CSS_SELECTOR, "h1")
assert header1.aria_role == "alert"
selenium-selenium-4.18.1/test/selenium/webdriver/common/example2.py 0000644 0001750 0001750 00000002234 14564764517 025321 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from google_one_box import GoogleOneBox
def test_search(driver):
"""This example shows how to use the page object pattern.
For more information about this pattern, see:
https://github.com/SeleniumHQ/selenium/wiki/PageObjects"""
google = GoogleOneBox(driver, "http://www.google.com")
res = google.search_for("cheese")
assert res.link_contains_match_for("Wikipedia")
selenium-selenium-4.18.1/test/selenium/webdriver/common/results_page.py 0000644 0001750 0001750 00000002650 14564764517 026303 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.webdriver.common.by import By
class ResultsPage:
"""This class models a google search result page."""
def __init__(self, driver):
self._driver = driver
def is_loaded(self):
return "/search" in self._driver.get_current_url()
def load(self):
raise Exception("This page shouldn't be loaded directly")
def link_contains_match_for(self, term):
result_section = self._driver.find_element(By.ID, "res")
elements = result_section.find_elements(By.XPATH, ".//*[@class='l']")
for e in elements:
if term in e.get_text():
return True
return False
selenium-selenium-4.18.1/test/selenium/webdriver/common/typing_tests.py 0000644 0001750 0001750 00000032427 14564764517 026347 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
def test_should_fire_key_press_events(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("a")
result = driver.find_element(by=By.ID, value="result")
assert "press:" in result.text
def test_should_fire_key_down_events(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("I")
result = driver.find_element(by=By.ID, value="result")
assert "down" in result.text
def test_should_fire_key_up_events(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("a")
result = driver.find_element(by=By.ID, value="result")
assert "up:" in result.text
def test_should_type_lower_case_letters(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("abc def")
assert keyReporter.get_attribute("value") == "abc def"
def test_should_be_able_to_type_capital_letters(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("ABC DEF")
assert keyReporter.get_attribute("value") == "ABC DEF"
def test_should_be_able_to_type_quote_marks(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys('"')
assert keyReporter.get_attribute("value") == '"'
def test_should_be_able_to_type_the_at_character(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("@")
assert keyReporter.get_attribute("value") == "@"
def test_should_be_able_to_mix_upper_and_lower_case_letters(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("me@eXample.com")
assert keyReporter.get_attribute("value") == "me@eXample.com"
def test_arrow_keys_should_not_be_printable(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys(Keys.ARROW_LEFT)
assert keyReporter.get_attribute("value") == ""
def test_list_of_arrow_keys_should_not_be_printable(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys([Keys.ARROW_LEFT])
assert keyReporter.get_attribute("value") == ""
def test_should_be_able_to_use_arrow_keys(driver, pages):
pages.load("javascriptPage.html")
keyReporter = driver.find_element(by=By.ID, value="keyReporter")
keyReporter.send_keys("Tet", Keys.ARROW_LEFT, "s")
assert keyReporter.get_attribute("value") == "Test"
@pytest.mark.xfail_safari
def test_will_simulate_akey_up_when_entering_text_into_input_elements(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyUp")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
assert result.text == "I like cheese"
@pytest.mark.xfail_safari
def test_will_simulate_akey_down_when_entering_text_into_input_elements(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyDown")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
# Because the key down gets the result before the input element is
# filled, we're a letter short here
assert result.text == "I like chees"
@pytest.mark.xfail_safari
def test_will_simulate_akey_press_when_entering_text_into_input_elements(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyPress")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
# Because the key down gets the result before the input element is
# filled, we're a letter short here
assert result.text == "I like chees"
@pytest.mark.xfail_safari
def test_will_simulate_akey_up_when_entering_text_into_text_areas(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyUpArea")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
assert result.text == "I like cheese"
@pytest.mark.xfail_safari
def test_will_simulate_akey_down_when_entering_text_into_text_areas(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyDownArea")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
# Because the key down gets the result before the input element is
# filled, we're a letter short here
assert result.text == "I like chees"
@pytest.mark.xfail_safari
def test_will_simulate_akey_press_when_entering_text_into_text_areas(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyPressArea")
element.send_keys("I like cheese")
result = driver.find_element(by=By.ID, value="result")
# Because the key down gets the result before the input element is
# filled, we're a letter short here
assert result.text == "I like chees"
def test_should_report_key_code_of_arrow_keys_up_down_events(driver, pages):
pages.load("javascriptPage.html")
result = driver.find_element(by=By.ID, value="result")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys(Keys.ARROW_DOWN)
assert "down: 40" in result.text.strip()
assert "up: 40" in result.text.strip()
element.send_keys(Keys.ARROW_UP)
assert "down: 38" in result.text.strip()
assert "up: 38" in result.text.strip()
element.send_keys(Keys.ARROW_LEFT)
assert "down: 37" in result.text.strip()
assert "up: 37" in result.text.strip()
element.send_keys(Keys.ARROW_RIGHT)
assert "down: 39" in result.text.strip()
assert "up: 39" in result.text.strip()
# And leave no rubbish/printable keys in the "keyReporter"
assert element.get_attribute("value") == ""
def test_numeric_non_shift_keys(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
numericLineCharsNonShifted = "`1234567890-=[]\\,.'/42"
element.send_keys(numericLineCharsNonShifted)
assert element.get_attribute("value") == numericLineCharsNonShifted
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
def test_numeric_shift_keys(driver, pages):
pages.load("javascriptPage.html")
result = driver.find_element(by=By.ID, value="result")
element = driver.find_element(by=By.ID, value="keyReporter")
numericShiftsEtc = '~!@#$%^&*()_+{}:i"<>?|END~'
element.send_keys(numericShiftsEtc)
assert element.get_attribute("value") == numericShiftsEtc
assert "up: 16" in result.text.strip()
def test_lower_case_alpha_keys(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
lowerAlphas = "abcdefghijklmnopqrstuvwxyz"
element.send_keys(lowerAlphas)
assert element.get_attribute("value") == lowerAlphas
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
def test_uppercase_alpha_keys(driver, pages):
pages.load("javascriptPage.html")
result = driver.find_element(by=By.ID, value="result")
element = driver.find_element(by=By.ID, value="keyReporter")
upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
element.send_keys(upperAlphas)
assert element.get_attribute("value") == upperAlphas
assert "up: 16" in result.text.strip()
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
def test_all_printable_keys(driver, pages):
pages.load("javascriptPage.html")
result = driver.find_element(by=By.ID, value="result")
element = driver.find_element(by=By.ID, value="keyReporter")
allPrintable = "!\"#$%&'()*+,-./0123456789:<=>?@ ABCDEFGHIJKLMNOPQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
element.send_keys(allPrintable)
assert element.get_attribute("value") == allPrintable
assert "up: 16" in result.text.strip()
def test_arrow_keys_and_page_up_and_down(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys(f"a{Keys.LEFT}b{Keys.RIGHT}{Keys.UP}{Keys.DOWN}{Keys.PAGE_UP}{Keys.PAGE_DOWN}1")
assert element.get_attribute("value") == "ba1"
# def test_home_and_end_and_page_up_and_page_down_keys(driver, pages):
# // FIXME: macs don't have HOME keys, would PGUP work?
# if (Platform.getCurrent().is(Platform.MAC)) {
# return
# }
# pages.load("javascriptPage.html")
# element = driver.find_element(by=By.ID, value="keyReporter")
# element.send_keys("abc" + Keys.HOME + "0" + Keys.LEFT + Keys.RIGHT +
# Keys.PAGE_UP + Keys.PAGE_DOWN + Keys.END + "1" + Keys.HOME +
# "0" + Keys.PAGE_UP + Keys.END + "111" + Keys.HOME + "00")
# assert element.get_attribute("value") == "0000abc1111"
def test_delete_and_backspace_keys(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys("abcdefghi")
assert element.get_attribute("value") == "abcdefghi"
element.send_keys(Keys.LEFT, Keys.LEFT, Keys.DELETE)
assert element.get_attribute("value") == "abcdefgi"
element.send_keys(Keys.LEFT, Keys.LEFT, Keys.BACK_SPACE)
assert element.get_attribute("value") == "abcdfgi"
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
def test_special_space_keys(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys("abcd" + Keys.SPACE + "fgh" + Keys.SPACE + "ij")
assert element.get_attribute("value") == "abcd fgh ij"
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1255258")
@pytest.mark.xfail_safari
def test_numberpad_and_function_keys(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys(
"abcd{}{}{}{}{}{}{}{}{}{}{}{}abcd".format(
Keys.MULTIPLY,
Keys.SUBTRACT,
Keys.ADD,
Keys.DECIMAL,
Keys.SEPARATOR,
Keys.NUMPAD0,
Keys.NUMPAD9,
Keys.ADD,
Keys.SEMICOLON,
Keys.EQUALS,
Keys.DIVIDE,
Keys.NUMPAD3,
)
)
assert element.get_attribute("value") == "abcd*-+.,09+;=/3abcd"
element.clear()
element.send_keys("FUNCTION" + Keys.F2 + "-KEYS" + Keys.F2)
element.send_keys("" + Keys.F2 + "-TOO" + Keys.F2)
assert element.get_attribute("value") == "FUNCTION-KEYS-TOO"
@pytest.mark.xfail_safari
def test_shift_selection_deletes(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys("abcd efgh")
assert element.get_attribute("value") == "abcd efgh"
element.send_keys(Keys.SHIFT, Keys.LEFT, Keys.LEFT, Keys.LEFT)
element.send_keys(Keys.DELETE)
assert element.get_attribute("value") == "abcd e"
def test_should_type_into_input_elements_that_have_no_type_attribute(driver, pages):
pages.load("formPage.html")
element = driver.find_element(by=By.ID, value="no-type")
element.send_keys("Should Say Cheese")
assert element.get_attribute("value") == "Should Say Cheese"
def test_should_type_an_integer(driver, pages):
pages.load("javascriptPage.html")
element = driver.find_element(by=By.ID, value="keyReporter")
element.send_keys(1234)
assert element.get_attribute("value") == "1234"
selenium-selenium-4.18.1/test/selenium/webdriver/common/bidi_tests.py 0000644 0001750 0001750 00000006667 14564764517 025753 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.common.log import Log
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1819965")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1819965")
@pytest.mark.xfail_safari
async def test_check_console_messages(driver, pages):
async with driver.bidi_connection() as session:
log = Log(driver, session)
pages.load("javascriptPage.html")
from selenium.webdriver.common.bidi.console import Console
async with log.add_listener(Console.LOG) as messages:
driver.execute_script("console.log('I love cheese')")
assert messages["message"] == "I love cheese"
@pytest.mark.xfail_firefox(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1819965")
@pytest.mark.xfail_remote(reason="https://bugzilla.mozilla.org/show_bug.cgi?id=1819965")
@pytest.mark.xfail_safari
async def test_check_error_console_messages(driver, pages):
async with driver.bidi_connection() as session:
log = Log(driver, session)
pages.load("javascriptPage.html")
from selenium.webdriver.common.bidi.console import Console
async with log.add_listener(Console.ERROR) as messages:
driver.execute_script('console.error("I don\'t cheese")')
driver.execute_script("console.log('I love cheese')")
assert messages["message"] == "I don't cheese"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
async def test_collect_js_exceptions(driver, pages):
async with driver.bidi_connection() as session:
log = Log(driver, session)
pages.load("javascriptPage.html")
async with log.add_js_error_listener() as exceptions:
driver.find_element(By.ID, "throwing-mouseover").click()
assert exceptions is not None
assert exceptions.exception_details.stack_trace.call_frames[0].function_name == "onmouseover"
@pytest.mark.xfail_firefox
@pytest.mark.xfail_safari
@pytest.mark.xfail_remote
async def test_collect_log_mutations(driver, pages):
async with driver.bidi_connection() as session:
log = Log(driver, session)
async with log.mutation_events() as event:
pages.load("dynamic.html")
driver.find_element(By.ID, "reveal").click()
WebDriverWait(driver, 5).until(EC.visibility_of(driver.find_element(By.ID, "revealed")))
assert event["attribute_name"] == "style"
assert event["current_value"] == ""
assert event["old_value"] == "display:none;"
selenium-selenium-4.18.1/test/selenium/webdriver/common/position_and_size_tests.py 0000644 0001750 0001750 00000011055 14564764517 030547 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
def test_should_be_able_to_determine_the_location_of_an_element(driver, pages):
pages.load("xhtmlTest.html")
location = driver.find_element(By.ID, "username").location_once_scrolled_into_view
assert location["x"] > 0
assert location["y"] > 0
@pytest.mark.parametrize(
"page",
(
"coordinates_tests/simple_page.html",
"coordinates_tests/page_with_empty_element.html",
"coordinates_tests/page_with_transparent_element.html",
"coordinates_tests/page_with_hidden_element.html",
),
ids=("basic", "empty", "transparent", "hidden"),
)
@pytest.mark.xfail_safari
def test_should_get_coordinates_of_an_element(page, driver, pages):
pages.load(page)
element = driver.find_element(By.ID, "box")
_check_location(element.location_once_scrolled_into_view, x=10, y=10)
_check_location(element.location, x=10, y=10)
@pytest.mark.xfail_safari
def test_should_get_coordinates_of_an_invisible_element(driver, pages):
pages.load("coordinates_tests/page_with_invisible_element.html")
element = driver.find_element(By.ID, "box")
_check_location(element.location_once_scrolled_into_view, x=0, y=0)
_check_location(element.location, x=0, y=0)
def test_should_scroll_page_and_get_coordinates_of_an_element_that_is_out_of_view_port(driver, pages):
pages.load("coordinates_tests/page_with_element_out_of_view.html")
element = driver.find_element(By.ID, "box")
windowHeight = driver.get_window_size()["height"]
_check_location(element.location_once_scrolled_into_view, x=10)
assert 0 <= element.location_once_scrolled_into_view["y"] <= (windowHeight - 100)
_check_location(element.location, x=10, y=5010)
@pytest.mark.xfail_chrome
@pytest.mark.xfail_chromiumedge
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
@pytest.mark.xfail_safari
def test_should_get_coordinates_of_an_element_in_aframe(driver, pages):
pages.load("coordinates_tests/element_in_frame.html")
driver.switch_to.frame(driver.find_element(By.NAME, "ifr"))
element = driver.find_element(By.ID, "box")
_check_location(element.location_once_scrolled_into_view, x=25, y=25)
_check_location(element.location, x=10, y=10)
@pytest.mark.xfail_chrome
@pytest.mark.xfail_chromiumedge
@pytest.mark.xfail_firefox
@pytest.mark.xfail_remote
@pytest.mark.xfail_safari
def test_should_get_coordinates_of_an_element_in_anested_frame(driver, pages):
pages.load("coordinates_tests/element_in_nested_frame.html")
driver.switch_to.frame(driver.find_element(By.NAME, "ifr"))
driver.switch_to.frame(driver.find_element(By.NAME, "ifr"))
element = driver.find_element(By.ID, "box")
_check_location(element.location_once_scrolled_into_view, x=40, y=40)
_check_location(element.location, x=10, y=10)
def test_should_get_coordinates_of_an_element_with_fixed_position(driver, pages):
pages.load("coordinates_tests/page_with_fixed_element.html")
element = driver.find_element(By.ID, "fixed")
_check_location(element.location_once_scrolled_into_view, y=0)
_check_location(element.location, y=0)
driver.find_element(By.ID, "bottom").click()
_check_location(element.location_once_scrolled_into_view, y=0)
assert element.location["y"] > 0
def test_should_correctly_identify_that_an_element_has_width_and_height(driver, pages):
pages.load("xhtmlTest.html")
shrinko = driver.find_element(By.ID, "linkId")
size = shrinko.size
assert size["width"] > 0
assert size["height"] > 0
def _check_location(location, **kwargs):
try:
# python 2.x
expected = kwargs.viewitems()
actual = location.viewitems()
except AttributeError:
# python 3.x
expected = kwargs.items()
actual = location.items()
assert expected <= actual
selenium-selenium-4.18.1/test/selenium/webdriver/common/opacity_tests.py 0000644 0001750 0001750 00000003377 14564764517 026507 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
@pytest.mark.xfail_ie
def test_should_be_able_to_click_on_elements_with_opacity_zero(driver, pages):
pages.load("click_jacker.html")
element = driver.find_element(By.ID, "clickJacker")
assert "0" == element.value_of_css_property("opacity"), (
"Precondition failed: clickJacker should be transparent.\
Value was %s"
% element.value_of_css_property("opacity")
)
element.click()
assert "1" == element.value_of_css_property("opacity")
@pytest.mark.xfail_ie
def test_should_be_able_to_select_options_from_an_invisible_select(driver, pages):
pages.load("formPage.html")
select = driver.find_element(By.ID, "invisi_select")
options = select.find_elements(By.TAG_NAME, "option")
apples = options[0]
oranges = options[1]
assert apples.is_selected()
assert not oranges.is_selected()
oranges.click()
assert not apples.is_selected()
assert oranges.is_selected()
selenium-selenium-4.18.1/test/selenium/webdriver/common/webserver.py 0000644 0001750 0001750 00000015227 14564764517 025616 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""A simple web server for testing purpose.
It serves the testing html pages that are needed by the webdriver unit tests."""
import contextlib
import logging
import os
import re
import threading
try:
from urllib import request as urllib_request
except ImportError:
import urllib as urllib_request
try:
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from socketserver import ThreadingMixIn
except ImportError:
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn
def updir():
dirname = os.path.dirname
return dirname(dirname(__file__))
LOGGER = logging.getLogger(__name__)
WEBDRIVER = os.environ.get("WEBDRIVER", updir())
HTML_ROOT = os.path.join(WEBDRIVER, "../../../../common/src/web")
if not os.path.isdir(HTML_ROOT):
message = (
"Can't find 'common_web' directory, try setting WEBDRIVER"
" environment variable WEBDRIVER:" + WEBDRIVER + " HTML_ROOT:" + HTML_ROOT
)
LOGGER.error(message)
assert 0, message
DEFAULT_HOST = "localhost"
DEFAULT_HOST_IP = "127.0.0.1"
DEFAULT_PORT = 8000
class HtmlOnlyHandler(BaseHTTPRequestHandler):
"""Http handler."""
def do_GET(self):
"""GET method handler."""
try:
path = self.path[1:].split("?")[0]
if path[:5] == "page/":
html = """Page{page_number}
Page number {page_number}
top
""".format(
page_number=path[5:]
)
html = html.encode("utf-8")
else:
with open(os.path.join(HTML_ROOT, path), encoding="latin-1") as f:
html = f.read().encode("utf-8")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(html)
except OSError:
self.send_error(404, f"File Not Found: {path}")
def do_POST(self):
"""POST method handler."""
try:
remaining_bytes = int(self.headers["content-length"])
contents = ""
line = self.rfile.readline()
contents += line.decode("utf-8")
remaining_bytes -= len(line)
line = self.rfile.readline()
contents += line.decode("utf-8")
remaining_bytes -= len(line)
fn = re.findall(r'Content-Disposition.*name="upload"; filename="(.*)"', line.decode("utf-8"))
if not fn:
self.send_error(500, f"File not found. {contents}")
return
line = self.rfile.readline()
remaining_bytes -= len(line)
contents += line.decode("utf-8")
line = self.rfile.readline()
remaining_bytes -= len(line)
contents += line.decode("utf-8")
preline = self.rfile.readline()
remaining_bytes -= len(preline)
while remaining_bytes > 0:
line = self.rfile.readline()
remaining_bytes -= len(line)
contents += line.decode("utf-8")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
f"""
{contents}
""".encode()
)
except Exception as e:
self.send_error(500, f"Error found: {e}")
def log_message(self, format, *args):
"""Override default to avoid trashing stderr"""
pass
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
class SimpleWebServer:
"""A very basic web server."""
def __init__(self, host=DEFAULT_HOST_IP, port=DEFAULT_PORT):
self.stop_serving = False
host = host
port = port
while True:
try:
self.server = ThreadedHTTPServer((host, port), HtmlOnlyHandler)
self.host = host
self.port = port
break
except OSError:
LOGGER.debug(f"port {port} is in use, trying to next one")
port += 1
self.thread = threading.Thread(target=self._run_web_server)
def _run_web_server(self):
"""Runs the server loop."""
LOGGER.debug("web server started")
while not self.stop_serving:
self.server.handle_request()
self.server.server_close()
def start(self):
"""Starts the server."""
self.thread.start()
def stop(self):
"""Stops the server."""
self.stop_serving = True
with contextlib.suppress(IOError):
_ = urllib_request.urlopen(f"http://{self.host}:{self.port}")
def where_is(self, path, localhost=False) -> str:
# True force serve the page from localhost
if localhost:
return f"http://{DEFAULT_HOST}:{self.port}/{path}"
return f"http://{self.host}:{self.port}/{path}"
def main(argv=None):
from optparse import OptionParser
from time import sleep
if argv is None:
import sys
argv = sys.argv
parser = OptionParser("%prog [options]")
parser.add_option(
"-p", "--port", dest="port", type="int", help=f"port to listen (default: {DEFAULT_PORT})", default=DEFAULT_PORT
)
opts, args = parser.parse_args(argv[1:])
if args:
parser.error("wrong number of arguments") # Will exit
server = SimpleWebServer(port=opts.port)
server.start()
print(f"Server started on port {opts.port}, hit CTRL-C to quit")
try:
while 1:
sleep(0.1)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
selenium-selenium-4.18.1/test/selenium/webdriver/common/print_pdf_tests.py 0000644 0001750 0001750 00000004561 14564764517 027020 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.print_page_options import PrintOptions
START_INDEX = 0
END_INDEX = 5
PDF_MAGIC_NUMBER = "JVBER"
@pytest.mark.xfail_safari(reason="no endpoint for print in safari")
def test_pdf_with_2_pages(driver, pages):
print_options = PrintOptions()
print_options.page_ranges = ["1-2"]
pages.load("printPage.html")
base64code = driver.print_page(print_options)
assert base64code[START_INDEX:END_INDEX] == PDF_MAGIC_NUMBER
@pytest.mark.xfail_safari(reason="no endpoint for print in safari")
def test_pdf_with_all_pages(driver, pages):
pages.load("printPage.html")
base64code = driver.print_page()
assert base64code[START_INDEX:END_INDEX] == PDF_MAGIC_NUMBER
@pytest.mark.xfail_safari(reason="no endpoint for print in safari")
def test_valid_params(driver, pages):
print_options = PrintOptions()
print_options.page_ranges = ["1-2"]
print_options.orientation = "landscape"
print_options.width = 30
pages.load("printPage.html")
base64code = driver.print_page(print_options)
assert base64code[START_INDEX:END_INDEX] == PDF_MAGIC_NUMBER
@pytest.mark.xfail_safari(reason="no endpoint for print in safari")
def test_session_id_is_not_preserved_after_page_is_printed(driver, pages):
print_options = PrintOptions()
print_options.margin_bottom = print_options.margin_top = print_options.margin_left = print_options.margin_right = 0
assert "sessionId" not in print_options.to_dict()
pages.load("printPage.html")
driver.print_page(print_options=print_options)
assert "sessionId" not in print_options.to_dict()
selenium-selenium-4.18.1/test/selenium/webdriver/common/test_file.txt 0000644 0001750 0001750 00000000033 14564764517 025744 0 ustar carsten carsten lorem ipsum dolor sit amet
selenium-selenium-4.18.1/test/selenium/webdriver/common/text_handling_tests.py 0000644 0001750 0001750 00000016102 14564764517 027655 0 ustar carsten carsten # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from selenium.webdriver.common.by import By
newLine = "\n"
def test_should_return_the_text_content_of_asingle_element_with_no_children(driver, pages):
pages.load("simpleTest.html")
selectText = driver.find_element(by=By.ID, value="oneline").text
assert selectText == "A single line of text"
getText = driver.find_element(by=By.ID, value="oneline").text
assert getText == "A single line of text"
def test_should_return_the_entire_text_content_of_child_elements(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="multiline").text
assert "A div containing" in text
assert "More than one line of text" in text
assert "and block level elements" in text
@pytest.mark.xfail_safari
def test_should_ignore_script_elements(driver, pages):
pages.load("javascriptEnhancedForm.html")
labelForUsername = driver.find_element(by=By.ID, value="labelforusername")
text = labelForUsername.text
assert len(labelForUsername.find_elements(by=By.TAG_NAME, value="script")) == 1
assert "document.getElementById" not in text
assert text == "Username:"
@pytest.mark.xfail_safari
def test_should_represent_ablock_level_element_as_anewline(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="multiline").text
assert text.startswith("A div containing" + newLine)
assert "More than one line of text" + newLine in text
assert text.endswith("and block level elements")
@pytest.mark.xfail_safari
def test_should_collapse_multiple_whitespace_characters_into_asingle_space(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="lotsofspaces").text
assert text == "This line has lots of spaces."
@pytest.mark.xfail_safari
def test_should_trim_text(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="multiline").text
assert text.startswith("A div containing")
assert text.endswith("block level elements")
@pytest.mark.xfail_safari
def test_should_convert_anon_breaking_space_into_anormal_space_character(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="nbsp").text
assert text == "This line has a non-breaking space"
@pytest.mark.xfail_safari
def test_should_treat_anon_breaking_space_as_any_other_whitespace_character_when_collapsing_whitespace(driver, pages):
pages.load("simpleTest.html")
element = driver.find_element(by=By.ID, value="nbspandspaces")
text = element.text
assert text == "This line has a non-breaking space and spaces"
@pytest.mark.xfail_safari
def test_having_inline_elements_should_not_affect_how_text_is_returned(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="inline").text
assert text == "This line has text within elements that are meant to be displayed inline"
@pytest.mark.xfail_safari
def test_should_return_the_entire_text_of_inline_elements(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="span").text
assert text == "An inline element"
def test_should_be_able_to_set_more_than_one_line_of_text_in_atext_area(driver, pages):
pages.load("formPage.html")
textarea = driver.find_element(by=By.ID, value="withText")
textarea.clear()
expectedText = "I like cheese" + newLine + newLine + "It's really nice"
textarea.send_keys(expectedText)
seenText = textarea.get_attribute("value")
assert seenText == expectedText
def test_should_be_able_to_enter_dates_after_filling_in_other_values_first(driver, pages):
pages.load("formPage.html")
input_ = driver.find_element(by=By.ID, value="working")
expectedValue = "10/03/2007 to 30/07/1993"
input_.send_keys(expectedValue)
seenValue = input_.get_attribute("value")
assert seenValue == expectedValue
@pytest.mark.xfail_safari
def test_should_return_empty_string_when_text_is_only_spaces(driver, pages):
pages.load("xhtmlTest.html")
text = driver.find_element(by=By.ID, value="spaces").text
assert text == ""
def test_should_return_empty_string_when_text_is_empty(driver, pages):
pages.load("xhtmlTest.html")
text = driver.find_element(by=By.ID, value="empty").text
assert text == ""
@pytest.mark.xfail
def test_should_return_empty_string_when_tag_is_self_closing(driver, pages):
pages.load("xhtmlFormPage.xhtml")
text = driver.find_element(by=By.ID, value="self-closed").text
assert text == ""
@pytest.mark.xfail_safari
def test_should_handle_sibling_block_level_elements(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="twoblocks").text
assert text == "Some text" + newLine + "Some more text"
@pytest.mark.xfail_safari
def test_should_handle_whitespace_in_inline_elements(driver, pages):
pages.load("simpleTest.html")
text = driver.find_element(by=By.ID, value="inlinespan").text
assert text == "line has text"
def test_read_alarge_amount_of_data(driver, pages):
pages.load("macbeth.html")
source = driver.page_source.strip().lower()
assert source.endswith("