diff --git a/docs/_templates/genindex.html b/docs/_templates/genindex.html
index 60c19efd4..89885dce0 100644
--- a/docs/_templates/genindex.html
+++ b/docs/_templates/genindex.html
@@ -1,4 +1,4 @@
{% extends "!genindex.html" %}
{% block bodyclass %}{% endblock %}
-{% block sidebarwrapper %}{% endblock %}
\ No newline at end of file
+{% block sidebarwrapper %}{% endblock %}
diff --git a/docs/_templates/modindex.html b/docs/_templates/modindex.html
index 96a1d2080..75a38e192 100644
--- a/docs/_templates/modindex.html
+++ b/docs/_templates/modindex.html
@@ -1,3 +1,3 @@
{% extends "!modindex.html" %}
{% block bodyclass %}{% endblock %}
-{% block sidebarwrapper %}{% endblock %}
\ No newline at end of file
+{% block sidebarwrapper %}{% endblock %}
diff --git a/docs/_templates/search.html b/docs/_templates/search.html
index 8bd6dbd33..99198dbe0 100644
--- a/docs/_templates/search.html
+++ b/docs/_templates/search.html
@@ -1,3 +1,3 @@
{% extends "!search.html" %}
{% block bodyclass %}{% endblock %}
-{% block sidebarwrapper %}{% endblock %}
\ No newline at end of file
+{% block sidebarwrapper %}{% endblock %}
diff --git a/docs/api/index.rst b/docs/api/index.rst
index 0b03f2f1e..bf7a56b0f 100644
--- a/docs/api/index.rst
+++ b/docs/api/index.rst
@@ -20,4 +20,3 @@ Welcome to the Splinter API documentation! Check what's inside:
element-list
request-handling
exceptions
-
diff --git a/docs/api/request-handling.rst b/docs/api/request-handling.rst
index 6de622fc7..e4cce5207 100644
--- a/docs/api/request-handling.rst
+++ b/docs/api/request-handling.rst
@@ -11,4 +11,3 @@ Request handling
.. autoclass:: splinter.request_handler.status_code.StatusCode
:members:
-
diff --git a/docs/conf.py b/docs/conf.py
index db4e981b1..900ecf710 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
#
# splinter documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 8 23:31:41 2011.
@@ -10,12 +9,10 @@
#
# All configuration values have a default; values that are commented out
# serve to show the default.
-
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
-
import os
import sys
from datetime import datetime
@@ -47,8 +44,8 @@
master_doc = "index"
# General information about the project.
-project = u"Splinter"
-copyright = u"{}, cobrateam".format(datetime.now().year)
+project = "Splinter"
+copyright = f"{datetime.now().year}, cobrateam"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -109,7 +106,7 @@
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
- 'collapse_navigation': False,
+ "collapse_navigation": False,
}
# Add any paths that contain custom themes here, relative to this directory.
@@ -192,7 +189,7 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
- ("index", "splinter.tex", u"splinter Documentation", u"andrews medina", "manual")
+ ("index", "splinter.tex", "splinter Documentation", "andrews medina", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -223,4 +220,4 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
-man_pages = [("index", "splinter", u"splinter Documentation", [u"andrews medina"], 1)]
+man_pages = [("index", "splinter", "splinter Documentation", ["andrews medina"], 1)]
diff --git a/docs/selenium-keys.rst b/docs/selenium-keys.rst
index ca999f78c..21c74e419 100644
--- a/docs/selenium-keys.rst
+++ b/docs/selenium-keys.rst
@@ -24,4 +24,4 @@ With Splinter's type() method, you can use Selenium's Keys implementation.
browser.type(Keys.RETURN)
The full list of all supported keys can be found at the official Selenium documentation:
-`selenium.webdriver.common.keys `_
\ No newline at end of file
+`selenium.webdriver.common.keys `_
diff --git a/samples/test_facebook_events.py b/samples/test_facebook_events.py
index 79a40ed4e..e213a02f1 100755
--- a/samples/test_facebook_events.py
+++ b/samples/test_facebook_events.py
@@ -1,18 +1,15 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
"""
This snippet show how to "test" a Facebook feature: the creation of an event.
It creates an event by going to http://www.facebook.com, login and navigate to "Create an event" page.
"""
-
import os
-import unittest
import time
+import unittest
+
from splinter import Browser
@@ -30,7 +27,7 @@ def do_login_if_need(self, username, password):
self.browser.fill("email", username)
self.browser.fill("pass", password)
self.browser.find_by_css(
- 'div.menu_login_container input[type="submit"]'
+ 'div.menu_login_container input[type="submit"]',
).first.click()
assert self.browser.is_element_present_by_css("li#navAccount")
@@ -49,12 +46,15 @@ def test_create_event(self):
# Uploading the picture
picture_path = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), "img", "turtles.jpg"
+ os.path.abspath(os.path.dirname(__file__)),
+ "img",
+ "turtles.jpg",
)
self.browser.find_by_css("div.eventEditUpload a.uiButton").first.click()
if not self.browser.is_element_present_by_css(
- "iframe#upload_pic_frame", wait_time=10
+ "iframe#upload_pic_frame",
+ wait_time=10,
):
self.fail("The upload pic iframe didn't appear :(")
@@ -68,7 +68,8 @@ def test_create_event(self):
self.browser.fill("name", "Splinter sprint")
self.browser.fill("location", "Rio de Janeiro, Brazil")
self.browser.fill(
- "desc", "For more info, check out the #cobratem channel on freenode!"
+ "desc",
+ "For more info, check out the #cobratem channel on freenode!",
)
self.browser.find_by_css('label.uiButton input[type="submit"]').first.click()
diff --git a/samples/test_google_search.py b/samples/test_google_search.py
index 785a18b8b..e35367c57 100755
--- a/samples/test_google_search.py
+++ b/samples/test_google_search.py
@@ -1,10 +1,9 @@
#!/usr/bin/env python
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import unittest
+
from splinter import Browser
diff --git a/setup.py b/setup.py
index acbab54bd..3a63cc6ad 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -10,7 +9,7 @@
def read(filename: str) -> str:
path = os.path.join(os.path.dirname(__file__), filename)
- with open(path, "r") as f:
+ with open(path) as f:
return f.read()
diff --git a/splinter/__init__.py b/splinter/__init__.py
index d80952635..a7b8a013e 100644
--- a/splinter/__init__.py
+++ b/splinter/__init__.py
@@ -1,13 +1,13 @@
# Copyright 2016 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from splinter.browser import Browser
from splinter.config import Config
-from splinter.version import __version_info__, __version__ # NOQA
+from splinter.version import __version__ # noqa: F401
+from splinter.version import __version_info__ # noqa: F401
__all__ = [
- 'Browser',
- 'Config',
+ "Browser",
+ "Config",
]
diff --git a/splinter/browser.py b/splinter/browser.py
index d3eb8f145..793118058 100644
--- a/splinter/browser.py
+++ b/splinter/browser.py
@@ -1,14 +1,12 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-
import logging
-
from http.client import HTTPException
-from typing import Dict, Tuple, Type, Union
+from typing import Dict
+from typing import Tuple
+from typing import Type
+from typing import Union
from urllib3.exceptions import MaxRetryError
@@ -21,19 +19,20 @@
try:
from selenium.common.exceptions import WebDriverException
+
driver_exceptions += (WebDriverException,)
except ImportError as e:
logger.debug(f"Import Warning: {e}")
_DRIVERS: Dict[str, Union[None, Type[DriverAPI]]] = {
- 'chrome': None,
- 'edge': None,
- 'firefox': None,
- 'remote': None,
- 'django': None,
- 'flask': None,
- 'zope.testbrowser': None,
+ "chrome": None,
+ "edge": None,
+ "firefox": None,
+ "remote": None,
+ "django": None,
+ "flask": None,
+ "zope.testbrowser": None,
}
try:
@@ -41,18 +40,18 @@
from splinter.driver.webdriver.firefox import WebDriver as FirefoxWebDriver
from splinter.driver.webdriver.remote import WebDriver as RemoteWebDriver
- _DRIVERS['chrome'] = ChromeWebDriver
- _DRIVERS['firefox'] = FirefoxWebDriver
- _DRIVERS['remote'] = RemoteWebDriver
+ _DRIVERS["chrome"] = ChromeWebDriver
+ _DRIVERS["firefox"] = FirefoxWebDriver
+ _DRIVERS["remote"] = RemoteWebDriver
except ImportError as e:
- logger.debug(f'Import Warning: {e}')
+ logger.debug(f"Import Warning: {e}")
try:
from splinter.driver.webdriver.edge import WebDriver as EdgeWebDriver
_DRIVERS["edge"] = EdgeWebDriver
except ImportError as e:
- logger.debug(f'Import Warning: {e}')
+ logger.debug(f"Import Warning: {e}")
try:
@@ -60,7 +59,7 @@
_DRIVERS["zope.testbrowser"] = ZopeTestBrowser
except ImportError as e:
- logger.debug(f'Import Warning: {e}')
+ logger.debug(f"Import Warning: {e}")
try:
import django # noqa
@@ -68,7 +67,7 @@
_DRIVERS["django"] = DjangoClient
except ImportError as e:
- logger.debug(f'Import Warning: {e}')
+ logger.debug(f"Import Warning: {e}")
try:
import flask # noqa
@@ -76,7 +75,7 @@
_DRIVERS["flask"] = FlaskClient
except ImportError as e:
- logger.debug(f'Import Warning: {e}')
+ logger.debug(f"Import Warning: {e}")
def get_driver(driver, retry_count=3, config=None, *args, **kwargs):
@@ -97,7 +96,13 @@ def get_driver(driver, retry_count=3, config=None, *args, **kwargs):
raise err
-def Browser(driver_name: str = "firefox", retry_count: int = 3, config=None, *args, **kwargs): # NOQA: N802
+def Browser(
+ driver_name: str = "firefox",
+ retry_count: int = 3,
+ config=None,
+ *args,
+ **kwargs,
+): # NOQA: N802
"""Get a new driver instance.
Extra arguments will be sent to the driver instance.
@@ -117,9 +122,9 @@ def Browser(driver_name: str = "firefox", retry_count: int = 3, config=None, *ar
try:
driver = _DRIVERS[driver_name]
except KeyError:
- raise DriverNotFoundError(f'{driver_name} is not a recognized driver.')
+ raise DriverNotFoundError(f"{driver_name} is not a recognized driver.")
if driver is None:
- raise DriverNotFoundError(f'Driver for {driver_name} was not found.')
+ raise DriverNotFoundError(f"Driver for {driver_name} was not found.")
return get_driver(driver, retry_count=retry_count, config=config, *args, **kwargs)
diff --git a/splinter/config.py b/splinter/config.py
index 0d29bad46..a955bf4af 100644
--- a/splinter/config.py
+++ b/splinter/config.py
@@ -1,5 +1,6 @@
from dataclasses import dataclass
-from typing import List, Optional
+from typing import List
+from typing import Optional
@dataclass
@@ -43,6 +44,7 @@ class Config:
user_agent: Set a custom user_agent.
"""
+
extensions: Optional[List[str]] = None
fullscreen: Optional[bool] = False
headless: Optional[bool] = False
diff --git a/splinter/cookie_manager.py b/splinter/cookie_manager.py
index 725418dc2..bbd64bc95 100644
--- a/splinter/cookie_manager.py
+++ b/splinter/cookie_manager.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from splinter.meta import InheritedDocs
diff --git a/splinter/driver/__init__.py b/splinter/driver/__init__.py
index d25df6f0f..8db227891 100644
--- a/splinter/driver/__init__.py
+++ b/splinter/driver/__init__.py
@@ -1,18 +1,16 @@
-# -*- coding: utf-8 -*-:
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
"""
This module contains the basic API for splinter drivers and elements.
"""
+from typing import Any
+from typing import Optional
+from typing import Type
-from typing import Any, Optional, Type
-
-from splinter.meta import InheritedDocs
-from splinter.element_list import ElementList
from splinter.cookie_manager import CookieManagerAPI
+from splinter.element_list import ElementList
+from splinter.meta import InheritedDocs
class DriverAPI(InheritedDocs("_DriverAPI", (object,), {})): # type: ignore
@@ -20,39 +18,39 @@ class DriverAPI(InheritedDocs("_DriverAPI", (object,), {})): # type: ignore
Basic driver API class.
"""
- driver_name: str = ''
+ driver_name: str = ""
@property
def title(self) -> str:
"""Title of current page."""
raise NotImplementedError(
- "%s doesn't support access to the title." % self.driver_name
+ "%s doesn't support access to the title." % self.driver_name,
)
def __enter__(self) -> Any:
"""Context manager to use the browser safely."""
raise NotImplementedError(
- "%s doesn't support use by 'with' statement." % self.driver_name
+ "%s doesn't support use by 'with' statement." % self.driver_name,
)
def __exit__(self) -> None:
"""Context manager to use the browser safely."""
raise NotImplementedError(
- "%s doesn't support use by 'with' statement." % self.driver_name
+ "%s doesn't support use by 'with' statement." % self.driver_name,
)
@property
def html(self) -> str:
"""Source of current page."""
raise NotImplementedError(
- "%s doesn't support access to the html." % self.driver_name
+ "%s doesn't support access to the html." % self.driver_name,
)
@property
def url(self) -> str:
"""URL of current page."""
raise NotImplementedError(
- "%s doesn't support access to the url." % self.driver_name
+ "%s doesn't support access to the url." % self.driver_name,
)
def visit(self, url: str) -> None:
@@ -77,7 +75,7 @@ def back(self) -> None:
If there is no previous URL, this method does nothing.
"""
raise NotImplementedError(
- "%s doesn't support moving back in history." % self.driver_name
+ "%s doesn't support moving back in history." % self.driver_name,
)
def forward(self) -> None:
@@ -86,13 +84,13 @@ def forward(self) -> None:
If there is no URL to forward, this method does nothing.
"""
raise NotImplementedError(
- "%s doesn't support moving forward in history." % self.driver_name
+ "%s doesn't support moving forward in history." % self.driver_name,
)
def reload(self) -> None:
"""Revisits the current URL."""
raise NotImplementedError(
- "%s doesn't support reloading the page." % self.driver_name
+ "%s doesn't support reloading the page." % self.driver_name,
)
def get_alert(self) -> Any:
@@ -120,7 +118,7 @@ def execute_script(self, script: str, *args: str) -> Any:
>>> browser.execute_script('document.getElementById("body").innerHTML = "Hello world!
"')
"""
raise NotImplementedError(
- "%s doesn't support execution of arbitrary JavaScript." % self.driver_name
+ "%s doesn't support execution of arbitrary JavaScript." % self.driver_name,
)
def evaluate_script(self, script: str, *args: str) -> Any:
@@ -137,7 +135,7 @@ def evaluate_script(self, script: str, *args: str) -> Any:
>>> assert 4 == browser.evaluate_script('2 + 2')
"""
raise NotImplementedError(
- "%s doesn't support evaluation of arbitrary JavaScript." % self.driver_name
+ "%s doesn't support evaluation of arbitrary JavaScript." % self.driver_name,
)
def find_by_css(self, css_selector: str) -> ElementList:
@@ -150,7 +148,7 @@ def find_by_css(self, css_selector: str) -> ElementList:
"""
raise NotImplementedError(
- "%s doesn't support finding elements by css selector." % self.driver_name
+ "%s doesn't support finding elements by css selector." % self.driver_name,
)
def find_by_xpath(self, xpath: str) -> ElementList:
@@ -163,7 +161,7 @@ def find_by_xpath(self, xpath: str) -> ElementList:
"""
raise NotImplementedError(
- "%s doesn't support finding elements by xpath selector." % self.driver_name
+ "%s doesn't support finding elements by xpath selector." % self.driver_name,
)
def find_by_name(self, name: str) -> ElementList:
@@ -176,7 +174,7 @@ def find_by_name(self, name: str) -> ElementList:
"""
raise NotImplementedError(
- "%s doesn't support finding elements by name." % self.driver_name
+ "%s doesn't support finding elements by name." % self.driver_name,
)
def find_by_id(self, id: str) -> ElementList: # NOQA: A002
@@ -189,7 +187,7 @@ def find_by_id(self, id: str) -> ElementList: # NOQA: A002
id (str): id to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding elements by id." % self.driver_name
+ "%s doesn't support finding elements by id." % self.driver_name,
)
def find_by_value(self, value: str) -> ElementList:
@@ -201,7 +199,7 @@ def find_by_value(self, value: str) -> ElementList:
value (str): value to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding elements by value." % self.driver_name
+ "%s doesn't support finding elements by value." % self.driver_name,
)
def find_by_text(self, text: str) -> ElementList:
@@ -213,7 +211,7 @@ def find_by_text(self, text: str) -> ElementList:
text (str): text to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding elements by text." % self.driver_name
+ "%s doesn't support finding elements by text." % self.driver_name,
)
def find_by_tag(self, tag: str) -> ElementList:
@@ -225,7 +223,7 @@ def find_by_tag(self, tag: str) -> ElementList:
tag (str): tag to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding elements by tag." % self.driver_name
+ "%s doesn't support finding elements by tag." % self.driver_name,
)
def find_option_by_value(self, value: str) -> ElementList:
@@ -238,7 +236,7 @@ def find_option_by_value(self, value: str) -> ElementList:
value (str): value to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding options by value." % self.driver_name
+ "%s doesn't support finding options by value." % self.driver_name,
)
def find_option_by_text(self, text: str) -> ElementList:
@@ -251,7 +249,7 @@ def find_option_by_text(self, text: str) -> ElementList:
text (str): text to use in the search query.
"""
raise NotImplementedError(
- "%s doesn't support finding options by text." % self.driver_name
+ "%s doesn't support finding options by text." % self.driver_name,
)
def is_text_present(self, text: str, wait_time: Optional[int] = None) -> bool:
@@ -266,7 +264,7 @@ def is_text_present(self, text: str, wait_time: Optional[int] = None) -> bool:
"""
raise NotImplementedError(
"%s doesn't support checking if some text is present in the html. "
- % self.driver_name
+ % self.driver_name,
)
def type(self, name: str, value: str, slowly: bool = False) -> str: # NOQA: A003
@@ -280,7 +278,7 @@ def type(self, name: str, value: str, slowly: bool = False) -> str: # NOQA: A00
slowly (bool): If True, this function returns an iterator which will type one character per iteration.
"""
raise NotImplementedError(
- "%s doesn't support typing on fields by name." % self.driver_name
+ "%s doesn't support typing on fields by name." % self.driver_name,
)
def fill(self, name: str, value: str) -> None:
@@ -291,7 +289,7 @@ def fill(self, name: str, value: str) -> None:
value (str): Value to enter into the element.
"""
raise NotImplementedError(
- "%s doesn't support filling fields by name." % self.driver_name
+ "%s doesn't support filling fields by name." % self.driver_name,
)
def fill_form(
@@ -315,7 +313,7 @@ def fill_form(
ignore_missing (bool): Ignore missing keys in the dict.
"""
raise NotImplementedError(
- "%s doesn't support filling forms with a dict." % self.driver_name
+ "%s doesn't support filling forms with a dict." % self.driver_name,
)
def choose(self, name: str, value: str) -> None:
@@ -334,7 +332,7 @@ def choose(self, name: str, value: str) -> None:
Then the female gender will be chosen.
"""
raise NotImplementedError(
- "%s doesn't support choosing options." % self.driver_name
+ "%s doesn't support choosing options." % self.driver_name,
)
def check(self, name: str) -> None:
@@ -352,7 +350,7 @@ def check(self, name: str) -> None:
To uncheck a checkbox, take a look in the :meth:`uncheck ` method.
"""
raise NotImplementedError(
- "%s doesn't support checking elements." % self.driver_name
+ "%s doesn't support checking elements." % self.driver_name,
)
def uncheck(self, name: str) -> None:
@@ -370,7 +368,7 @@ def uncheck(self, name: str) -> None:
To check a checkbox, take a look in the :meth:`check ` method.
"""
raise NotImplementedError(
- "%s doesn't support unchecking elements." % self.driver_name
+ "%s doesn't support unchecking elements." % self.driver_name,
)
def select(self, name: str, value: str) -> None:
@@ -388,14 +386,18 @@ def select(self, name: str, value: str) -> None:
"""
raise NotImplementedError(
"%s doesn't support selecting options in 'select' element."
- % self.driver_name
+ % self.driver_name,
)
def quit(self) -> None: # NOQA: A003
"""Quit the browser, closing its windows (if it has one)."""
raise NotImplementedError("%s doesn't support quit" % self.driver_name)
- def is_element_present_by_css(self, css_selector: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_css(
+ self,
+ css_selector: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -407,10 +409,14 @@ def is_element_present_by_css(self, css_selector: str, wait_time: Optional[int]
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by css"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_css(self, css_selector: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_css(
+ self,
+ css_selector: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -422,10 +428,14 @@ def is_element_not_present_by_css(self, css_selector: str, wait_time: Optional[i
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by css"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_xpath(self, xpath: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_xpath(
+ self,
+ xpath: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -437,10 +447,14 @@ def is_element_present_by_xpath(self, xpath: str, wait_time: Optional[int] = Non
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by xpath"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_xpath(self, xpath: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_xpath(
+ self,
+ xpath: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -452,10 +466,14 @@ def is_element_not_present_by_xpath(self, xpath: str, wait_time: Optional[int] =
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by xpath"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_tag(self, tag: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_tag(
+ self,
+ tag: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -467,10 +485,14 @@ def is_element_present_by_tag(self, tag: str, wait_time: Optional[int] = None) -
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by tag"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_tag(self, tag: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_tag(
+ self,
+ tag: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -482,10 +504,14 @@ def is_element_not_present_by_tag(self, tag: str, wait_time: Optional[int] = Non
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by tag"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_name(self, name: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_name(
+ self,
+ name: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -497,10 +523,14 @@ def is_element_present_by_name(self, name: str, wait_time: Optional[int] = None)
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by name"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_name(self, name: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_name(
+ self,
+ name: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -512,10 +542,14 @@ def is_element_not_present_by_name(self, name: str, wait_time: Optional[int] = N
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by name"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_value(self, value: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_value(
+ self,
+ value: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -527,10 +561,14 @@ def is_element_present_by_value(self, value: str, wait_time: Optional[int] = Non
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by value"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_value(self, value: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_value(
+ self,
+ value: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -542,10 +580,14 @@ def is_element_not_present_by_value(self, value: str, wait_time: Optional[int] =
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by value"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_text(self, text: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_present_by_text(
+ self,
+ text: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is present in the current page.
Arguments:
@@ -557,10 +599,14 @@ def is_element_present_by_text(self, text: str, wait_time: Optional[int] = None)
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by text"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_text(self, text: str, wait_time: Optional[int] = None) -> bool:
+ def is_element_not_present_by_text(
+ self,
+ text: str,
+ wait_time: Optional[int] = None,
+ ) -> bool:
"""Verify if an element is not present in the current page.
Arguments:
@@ -572,10 +618,14 @@ def is_element_not_present_by_text(self, text: str, wait_time: Optional[int] = N
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by text"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_present_by_id(self, id: str, wait_time: Optional[int] = None) -> bool: # NOQA: A002
+ def is_element_present_by_id(
+ self,
+ id: str,
+ wait_time: Optional[int] = None,
+ ) -> bool: # NOQA: A002
"""Verify if an element is present in the current page.
Arguments:
@@ -587,10 +637,14 @@ def is_element_present_by_id(self, id: str, wait_time: Optional[int] = None) ->
"""
raise NotImplementedError(
"%s doesn't support verifying if element is present by id"
- % self.driver_name
+ % self.driver_name,
)
- def is_element_not_present_by_id(self, id: str, wait_time: Optional[int] = None) -> bool: # NOQA: A002
+ def is_element_not_present_by_id(
+ self,
+ id: str,
+ wait_time: Optional[int] = None,
+ ) -> bool: # NOQA: A002
"""Verify if an element is not present in the current page.
Arguments:
@@ -602,7 +656,7 @@ def is_element_not_present_by_id(self, id: str, wait_time: Optional[int] = None)
"""
raise NotImplementedError(
"%s doesn't support verifying if element is not present by id"
- % self.driver_name
+ % self.driver_name,
)
def screenshot(
@@ -626,14 +680,14 @@ def screenshot(
str: Full file name of the created screenshot.
"""
raise NotImplementedError(
- "%s doesn't support taking screenshots." % self.driver_name
+ "%s doesn't support taking screenshots." % self.driver_name,
)
def html_snapshot(
self,
name: str = "",
suffix: str = ".html",
- encoding: str = 'utf-8',
+ encoding: str = "utf-8",
unique_file: bool = True,
) -> str:
"""Write the current html to a file.
@@ -651,7 +705,7 @@ def html_snapshot(
"""
raise NotImplementedError(
- f"{self.driver_name} doesn't support taking screenshots."
+ f"{self.driver_name} doesn't support taking screenshots.",
)
@property
@@ -662,7 +716,7 @@ def cookies(self) -> Type[CookieManagerAPI]:
For more details, check the :doc:`cookies manipulation section `.
"""
raise NotImplementedError(
- "%s doesn't support cookies manipulation" % self.driver_name
+ "%s doesn't support cookies manipulation" % self.driver_name,
)
diff --git a/splinter/driver/djangoclient.py b/splinter/driver/djangoclient.py
index 3f65803a0..0565c79f5 100644
--- a/splinter/driver/djangoclient.py
+++ b/splinter/driver/djangoclient.py
@@ -1,17 +1,14 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from typing import Optional
from urllib import parse
+from .lxmldriver import LxmlDriver
from splinter.config import Config
from splinter.cookie_manager import CookieManagerAPI
from splinter.request_handler.status_code import StatusCode
-from .lxmldriver import LxmlDriver
-
class CookieManager(CookieManagerAPI):
def add(self, cookie, **kwargs):
@@ -53,7 +50,6 @@ def __eq__(self, other_object):
class DjangoClient(LxmlDriver):
-
driver_name = "django"
def __init__(
@@ -76,7 +72,11 @@ def __init__(
self._cookie_manager = CookieManager(self._browser)
- super(DjangoClient, self).__init__(wait_time=wait_time, user_agent=user_agent, config=config)
+ super().__init__(
+ wait_time=wait_time,
+ user_agent=user_agent,
+ config=config,
+ )
def __enter__(self):
return self
@@ -120,14 +120,14 @@ def _do_method(self, method, url, data=None, record_url=True):
if record_url:
self._last_url_index += 1
# Going to a new URL always crops the url history
- self._last_urls = self._last_urls[:self._last_url_index]
+ self._last_urls = self._last_urls[: self._last_url_index]
self._last_urls.append(url)
self._handle_redirect_chain()
self._post_load()
def submit_data(self, form):
- return super(DjangoClient, self).submit(form).content
+ return super().submit(form).content
@property
def html(self):
diff --git a/splinter/driver/element_present.py b/splinter/driver/element_present.py
index 2555ac52b..60e409011 100644
--- a/splinter/driver/element_present.py
+++ b/splinter/driver/element_present.py
@@ -1,5 +1,5 @@
class ElementPresentMixIn:
- """ Support is_element_present_by_* methods for non-javascript drivers. """
+ """Support is_element_present_by_* methods for non-javascript drivers."""
def is_element_present_by_css(self, css_selector, wait_time=None):
return bool(self.find_by_css(css_selector))
diff --git a/splinter/driver/find_links.py b/splinter/driver/find_links.py
index b0a672391..f88676069 100644
--- a/splinter/driver/find_links.py
+++ b/splinter/driver/find_links.py
@@ -17,28 +17,28 @@ def __init__(self, parent) -> None:
def find_by_href(self, href: str) -> ElementList:
return self.parent.find_by_xpath(
- '//a[@href="{}"]'.format(href),
+ f'//a[@href="{href}"]',
original_find="link by href",
original_query=href,
)
def find_by_partial_href(self, partial_href: str) -> ElementList:
return self.parent.find_by_xpath(
- '//a[contains(@href, "{}")]'.format(partial_href),
+ f'//a[contains(@href, "{partial_href}")]',
original_find="link by partial href",
original_query=partial_href,
)
def find_by_partial_text(self, partial_text: str) -> ElementList:
return self.parent.find_by_xpath(
- '//a[contains(normalize-space(.), "{}")]'.format(partial_text),
+ f'//a[contains(normalize-space(.), "{partial_text}")]',
original_find="link by partial text",
original_query=partial_text,
)
def find_by_text(self, text: str) -> ElementList:
return self.parent.find_by_xpath(
- '//a[text()="{}"]'.format(text),
+ f'//a[text()="{text}"]',
original_find="link by text",
original_query=text,
)
diff --git a/splinter/driver/flaskclient.py b/splinter/driver/flaskclient.py
index 27a320702..d567ab8b4 100644
--- a/splinter/driver/flaskclient.py
+++ b/splinter/driver/flaskclient.py
@@ -1,24 +1,24 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from typing import Optional
-from urllib.parse import parse_qs, urlparse, urlencode, urlunparse
+from urllib.parse import parse_qs
+from urllib.parse import urlencode
+from urllib.parse import urlparse
+from urllib.parse import urlunparse
+from .lxmldriver import LxmlDriver
from splinter.config import Config
from splinter.cookie_manager import CookieManagerAPI
from splinter.request_handler.status_code import StatusCode
-from .lxmldriver import LxmlDriver
-
class CookieManager(CookieManagerAPI):
def add(self, cookie, **kwargs):
for key, value in cookie.items():
- kwargs['server_name'] = "localhost"
- kwargs['key'] = key
- kwargs['value'] = value
+ kwargs["server_name"] = "localhost"
+ kwargs["key"] = key
+ kwargs["value"] = value
self.driver.set_cookie(**kwargs)
def delete(self, *cookies):
@@ -56,7 +56,6 @@ def __eq__(self, other_object):
class FlaskClient(LxmlDriver):
-
driver_name = "flask"
def __init__(
@@ -71,7 +70,7 @@ def __init__(
self._browser = app.test_client()
self._cookie_manager = CookieManager(self._browser)
self._custom_headers = custom_headers if custom_headers else {}
- super(FlaskClient, self).__init__(wait_time=wait_time)
+ super().__init__(wait_time=wait_time)
def __enter__(self):
return self
@@ -88,7 +87,6 @@ def _post_load(self):
self.status_code = StatusCode(self._response.status_code, "")
def _do_method(self, method, url, data=None, record_url=True):
-
# Set the initial URL and client/HTTP method
self._url = url
func_method = getattr(self._browser, method.lower())
@@ -98,13 +96,12 @@ def _do_method(self, method, url, data=None, record_url=True):
if record_url:
self._last_url_index += 1
# Going to a new URL always crops the url history
- self._last_urls = self._last_urls[:self._last_url_index]
+ self._last_urls = self._last_urls[: self._last_url_index]
self._last_urls.append(url)
# If we're making a GET request set the data against the URL as a
# query.
if method.lower() == "get":
-
# Parse the existing URL and it's query
url_parts = urlparse(url)
url_params = parse_qs(url_parts.query)
@@ -123,7 +120,10 @@ def _do_method(self, method, url, data=None, record_url=True):
# Call the flask client
self._response = func_method(
- url, headers=self._custom_headers, data=data, follow_redirects=False
+ url,
+ headers=self._custom_headers,
+ data=data,
+ follow_redirects=False,
)
# Implement more standard `302`/`303` behaviour
@@ -142,7 +142,7 @@ def _do_method(self, method, url, data=None, record_url=True):
self._post_load()
def submit_data(self, form):
- return super(FlaskClient, self).submit(form).data
+ return super().submit(form).data
@property
def html(self):
diff --git a/splinter/driver/lxmldriver.py b/splinter/driver/lxmldriver.py
index d1c3390c4..810a404d1 100644
--- a/splinter/driver/lxmldriver.py
+++ b/splinter/driver/lxmldriver.py
@@ -1,11 +1,8 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import re
import time
-
from typing import Optional
from urllib import parse
@@ -14,9 +11,10 @@
from lxml.cssselect import CSSSelector
from splinter.config import Config
-from splinter.driver import DriverAPI, ElementAPI
-from splinter.driver.find_links import FindLinks
+from splinter.driver import DriverAPI
+from splinter.driver import ElementAPI
from splinter.driver.element_present import ElementPresentMixIn
+from splinter.driver.find_links import FindLinks
from splinter.driver.xpath_utils import _concat_xpath_from_str
from splinter.element_list import ElementList
from splinter.exceptions import ElementDoesNotExist
@@ -50,7 +48,7 @@ def __exit__(self, exc_type, exc_value, traceback):
def _do_method(self, action, url, data=None):
raise NotImplementedError(
- "%s doesn't support doing http methods." % self.driver_name
+ "%s doesn't support doing http methods." % self.driver_name,
)
def visit(self, url):
@@ -88,7 +86,7 @@ def submit(self, form):
method = form.attrib.get("method", "get").lower()
action = form.attrib.get("action", "")
- if action.strip() not in ['.', '']:
+ if action.strip() not in [".", ""]:
url = parse.urljoin(self._url, action)
else:
url = self._url
@@ -100,18 +98,28 @@ def submit(self, form):
def submit_data(self, form):
raise NotImplementedError(
- "%s doesn't support submitting then getting the data." % self.driver_name
+ "%s doesn't support submitting then getting the data." % self.driver_name,
)
def back(self):
if self._last_url_index >= 1:
self._last_url_index -= 1
- self._do_method("get", self._last_urls[self._last_url_index], record_url=False)
+ self._do_method(
+ "get",
+ self._last_urls[self._last_url_index],
+ record_url=False,
+ )
def forward(self):
- if (self._last_url_index >= 0) and (self._last_url_index < len(self._last_urls) - 1):
+ if (self._last_url_index >= 0) and (
+ self._last_url_index < len(self._last_urls) - 1
+ ):
self._last_url_index += 1
- self._do_method("get", self._last_urls[self._last_url_index], record_url=False)
+ self._do_method(
+ "get",
+ self._last_urls[self._last_url_index],
+ record_url=False,
+ )
def reload(self):
self.visit(self._url)
@@ -135,7 +143,7 @@ def title(self):
@property
def html(self):
raise NotImplementedError(
- "%s doesn't support getting the html of the response." % self.driver_name
+ "%s doesn't support getting the html of the response." % self.driver_name,
)
@property
@@ -147,7 +155,9 @@ def find_option_by_value(self, value):
element = html.xpath('//option[@value="%s"]' % value)[0]
control = LxmlControlElement(element.getparent(), self)
return ElementList(
- [LxmlOptionElement(element, control)], find_by="value", query=value
+ [LxmlOptionElement(element, control)],
+ find_by="value",
+ query=value,
)
def find_option_by_text(self, text):
@@ -155,14 +165,14 @@ def find_option_by_text(self, text):
element = html.xpath('//option[normalize-space(text())="%s"]' % text)[0]
control = LxmlControlElement(element.getparent(), self)
return ElementList(
- [LxmlOptionElement(element, control)], find_by="text", query=text
+ [LxmlOptionElement(element, control)],
+ find_by="text",
+ query=text,
)
def find_by_css(self, selector):
xpath = CSSSelector(selector).path
- return self.find_by_xpath(
- xpath, original_find="css", original_query=selector
- )
+ return self.find_by_xpath(xpath, original_find="css", original_query=selector)
def find_by_xpath(self, xpath, original_find=None, original_query=None):
html = self.htmltree
@@ -187,13 +197,13 @@ def find_by_xpath(self, xpath, original_find=None, original_query=None):
)
def find_by_tag(self, tag):
- return self.find_by_xpath(
- "//%s" % tag, original_find="tag", original_query=tag
- )
+ return self.find_by_xpath("//%s" % tag, original_find="tag", original_query=tag)
def find_by_value(self, value):
elem = self.find_by_xpath(
- '//*[@value="%s"]' % value, original_find="value", original_query=value
+ '//*[@value="%s"]' % value,
+ original_find="value",
+ original_query=value,
)
if elem:
return elem
@@ -258,9 +268,7 @@ def fill_form(self, field_values, form_id=None, name=None, ignore_missing=False)
else:
control.value = []
elif control_type == "radio":
- control.value = (
- value
- ) # [option for option in control.options if option == value]
+ control.value = value # [option for option in control.options if option == value]
elif control_type == "select":
if isinstance(value, list):
control.value = value
@@ -369,7 +377,7 @@ def find_by_value(self, value):
def find_by_text(self, text):
# Add a period to the xpath to search only inside the parent.
- xpath_str = '.{}'.format(_concat_xpath_from_str(text))
+ xpath_str = f".{_concat_xpath_from_str(text)}"
return self.find_by_xpath(xpath_str)
def find_by_id(self, id): # NOQA: A002
@@ -390,7 +398,11 @@ def outer_html(self):
@property
def html(self):
- return re.match(r"^<[^<>]+>(.*)[^<>]+>$", self.outer_html, re.MULTILINE | re.DOTALL).group(1)
+ return re.match(
+ r"^<[^<>]+>(.*)[^<>]+>$",
+ self.outer_html,
+ re.MULTILINE | re.DOTALL,
+ ).group(1)
def has_class(self, class_name):
return len(self._element.find_class(class_name)) > 0
@@ -398,11 +410,11 @@ def has_class(self, class_name):
class LxmlLinkElement(LxmlElement):
def __init__(self, element, parent):
- super(LxmlLinkElement, self).__init__(element, parent)
+ super().__init__(element, parent)
self._browser = parent
def __getitem__(self, attr):
- return super(LxmlLinkElement, self).__getitem__(attr)
+ return super().__getitem__(attr)
def click(self):
return self._browser.visit(self["href"])
@@ -436,7 +448,7 @@ def click(self):
if name:
value = self._control.get("value", "")
parent_form.append(
- lxml.html.Element("input", name=name, value=value, type="hidden")
+ lxml.html.Element("input", name=name, value=value, type="hidden"),
)
return self.parent.submit_data(parent_form)
diff --git a/splinter/driver/webdriver/__init__.py b/splinter/driver/webdriver/__init__.py
index cca383a60..9390aeb6c 100644
--- a/splinter/driver/webdriver/__init__.py
+++ b/splinter/driver/webdriver/__init__.py
@@ -1,10 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-import io
import os
import re
import tempfile
@@ -12,25 +8,24 @@
from contextlib import contextmanager
from typing import Optional
-from selenium.webdriver.common.alert import Alert
-from selenium.common.exceptions import (
- ElementClickInterceptedException,
- NoSuchElementException,
- WebDriverException,
- StaleElementReferenceException,
- TimeoutException,
- MoveTargetOutOfBoundsException,
-)
+from selenium.common.exceptions import ElementClickInterceptedException
+from selenium.common.exceptions import MoveTargetOutOfBoundsException
+from selenium.common.exceptions import NoSuchElementException
+from selenium.common.exceptions import StaleElementReferenceException
+from selenium.common.exceptions import TimeoutException
+from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
+from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC # NOQA: N812
from selenium.webdriver.support.ui import WebDriverWait
-from splinter.driver import DriverAPI, ElementAPI
+from splinter.driver import DriverAPI
+from splinter.driver import ElementAPI
from splinter.driver.find_links import FindLinks
+from splinter.driver.webdriver.cookie_manager import CookieManager
from splinter.driver.xpath_utils import _concat_xpath_from_str
from splinter.element_list import ElementList
-from splinter.driver.webdriver.cookie_manager import CookieManager
from splinter.exceptions import ElementDoesNotExist
from splinter.retry import _retry
@@ -64,7 +59,7 @@ def __exit__(self, type, value, traceback): # NOQA: A002
class Window:
- """ A class representing a browser window """
+ """A class representing a browser window"""
def __init__(self, browser, name):
self._browser = browser
@@ -72,31 +67,31 @@ def __init__(self, browser, name):
@property
def title(self):
- """ The title of this window """
+ """The title of this window"""
with switch_window(self._browser, self.name):
return self._browser.title
@property
def url(self):
- """ The url of this window """
+ """The url of this window"""
with switch_window(self._browser, self.name):
return self._browser.url
@property
def index(self):
- """ The index of this window in browser.windows """
+ """The index of this window in browser.windows"""
return self._browser.driver.window_handles.index(self.name)
@property
def prev(self):
- """ Return the previous window """
+ """Return the previous window"""
prev_index = self.index - 1
prev_handle = self._browser.driver.window_handles[prev_index]
return Window(self._browser, prev_handle)
@property # NOQA: A003
def next(self): # NOQA: A003
- """ Return the next window """
+ """Return the next window"""
next_index = (self.index + 1) % len(self._browser.driver.window_handles)
next_handle = self._browser.driver.window_handles[next_index]
return Window(self._browser, next_handle)
@@ -118,30 +113,34 @@ def fset(self, value):
is_current = property(**is_current())
def new_tab(self, url):
- """ Open new tab in current window """
- if self._browser.driver.name == 'firefox':
- self._browser.driver.get('about:config')
- self._browser.driver.execute_script('document.getElementById("warningButton").click();')
+ """Open new tab in current window"""
+ if self._browser.driver.name == "firefox":
+ self._browser.driver.get("about:config")
+ self._browser.driver.execute_script(
+ 'document.getElementById("warningButton").click();',
+ )
self._browser.driver.execute_script(
"""
Components.classes['@mozilla.org/preferences-service;1']
.getService(Components.interfaces.nsIPrefBranch)
.setIntPref('browser.link.open_newwindow', 3);
- """)
+ """,
+ )
self._browser.driver.execute_script("window.open('%s', '_blank');" % url)
- if self._browser.driver.name == 'firefox':
+ if self._browser.driver.name == "firefox":
self._browser.driver.execute_script(
"""
Components.classes['@mozilla.org/preferences-service;1']
.getService(Components.interfaces.nsIPrefBranch)
.setIntPref('browser.link.open_newwindow', 2);
- """)
+ """,
+ )
self._browser.driver.back()
def close(self):
- """ Close this window. If this window is active, switch to previous window """
+ """Close this window. If this window is active, switch to previous window"""
target = self.prev if (self.is_current and self.prev != self) else None
with switch_window(self._browser, self.name):
@@ -163,12 +162,12 @@ def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
- return "" % (self.name, self.url)
+ return f""
class Windows:
- """ A class representing all open browser windows """
+ """A class representing all open browser windows"""
def __init__(self, browser):
self._browser = browser
@@ -204,7 +203,7 @@ def __repr__(self):
[
Window(self._browser, handle)
for handle in self._browser.driver.window_handles
- ]
+ ],
)
@@ -238,7 +237,9 @@ def _find(self, finder, finder_kwargs=None):
pass
if elements:
- elem_list = [self.element_class(element, self, finder_kwargs) for element in elements]
+ elem_list = [
+ self.element_class(element, self, finder_kwargs) for element in elements
+ ]
return elem_list
@@ -261,8 +262,8 @@ def find_by(
"""
elem_list = []
- find_by = original_find or finder_kwargs['by']
- query = original_query or finder_kwargs.get('value')
+ find_by = original_find or finder_kwargs["by"]
+ query = original_query or finder_kwargs.get("value")
# Zero second wait time means only check once
if wait_time == 0:
@@ -436,7 +437,6 @@ def is_text_not_present(self, text, wait_time=None):
@contextmanager
def get_iframe(self, frame_reference):
-
# If a WebDriverElement is provided, send the underlying element
if isinstance(frame_reference, WebDriverElement):
frame_reference = frame_reference._element
@@ -465,17 +465,23 @@ def find_option_by_text(self, text):
def find_by_css(self, css_selector, wait_time=None):
return self.find_by(
self.driver.find_elements,
- finder_kwargs={'by': By.CSS_SELECTOR, 'value': css_selector},
+ finder_kwargs={"by": By.CSS_SELECTOR, "value": css_selector},
original_find="css",
original_query=css_selector,
wait_time=wait_time,
)
- def find_by_xpath(self, xpath, original_find="xpath", original_query=None, wait_time=None):
+ def find_by_xpath(
+ self,
+ xpath,
+ original_find="xpath",
+ original_query=None,
+ wait_time=None,
+ ):
original_query = original_query or xpath
return self.find_by(
self.driver.find_elements,
- finder_kwargs={'by': By.XPATH, 'value': xpath},
+ finder_kwargs={"by": By.XPATH, "value": xpath},
original_find=original_find,
original_query=original_query,
wait_time=wait_time,
@@ -484,22 +490,22 @@ def find_by_xpath(self, xpath, original_find="xpath", original_query=None, wait_
def find_by_name(self, name, wait_time=None):
return self.find_by(
self.driver.find_elements,
- finder_kwargs={'by': By.NAME, 'value': name},
- original_find='name',
+ finder_kwargs={"by": By.NAME, "value": name},
+ original_find="name",
wait_time=wait_time,
)
def find_by_tag(self, tag, wait_time=None):
return self.find_by(
self.driver.find_elements,
- finder_kwargs={'by': By.TAG_NAME, 'value': tag},
- original_find='tag_name',
+ finder_kwargs={"by": By.TAG_NAME, "value": tag},
+ original_find="tag_name",
wait_time=wait_time,
)
def find_by_value(self, value, wait_time=None):
elem = self.find_by_xpath(
- '//*[@value="{}"]'.format(value),
+ f'//*[@value="{value}"]',
original_find="value",
original_query=value,
wait_time=wait_time,
@@ -520,8 +526,8 @@ def find_by_text(self, text=None, wait_time=None):
def find_by_id(self, id, wait_time=None): # NOQA: A002
return self.find_by(
self.driver.find_element,
- finder_kwargs={'by': By.ID, 'value': id},
- original_find='id',
+ finder_kwargs={"by": By.ID, "value": id},
+ original_find="id",
wait_time=wait_time,
)
@@ -588,7 +594,7 @@ def uncheck(self, name):
self.find_by_name(name).first.uncheck()
def screenshot(self, name="", suffix=".png", full=False, unique_file=True):
- filename = '{}{}'.format(name, suffix)
+ filename = f"{name}{suffix}"
if unique_file:
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
@@ -606,27 +612,33 @@ def screenshot(self, name="", suffix=".png", full=False, unique_file=True):
return filename
- def html_snapshot(self, name="", suffix=".html", encoding='utf-8', unique_file=True):
- filename = '{}{}'.format(name, suffix)
+ def html_snapshot(
+ self,
+ name="",
+ suffix=".html",
+ encoding="utf-8",
+ unique_file=True,
+ ):
+ filename = f"{name}{suffix}"
if unique_file:
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
# Don't hold the file
os.close(fd)
- with io.open(filename, 'w', encoding=encoding) as f:
+ with open(filename, "w", encoding=encoding) as f:
f.write(self.html)
return filename
def select(self, name, value):
self.find_by_xpath(
- '//select[@name="%s"]//option[@value="%s"]' % (name, value)
+ f'//select[@name="{name}"]//option[@value="{value}"]',
).first._element.click()
def select_by_text(self, name, text):
self.find_by_xpath(
- '//select[@name="%s"]/option[text()="%s"]' % (name, text)
+ f'//select[@name="{name}"]/option[text()="{text}"]',
).first._element.click()
def quit(self): # NOQA: A003
@@ -636,13 +648,17 @@ def quit(self): # NOQA: A003
pass
def full_screen(self):
- width = self.driver.execute_script("return Math.max(document.body.scrollWidth, document.body.offsetWidth);")
- height = self.driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight);")
+ width = self.driver.execute_script(
+ "return Math.max(document.body.scrollWidth, document.body.offsetWidth);",
+ )
+ height = self.driver.execute_script(
+ "return Math.max(document.body.scrollHeight, document.body.offsetHeight);",
+ )
self.driver.set_window_size(width, height)
def recover_screen(self, size):
- width = size.get('width')
- height = size.get('height')
+ width = size.get("width")
+ height = size.get("height")
self.driver.set_window_size(width, height)
@property
@@ -654,7 +670,7 @@ def windows(self):
return Windows(self)
-class TypeIterator(object):
+class TypeIterator:
def __init__(self, element, keys):
self._element = element
self._keys = keys
@@ -679,7 +695,7 @@ def __init__(self, element, parent):
def _find(self, by: By, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': by, 'value': selector},
+ finder_kwargs={"by": by, "value": selector},
wait_time=wait_time,
)
@@ -754,14 +770,14 @@ def select(self, value=None, text=None):
search_value = None
if text:
- finder = 'text()'
+ finder = "text()"
search_value = text
elif value:
- finder = '@value'
+ finder = "@value"
search_value = value
self.find_by_xpath(
- './/option[{}="{}"]'.format(finder, search_value)
+ f'.//option[{finder}="{search_value}"]',
)._element.click()
def select_by_text(self, text):
@@ -832,7 +848,7 @@ def _refresh_element(self, wait_time: Optional[int] = None):
element_list = self.find_by(
self.parent._find_elements,
finder_kwargs=self._finder_kwargs,
- original_find=self._finder_kwargs['by'],
+ original_find=self._finder_kwargs["by"],
wait_time=wait_time,
)
@@ -891,15 +907,21 @@ def search() -> bool:
def find_by_css(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.CSS_SELECTOR, 'value': selector},
+ finder_kwargs={"by": By.CSS_SELECTOR, "value": selector},
original_find="css",
wait_time=wait_time,
)
- def find_by_xpath(self, selector, wait_time=None, original_find="xpath", original_query=None):
+ def find_by_xpath(
+ self,
+ selector,
+ wait_time=None,
+ original_find="xpath",
+ original_query=None,
+ ):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.XPATH, 'value': selector},
+ finder_kwargs={"by": By.XPATH, "value": selector},
original_find=original_find,
original_query=original_query,
wait_time=wait_time,
@@ -908,7 +930,7 @@ def find_by_xpath(self, selector, wait_time=None, original_find="xpath", origina
def find_by_name(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.NAME, 'value': selector},
+ finder_kwargs={"by": By.NAME, "value": selector},
original_find="name",
wait_time=wait_time,
)
@@ -916,17 +938,17 @@ def find_by_name(self, selector, wait_time=None):
def find_by_tag(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.TAG_NAME, 'value': selector},
+ finder_kwargs={"by": By.TAG_NAME, "value": selector},
original_find="tag",
wait_time=wait_time,
)
def find_by_value(self, value, wait_time=None):
- selector = '[value="{}"]'.format(value)
+ selector = f'[value="{value}"]'
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.CSS_SELECTOR, 'value': selector},
+ finder_kwargs={"by": By.CSS_SELECTOR, "value": selector},
original_find="value",
original_query=value,
wait_time=wait_time,
@@ -934,11 +956,11 @@ def find_by_value(self, value, wait_time=None):
def find_by_text(self, text, wait_time=None):
# Add a period to the xpath to search only inside the parent.
- xpath_str = '.{}'.format(_concat_xpath_from_str(text))
+ xpath_str = f".{_concat_xpath_from_str(text)}"
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.XPATH, 'value': xpath_str},
+ finder_kwargs={"by": By.XPATH, "value": xpath_str},
original_find="text",
original_query=text,
wait_time=wait_time,
@@ -947,14 +969,14 @@ def find_by_text(self, text, wait_time=None):
def find_by_id(self, selector, wait_time=None):
return self.find_by(
self._element.find_elements,
- finder_kwargs={'by': By.ID, 'value': selector},
+ finder_kwargs={"by": By.ID, "value": selector},
original_find="id",
wait_time=wait_time,
)
def has_class(self, class_name):
return bool(
- re.search(r"(?:^|\s)" + re.escape(class_name) + r"(?:$|\s)", self["class"])
+ re.search(r"(?:^|\s)" + re.escape(class_name) + r"(?:$|\s)", self["class"]),
)
def scroll_to(self):
@@ -974,14 +996,23 @@ def mouse_out(self):
try:
# Fails on left edge of viewport
ActionChains(self.driver).move_to_element_with_offset(
- self._element, -10, -10).click().perform()
+ self._element,
+ -10,
+ -10,
+ ).click().perform()
except MoveTargetOutOfBoundsException:
try:
ActionChains(self.driver).move_to_element_with_offset(
- self._element, size['width'] + 10, 10).click().perform()
+ self._element,
+ size["width"] + 10,
+ 10,
+ ).click().perform()
except MoveTargetOutOfBoundsException:
ActionChains(self.driver).move_to_element_with_offset(
- self._element, 10, size['height'] + 10).click().perform()
+ self._element,
+ 10,
+ size["height"] + 10,
+ ).click().perform()
def double_click(self):
"""Perform a double click in the element."""
@@ -996,16 +1027,22 @@ def right_click(self):
def drag_and_drop(self, droppable):
"""Drag an element to another element."""
self.scroll_to()
- ActionChains(self.driver).drag_and_drop(self._element, droppable._element).perform()
+ ActionChains(self.driver).drag_and_drop(
+ self._element,
+ droppable._element,
+ ).perform()
def _full_screen(self):
- width = self.driver.execute_script("return Math.max(document.body.scrollWidth, document.body.offsetWidth);")
- height = self.driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight);")
+ width = self.driver.execute_script(
+ "return Math.max(document.body.scrollWidth, document.body.offsetWidth);",
+ )
+ height = self.driver.execute_script(
+ "return Math.max(document.body.scrollHeight, document.body.offsetHeight);",
+ )
self.driver.set_window_size(width, height)
- def screenshot(self, name='', suffix='.png', full=False, unique_file=True):
-
- filename = '{}{}'.format(name, suffix)
+ def screenshot(self, name="", suffix=".png", full=False, unique_file=True):
+ filename = f"{name}{suffix}"
if unique_file:
(fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
@@ -1020,8 +1057,8 @@ def screenshot(self, name='', suffix='.png', full=False, unique_file=True):
if full:
# Restore screen size
- width = ori_window_size.get('width')
- height = ori_window_size.get('height')
+ width = ori_window_size.get("width")
+ height = ori_window_size.get("height")
self.driver.set_window_size(width, height)
return filename
diff --git a/splinter/driver/webdriver/chrome.py b/splinter/driver/webdriver/chrome.py
index d160300c4..c8cfb7383 100644
--- a/splinter/driver/webdriver/chrome.py
+++ b/splinter/driver/webdriver/chrome.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -11,12 +9,11 @@
from selenium.webdriver.chrome.service import Service
from splinter.config import Config
-from splinter.driver.webdriver.setup import _setup_chrome
from splinter.driver.webdriver import BaseWebDriver
+from splinter.driver.webdriver.setup import _setup_chrome
class WebDriver(BaseWebDriver):
-
driver_name = "Chrome"
def __init__(
@@ -29,10 +26,9 @@ def __init__(
headless=False,
service: Optional[Service] = None,
config: Optional[Config] = None,
- **kwargs
+ **kwargs,
):
-
- if 'executable_path' in kwargs:
+ if "executable_path" in kwargs:
warnings.warn(
(
"Webdriver's executable_path argument has been deprecated."
@@ -42,9 +38,9 @@ def __init__(
stacklevel=2,
)
if service is None:
- service = Service(executable_path=kwargs['executable_path'])
+ service = Service(executable_path=kwargs["executable_path"])
else:
- service.executable_path = kwargs['executable_path']
+ service.executable_path = kwargs["executable_path"]
if True in [fullscreen, incognito, headless] or user_agent:
warnings.warn(
@@ -66,6 +62,12 @@ def __init__(
user_agent=user_agent,
)
- driver = _setup_chrome(Chrome, config=self.config, options=options, service=service, **kwargs)
+ driver = _setup_chrome(
+ Chrome,
+ config=self.config,
+ options=options,
+ service=service,
+ **kwargs,
+ )
- super(WebDriver, self).__init__(driver, wait_time)
+ super().__init__(driver, wait_time)
diff --git a/splinter/driver/webdriver/cookie_manager.py b/splinter/driver/webdriver/cookie_manager.py
index e5fa667e5..1bed7cbd3 100644
--- a/splinter/driver/webdriver/cookie_manager.py
+++ b/splinter/driver/webdriver/cookie_manager.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -11,8 +9,8 @@
class CookieManager(CookieManagerAPI):
def add(self, cookie, **kwargs):
for key, value in cookie.items():
- kwargs['name'] = key
- kwargs['value'] = value
+ kwargs["name"] = key
+ kwargs["value"] = value
self.driver.add_cookie(kwargs)
def delete(self, *cookies):
diff --git a/splinter/driver/webdriver/edge.py b/splinter/driver/webdriver/edge.py
index 21b04cacc..357bd8592 100644
--- a/splinter/driver/webdriver/edge.py
+++ b/splinter/driver/webdriver/edge.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2021 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -11,12 +9,11 @@
from selenium.webdriver.edge.service import Service
from splinter.config import Config
-from splinter.driver.webdriver.setup import _setup_edge
from splinter.driver.webdriver import BaseWebDriver
+from splinter.driver.webdriver.setup import _setup_edge
class WebDriver(BaseWebDriver):
-
driver_name = "Edge"
def __init__(
@@ -30,10 +27,9 @@ def __init__(
chromium=True,
service: Optional[Service] = None,
config: Optional[Config] = None,
- **kwargs
+ **kwargs,
):
-
- if 'executable_path' in kwargs:
+ if "executable_path" in kwargs:
warnings.warn(
(
"Webdriver's executable_path argument has been deprecated."
@@ -43,9 +39,9 @@ def __init__(
stacklevel=2,
)
if service is None:
- service = Service(executable_path=kwargs['executable_path'])
+ service = Service(executable_path=kwargs["executable_path"])
else:
- service.executable_path = kwargs['executable_path']
+ service.executable_path = kwargs["executable_path"]
if True in [fullscreen, incognito, headless] or user_agent:
warnings.warn(
@@ -68,6 +64,12 @@ def __init__(
user_agent=user_agent,
)
- driver = _setup_edge(Edge, config=self.config, options=options, service=service, **kwargs)
+ driver = _setup_edge(
+ Edge,
+ config=self.config,
+ options=options,
+ service=service,
+ **kwargs,
+ )
- super(WebDriver, self).__init__(driver, wait_time)
+ super().__init__(driver, wait_time)
diff --git a/splinter/driver/webdriver/firefox.py b/splinter/driver/webdriver/firefox.py
index 5b2132b59..d94e8d26c 100644
--- a/splinter/driver/webdriver/firefox.py
+++ b/splinter/driver/webdriver/firefox.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -11,12 +9,11 @@
from selenium.webdriver.firefox.service import Service
from splinter.config import Config
-from splinter.driver.webdriver.setup import _setup_firefox
from splinter.driver.webdriver import BaseWebDriver
+from splinter.driver.webdriver.setup import _setup_firefox
class WebDriver(BaseWebDriver):
-
driver_name = "Firefox"
def __init__(
@@ -33,10 +30,9 @@ def __init__(
incognito=False,
service: Optional[Service] = None,
config: Optional[Config] = None,
- **kwargs
+ **kwargs,
):
-
- if 'executable_path' in kwargs:
+ if "executable_path" in kwargs:
warnings.warn(
(
"Webdriver's executable_path argument has been deprecated."
@@ -46,9 +42,9 @@ def __init__(
stacklevel=2,
)
if service is None:
- service = Service(executable_path=kwargs['executable_path'])
+ service = Service(executable_path=kwargs["executable_path"])
else:
- service.executable_path = kwargs['executable_path']
+ service.executable_path = kwargs["executable_path"]
if True in [fullscreen, incognito, headless] or user_agent:
warnings.warn(
@@ -84,6 +80,12 @@ def __init__(
for key, value in profile_preferences.items():
options.set_preference(key, value)
- driver = _setup_firefox(Firefox, config=self.config, options=options, service=service, **kwargs)
+ driver = _setup_firefox(
+ Firefox,
+ config=self.config,
+ options=options,
+ service=service,
+ **kwargs,
+ )
- super(WebDriver, self).__init__(driver, wait_time)
+ super().__init__(driver, wait_time)
diff --git a/splinter/driver/webdriver/remote.py b/splinter/driver/webdriver/remote.py
index 6da04a9d3..1135649e2 100644
--- a/splinter/driver/webdriver/remote.py
+++ b/splinter/driver/webdriver/remote.py
@@ -1,30 +1,24 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from typing import Optional
from selenium.webdriver import Remote
-from selenium.webdriver.remote import remote_connection
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
+from selenium.webdriver.remote import remote_connection
from splinter.config import Config
-
from splinter.driver.webdriver import BaseWebDriver
from splinter.driver.webdriver.remote_connection import patch_request
-from splinter.driver.webdriver.setup import (
- _setup_chrome,
- _setup_edge,
- _setup_firefox,
-)
+from splinter.driver.webdriver.setup import _setup_chrome
+from splinter.driver.webdriver.setup import _setup_edge
+from splinter.driver.webdriver.setup import _setup_firefox
# MonkeyPatch RemoteConnection
remote_connection.RemoteConnection._request = patch_request # type: ignore
class WebDriver(BaseWebDriver):
-
driver_name = "remote"
# TODO: This constant belongs in selenium.webdriver.Remote
DEFAULT_URL = "http://127.0.0.1:4444/wd/hub"
@@ -45,30 +39,30 @@ def __init__(
# If no desired capabilities specified, add default ones
caps = getattr(DesiredCapabilities, browser_name, {})
- if kwargs.get('desired_capabilities'):
+ if kwargs.get("desired_capabilities"):
# Combine user's desired capabilities with default
- caps.update(kwargs['desired_capabilities'])
+ caps.update(kwargs["desired_capabilities"])
- kwargs['desired_capabilities'] = caps
+ kwargs["desired_capabilities"] = caps
- kwargs['command_executor'] = command_executor
+ kwargs["command_executor"] = command_executor
self.config = config or Config()
- if browser_name == 'CHROME':
+ if browser_name == "CHROME":
from selenium.webdriver.chrome.options import Options
options = options or Options()
driver = _setup_chrome(Remote, self.config, options, **kwargs)
- elif browser_name == 'EDGE':
+ elif browser_name == "EDGE":
from selenium.webdriver.edge.options import Options
options = options or Options()
driver = _setup_edge(Remote, self.config, options, **kwargs)
- elif browser_name == 'FIREFOX':
+ elif browser_name == "FIREFOX":
from selenium.webdriver.firefox.options import Options
options = options or Options()
driver = _setup_firefox(Remote, self.config, options, **kwargs)
- super(WebDriver, self).__init__(driver, wait_time)
+ super().__init__(driver, wait_time)
diff --git a/splinter/driver/webdriver/remote_connection.py b/splinter/driver/webdriver/remote_connection.py
index b68e13f17..b2bb369e7 100644
--- a/splinter/driver/webdriver/remote_connection.py
+++ b/splinter/driver/webdriver/remote_connection.py
@@ -1,10 +1,8 @@
-import socket
from http.client import HTTPException
import urllib3
-from urllib3.exceptions import MaxRetryError
-
from selenium.webdriver.remote import remote_connection
+from urllib3.exceptions import MaxRetryError
# Get the original _request and store for future use in the monkey patched version as 'super'
@@ -13,11 +11,11 @@
def patch_request(self, *args, **kwargs):
"""Override _request to set socket timeout to some appropriate value."""
- exception = HTTPException('Unable to get response')
+ exception = HTTPException("Unable to get response")
for _ in range(3):
try:
return old_request(self, *args, **kwargs)
- except (socket.error, HTTPException, IOError, OSError, MaxRetryError) as exc:
+ except (OSError, HTTPException, MaxRetryError) as exc:
exception = exc
self._conn = urllib3.PoolManager(timeout=self._timeout)
raise exception
diff --git a/splinter/driver/xpath_utils.py b/splinter/driver/xpath_utils.py
index 2ca03fd59..50c9fd69d 100644
--- a/splinter/driver/xpath_utils.py
+++ b/splinter/driver/xpath_utils.py
@@ -9,11 +9,11 @@ def _concat_xpath_from_str(text: str) -> str:
"""
concat_text = _recurse(
text,
- split_on='\"',
+ split_on='"',
wrapper="'{}',",
replacer="'\"',",
)
- return '//*[text()=concat({} "")]'.format(concat_text)
+ return f'//*[text()=concat({concat_text} "")]'
def _recurse(
@@ -39,7 +39,7 @@ def _recurse(
str
"""
- final_value = ''
+ final_value = ""
split_text = text.split(split_on)
# Ignore single length split lists in nested searches.
@@ -50,7 +50,7 @@ def _recurse(
# Check every block of text for a single quotation mark
sub_block = _recurse(
item,
- split_on="\'",
+ split_on="'",
wrapper='"{}",',
replacer='"\'",',
inner=True,
diff --git a/splinter/driver/zopetestbrowser.py b/splinter/driver/zopetestbrowser.py
index 01dd5816b..89e6964f7 100644
--- a/splinter/driver/zopetestbrowser.py
+++ b/splinter/driver/zopetestbrowser.py
@@ -1,36 +1,32 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-from __future__ import unicode_literals
-
import mimetypes
import re
import time
-
from typing import Optional
import lxml.html
from lxml.cssselect import CSSSelector
-from zope.testbrowser.browser import Browser, ListControl
+from zope.testbrowser.browser import Browser
+from zope.testbrowser.browser import ListControl
from splinter.config import Config
-from splinter.element_list import ElementList
-from splinter.exceptions import ElementDoesNotExist
-from splinter.driver import DriverAPI, ElementAPI
+from splinter.cookie_manager import CookieManagerAPI
+from splinter.driver import DriverAPI
+from splinter.driver import ElementAPI
from splinter.driver.element_present import ElementPresentMixIn
from splinter.driver.find_links import FindLinks
from splinter.driver.xpath_utils import _concat_xpath_from_str
-from splinter.cookie_manager import CookieManagerAPI
+from splinter.element_list import ElementList
+from splinter.exceptions import ElementDoesNotExist
class CookieManager(CookieManagerAPI):
def add(self, cookie, **kwargs):
for key, value in cookie.items():
- kwargs['name'] = key
- kwargs['value'] = value
+ kwargs["name"] = key
+ kwargs["value"] = value
if key not in self.driver.cookies:
self.driver.cookies.create(**kwargs)
else:
@@ -66,7 +62,6 @@ def __eq__(self, other_object):
class ZopeTestBrowser(ElementPresentMixIn, DriverAPI):
-
driver_name = "zope.testbrowser"
def __init__(self, wait_time=2, config: Optional[Config] = None):
@@ -129,7 +124,9 @@ def find_option_by_value(self, value):
element = html.xpath('//option[@value="%s"]' % value)[0]
control = self._browser.getControl(element.text)
return ElementList(
- [ZopeTestBrowserOptionElement(control, self)], find_by="value", query=value
+ [ZopeTestBrowserOptionElement(control, self)],
+ find_by="value",
+ query=value,
)
def find_option_by_text(self, text):
@@ -137,14 +134,14 @@ def find_option_by_text(self, text):
element = html.xpath('//option[normalize-space(text())="%s"]' % text)[0]
control = self._browser.getControl(element.text)
return ElementList(
- [ZopeTestBrowserOptionElement(control, self)], find_by="text", query=text
+ [ZopeTestBrowserOptionElement(control, self)],
+ find_by="text",
+ query=text,
)
def find_by_css(self, selector):
xpath = CSSSelector(selector).path
- return self.find_by_xpath(
- xpath, original_find="css", original_query=selector
- )
+ return self.find_by_xpath(xpath, original_find="css", original_query=selector)
def get_control(self, xpath_element):
return xpath_element
@@ -172,13 +169,13 @@ def find_by_xpath(self, xpath, original_find=None, original_query=None):
)
def find_by_tag(self, tag):
- return self.find_by_xpath(
- "//%s" % tag, original_find="tag", original_query=tag
- )
+ return self.find_by_xpath("//%s" % tag, original_find="tag", original_query=tag)
def find_by_value(self, value):
elem = self.find_by_xpath(
- '//*[@value="%s"]' % value, original_find="value", original_query=value
+ '//*[@value="%s"]' % value,
+ original_find="value",
+ original_query=value,
)
if elem:
return elem
@@ -263,7 +260,7 @@ def attach_file(self, name, file_path):
filename = file_path.split("/")[-1]
control = self._browser.getControl(name=name)
content_type, _ = mimetypes.guess_type(file_path)
- with open(file_path, 'rb') as f:
+ with open(file_path, "rb") as f:
control.add_file(f, content_type, filename)
def _find_links_by_xpath(self, xpath):
@@ -350,7 +347,7 @@ def find_by_value(self, value):
def find_by_text(self, text):
# Add a period to the xpath to search only inside the parent.
- xpath_str = '.{}'.format(_concat_xpath_from_str(text))
+ xpath_str = f".{_concat_xpath_from_str(text)}"
return self.find_by_xpath(xpath_str)
def find_by_id(self, id): # NOQA: A002
@@ -379,11 +376,11 @@ def has_class(self, class_name):
class ZopeTestBrowserLinkElement(ZopeTestBrowserElement):
def __init__(self, element, parent):
- super(ZopeTestBrowserLinkElement, self).__init__(element, parent)
+ super().__init__(element, parent)
self._browser = parent._browser
def __getitem__(self, attr):
- return super(ZopeTestBrowserLinkElement, self).__getitem__(attr)
+ return super().__getitem__(attr)
def click(self):
return self._browser.open(self["href"])
diff --git a/splinter/element_list.py b/splinter/element_list.py
index 81d0f6c6a..d267b880b 100644
--- a/splinter/element_list.py
+++ b/splinter/element_list.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from splinter.exceptions import ElementDoesNotExist
@@ -25,7 +22,13 @@ class ElementList:
>>> element_list[0] # raises ElementDoesNotExist
"""
- def __init__(self, list, driver=None, find_by=None, query=None) -> None: # NOQA: A002
+ def __init__(
+ self,
+ list,
+ driver=None,
+ find_by=None,
+ query=None,
+ ) -> None: # NOQA: A002
self._container = []
self._container.extend(list)
@@ -40,9 +43,10 @@ def __getitem__(self, index):
return self._container[index]
except IndexError:
raise ElementDoesNotExist(
- u'no elements could be found with {0} "{1}"'.format(
- self.find_by, self.query
- )
+ 'no elements could be found with {} "{}"'.format(
+ self.find_by,
+ self.query,
+ ),
)
@property
@@ -81,14 +85,14 @@ def __getattr__(self, name):
return getattr(self._container, name)
except AttributeError:
raise AttributeError(
- u"'{0}' object has no attribute '{1}'".format(
- self.__class__.__name__, name
- )
+ "'{}' object has no attribute '{}'".format(
+ self.__class__.__name__,
+ name,
+ ),
)
def __iter__(self):
- for item in self._container:
- yield item
+ yield from self._container
def __len__(self) -> int:
"""__len__ checks the internal container."""
diff --git a/splinter/exceptions.py b/splinter/exceptions.py
index 8df4b42b2..8d735aa65 100644
--- a/splinter/exceptions.py
+++ b/splinter/exceptions.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
diff --git a/splinter/meta.py b/splinter/meta.py
index 6cabb1fdf..8cf8bc4f9 100644
--- a/splinter/meta.py
+++ b/splinter/meta.py
@@ -1,12 +1,15 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
class InheritedDocs(type):
- def __new__(mcs, class_name: str, bases: tuple, dict: dict) -> type: # NOQA: N804, A002
+ def __new__(
+ mcs,
+ class_name: str,
+ bases: tuple,
+ dict: dict,
+ ) -> type: # NOQA: N804, A002
"""Metaclass that forces inheritance of docstrings."""
items_to_patch = [
(k, v) for k, v in dict.items() if not k.startswith("__") and not v.__doc__
diff --git a/splinter/request_handler/status_code.py b/splinter/request_handler/status_code.py
index ea0703dd9..992f7129f 100644
--- a/splinter/request_handler/status_code.py
+++ b/splinter/request_handler/status_code.py
@@ -1,11 +1,9 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-class StatusCode(object):
+class StatusCode:
def __init__(self, status_code: int, reason: str) -> None:
#: A message for the response (example: Success)
self.reason = reason
@@ -19,7 +17,7 @@ def __ne__(self, other) -> bool:
return not self.__eq__(other)
def __str__(self) -> str:
- return "{} - {}".format(self.code, self.reason)
+ return f"{self.code} - {self.reason}"
def is_success(self) -> bool:
"""
diff --git a/splinter/retry.py b/splinter/retry.py
index a369bb7a5..546611a44 100644
--- a/splinter/retry.py
+++ b/splinter/retry.py
@@ -1,5 +1,7 @@
import time
-from typing import Any, Callable, Optional
+from typing import Any
+from typing import Callable
+from typing import Optional
def _retry(
diff --git a/splinter/version.py b/splinter/version.py
index f873d904b..c64d1f906 100644
--- a/splinter/version.py
+++ b/splinter/version.py
@@ -1,2 +1,2 @@
__version_info__ = (0, 19, 0)
-__version__ = '.'.join(map(str, __version_info__))
+__version__ = ".".join(map(str, __version_info__))
diff --git a/tests/__init__.py b/tests/__init__.py
index 678b44853..ac33bfb9c 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
diff --git a/tests/base.py b/tests/base.py
index 6b021b5c0..17be49de7 100644
--- a/tests/base.py
+++ b/tests/base.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -29,11 +27,14 @@
supported_browsers = [
- 'chrome', 'firefox', 'chrome_fullscreen', 'firefox_fullscreen',
+ "chrome",
+ "firefox",
+ "chrome_fullscreen",
+ "firefox_fullscreen",
]
-if platform.system() == 'Windows':
- supported_browsers = ['edge']
+if platform.system() == "Windows":
+ supported_browsers = ["edge"]
class BaseBrowserTests(
@@ -60,7 +61,7 @@ def test_can_open_page(self):
def test_can_back_on_history(self):
"""should be able to back on history"""
self.browser.visit(EXAMPLE_APP)
- self.browser.visit("{}iframe".format(EXAMPLE_APP))
+ self.browser.visit(f"{EXAMPLE_APP}iframe")
self.browser.back()
self.assertEqual(EXAMPLE_APP, self.browser.url)
@@ -123,7 +124,7 @@ def test_redirection(self):
when visiting /redirected, browser should be redirected to /redirected-location?come=get&some=true
browser.url should be updated
"""
- self.browser.visit("{}redirected".format(EXAMPLE_APP))
+ self.browser.visit(f"{EXAMPLE_APP}redirected")
self.assertIn("I just been redirected to this location.", self.browser.html)
self.assertIn("redirect-location?come=get&some=true", self.browser.url)
@@ -163,7 +164,8 @@ def test_can_see_the_text_for_an_element(self):
def test_the_text_for_an_element_strips_html_tags(self):
"should show that the text attribute strips html"
self.assertEqual(
- self.browser.find_by_id("text_with_html").text, "another bit of text"
+ self.browser.find_by_id("text_with_html").text,
+ "another bit of text",
)
def test_can_verify_if_a_element_is_visible(self):
diff --git a/tests/click_elements.py b/tests/click_elements.py
index dc45c40be..7365c6e05 100644
--- a/tests/click_elements.py
+++ b/tests/click_elements.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
diff --git a/tests/conftest.py b/tests/conftest.py
index 4c76edd83..aabf9edf2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,21 +1,19 @@
-import sys
-
import os
-
+import sys
from multiprocessing import Process
-
from urllib.request import urlopen
-from tests.fake_webapp import start_flask_app, EXAMPLE_APP
-from tests.get_browser import get_browser
-
import pytest
+from tests.fake_webapp import EXAMPLE_APP
+from tests.fake_webapp import start_flask_app
+from tests.get_browser import get_browser
-class Env(object):
+
+class Env:
def __init__(self):
self.process = None
- self.host = 'localhost'
+ self.host = "localhost"
self.port = 5000
@@ -29,7 +27,7 @@ def wait_until_start():
if results.code == 404:
raise Exception("%s returned unexpected 404" % EXAMPLE_APP)
break
- except IOError:
+ except OSError:
pass
@@ -39,7 +37,7 @@ def wait_until_stop():
results = urlopen(EXAMPLE_APP)
if results.code == 404:
break
- except IOError:
+ except OSError:
break
@@ -75,4 +73,5 @@ def new_browser(browser_name):
browser = get_browser(browser_name)
request.addfinalizer(browser.quit)
return browser
+
return new_browser
diff --git a/tests/cookies.py b/tests/cookies.py
index 8faf9c493..eb5726088 100644
--- a/tests/cookies.py
+++ b/tests/cookies.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -117,6 +115,6 @@ def test_create_and_use_contains(self):
def test_cookies_extra_parameters(self):
"""Cookie can be created with extra parameters."""
timestamp = int(time.time() + 120)
- self.browser.cookies.add({'sha': 'zam'}, expiry=timestamp)
- cookie = self.browser.driver.get_cookie('sha')
+ self.browser.cookies.add({"sha": "zam"}, expiry=timestamp)
+ cookie = self.browser.driver.get_cookie("sha")
assert timestamp == cookie["expiry"]
diff --git a/tests/element.py b/tests/element.py
index d67506bb6..78be1d573 100644
--- a/tests/element.py
+++ b/tests/element.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -8,39 +6,39 @@
class ElementTest:
def test_element_has_class_when_element_has_the_class_as_first_class(self):
self.assertTrue(
- self.browser.find_by_css(".has-class-first").has_class("has-class-first")
+ self.browser.find_by_css(".has-class-first").has_class("has-class-first"),
)
def test_element_has_class_when_element_has_the_class_as_middle_class(self):
self.assertTrue(
- self.browser.find_by_css(".has-class-middle").has_class("has-class-middle")
+ self.browser.find_by_css(".has-class-middle").has_class("has-class-middle"),
)
def test_element_has_class_when_element_has_the_class_as_end_class(self):
self.assertTrue(
- self.browser.find_by_css(".has-class-end").has_class("has-class-end")
+ self.browser.find_by_css(".has-class-end").has_class("has-class-end"),
)
def test_element_has_class_when_element_doesnt_have_the_class(self):
self.assertFalse(
- self.browser.find_by_css(".has-class-first").has_class("has-class")
+ self.browser.find_by_css(".has-class-first").has_class("has-class"),
)
def test_element_outer_html(self):
self.assertEqual(
self.browser.find_by_id("html-property").outer_html,
- u''
- u'inner
inner text
html test
',
+ ''
+ 'inner
inner text
html test
',
)
def test_element_html_with_breakline(self):
self.assertEqual(
self.browser.find_by_id("html-property-with-breakline").html,
- u'\\n some text here\\n',
+ "\\n some text here\\n",
)
def test_element_html(self):
self.assertEqual(
self.browser.find_by_id("html-property").html,
- u'inner inner text
html test',
+ 'inner inner text
html test',
)
diff --git a/tests/element_does_not_exist.py b/tests/element_does_not_exist.py
index 22336aa75..9993fa3fa 100644
--- a/tests/element_does_not_exist.py
+++ b/tests/element_does_not_exist.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from splinter.exceptions import ElementDoesNotExist
@@ -22,7 +19,7 @@ def test_element_list_raises_when_element_does_not_exists(self):
def test_element_list_raises_with_unicode_query(self):
with self.assertRaises(ElementDoesNotExist):
- self.browser.find_by_css(u".element[title=título]").last
+ self.browser.find_by_css(".element[title=título]").last
def test_element_list_contains_right_information_and_raises_right_exception(self):
"element list contains right information about query and raises nice exception message"
@@ -40,12 +37,12 @@ def test_element_list_contains_right_information_and_raises_right_exception(self
self.assertEqual(expected_message, e.args[0])
def test_element_list_raises_when_element_first_doesnt_exists_in_element_context(
- self
+ self,
):
"element list raises exception with right information in element context"
with self.assertRaises(ElementDoesNotExist) as cm:
element_list = self.browser.find_by_css("#inside").find_by_css(
- ".inner-element-that-dont-exists"
+ ".inner-element-that-dont-exists",
)
self.assertEqual("css", element_list.find_by)
self.assertEqual(".inner-element-that-dont-exists", element_list.query)
diff --git a/tests/fake_django/settings.py b/tests/fake_django/settings.py
index aa6b1e72c..c382f089d 100644
--- a/tests/fake_django/settings.py
+++ b/tests/fake_django/settings.py
@@ -7,7 +7,6 @@
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
@@ -60,7 +59,7 @@
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
- }
+ },
}
# Internationalization
diff --git a/tests/fake_django/urls.py b/tests/fake_django/urls.py
index 7c43f9a71..bf83ba8e0 100644
--- a/tests/fake_django/urls.py
+++ b/tests/fake_django/urls.py
@@ -1,18 +1,17 @@
-from django.http import HttpResponse
-from django.shortcuts import redirect
from django.contrib import admin
from django.contrib.auth.decorators import login_required
-from django.urls import re_path, reverse
+from django.http import HttpResponse
+from django.shortcuts import redirect
+from django.urls import re_path
+from django.urls import reverse
-from tests.fake_webapp import (
- EXAMPLE_HTML,
- EXAMPLE_IFRAME_HTML,
- EXAMPLE_ALERT_HTML,
- EXAMPLE_TYPE_HTML,
- EXAMPLE_NO_BODY_HTML,
- EXAMPLE_POPUP_HTML,
- EXAMPLE_REDIRECT_LOCATION_HTML,
-)
+from tests.fake_webapp import EXAMPLE_ALERT_HTML
+from tests.fake_webapp import EXAMPLE_HTML
+from tests.fake_webapp import EXAMPLE_IFRAME_HTML
+from tests.fake_webapp import EXAMPLE_NO_BODY_HTML
+from tests.fake_webapp import EXAMPLE_POPUP_HTML
+from tests.fake_webapp import EXAMPLE_REDIRECT_LOCATION_HTML
+from tests.fake_webapp import EXAMPLE_TYPE_HTML
admin.autodiscover()
@@ -48,14 +47,12 @@ def get_user_agent(request):
def post_form(request):
items = "\n".join("{}: {}".format(*item) for item in request.POST.items())
- body = "{}".format(items)
+ body = f"{items}"
return HttpResponse(body)
def request_headers(request):
- body = "\n".join(
- "%s: %s" % (key, value) for key, value in request.META.items()
- )
+ body = "\n".join(f"{key}: {value}" for key, value in request.META.items())
return HttpResponse(body)
@@ -63,8 +60,8 @@ def upload_file(request):
if request.method == "POST":
f = request.FILES["file"]
buffer = [
- "Content-type: {}".format(f.content_type),
- "File content: {}".format(f.read()),
+ f"Content-type: {f.content_type}",
+ f"File content: {f.read()}",
]
return HttpResponse("|".join(buffer))
diff --git a/tests/fake_webapp.py b/tests/fake_webapp.py
index 27e80d3b2..0f9c50453 100644
--- a/tests/fake_webapp.py
+++ b/tests/fake_webapp.py
@@ -1,14 +1,15 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from functools import wraps
-from io import open
from os import path
-from flask import Flask, request, abort, Response, redirect, url_for
+from flask import abort
+from flask import Flask
+from flask import redirect
+from flask import request
+from flask import Response
+from flask import url_for
this_folder = path.abspath(path.dirname(__file__))
@@ -16,7 +17,7 @@
def read_static(static_name):
file_path = path.join(this_folder, "static", static_name)
- return open(file_path, encoding='utf8').read()
+ return open(file_path, encoding="utf8").read()
EXAMPLE_APP = "http://127.0.0.1:5000/"
@@ -104,16 +105,16 @@ def get_user_agent():
@app.route("/post", methods=["POST"])
def post_form():
items = "\n".join("{}: {}".format(*item) for item in request.form.items())
- return "{}".format(items)
+ return f"{items}"
@app.route("/upload", methods=["GET", "POST"])
def upload_file():
if request.method == "POST":
f = request.files["file"]
- BUFFER.append("Content-type: {}".format(f.content_type))
- BUFFER.append("File content: {}".format(f.stream.read()))
- return redirect(url_for('upload_file'))
+ BUFFER.append(f"Content-type: {f.content_type}")
+ BUFFER.append(f"File content: {f.stream.read()}")
+ return redirect(url_for("upload_file"))
return "|".join(BUFFER)
diff --git a/tests/find_elements.py b/tests/find_elements.py
index f498fbd66..9b79dc2bb 100644
--- a/tests/find_elements.py
+++ b/tests/find_elements.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from splinter.driver import ElementAPI
from splinter.element_list import ElementList
@@ -36,8 +33,8 @@ def test_finding_by_text(self):
self.assertEqual(element.value, "Complex")
def test_finding_by_text_with_quotation_marks(self):
- element = self.browser.find_by_text("Quotation \" marks")
- self.assertEqual(element.value, "Quotation \" marks")
+ element = self.browser.find_by_text('Quotation " marks')
+ self.assertEqual(element.value, 'Quotation " marks')
def test_finding_by_id(self):
value = self.browser.find_by_id("firstheader").value
@@ -91,19 +88,19 @@ def test_find_links_by_partial_text_nested_elements(self):
expected = "http://localhost:5000/nested"
link = self.browser.links.find_by_partial_text("Nested text")[0]
- assert expected == link['href']
+ assert expected == link["href"]
link = self.browser.links.find_by_partial_text("in a link")[0]
- assert expected == link['href']
+ assert expected == link["href"]
link = self.browser.links.find_by_partial_text("Nested text in")[0]
- assert expected == link['href']
+ assert expected == link["href"]
link = self.browser.links.find_by_partial_text("text in a link")[0]
- assert expected == link['href']
+ assert expected == link["href"]
link = self.browser.links.find_by_partial_text("Nested text in a link")[0]
- assert expected == link['href']
+ assert expected == link["href"]
def test_finding_last_element_by_css(self):
value = self.browser.find_by_css("h1").last.value
diff --git a/tests/form_elements.py b/tests/form_elements.py
index 558516ef7..6df3630bb 100644
--- a/tests/form_elements.py
+++ b/tests/form_elements.py
@@ -1,11 +1,8 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-import time
import re
+import time
import unittest
import pytest
@@ -15,19 +12,21 @@
def skip_if_zope(f):
def wrapper(self, *args, **kwargs):
- if self.__class__.__name__ == 'ZopeTestBrowserDriverTest':
+ if self.__class__.__name__ == "ZopeTestBrowserDriverTest":
return unittest.skip("skipping this test for zope testbrowser")
else:
f(self, *args, **kwargs)
+
return wrapper
def skip_if_django(f):
def wrapper(self, *args, **kwargs):
- if self.__class__.__name__ == 'DjangoClientDriverTest':
+ if self.__class__.__name__ == "DjangoClientDriverTest":
return unittest.skip("skipping this test for django")
else:
f(self, *args, **kwargs)
+
return wrapper
@@ -47,7 +46,8 @@ def test_fill_element(self):
def test_clicking_submit_input_doesnt_post_input_value_if_name_not_present(self):
self.browser.find_by_css("input.submit-input-no-name").click()
self.assertEqual(
- self.browser.find_by_xpath("/descendant-or-self::*").text.strip(), ""
+ self.browser.find_by_xpath("/descendant-or-self::*").text.strip(),
+ "",
)
@skip_if_zope
@@ -63,7 +63,8 @@ def test_clicking_submit_input_posts_empty_value_if_value_not_present(self):
def test_clicking_submit_input_doesnt_post_input_value_if_empty(self):
self.browser.find_by_css("input.submit-input-empty").click()
self.assertEqual(
- self.browser.find_by_xpath("/descendant-or-self::*").text.strip(), ""
+ self.browser.find_by_xpath("/descendant-or-self::*").text.strip(),
+ "",
)
def test_clicking_submit_input_posts_input_value_if_value_present(self):
@@ -90,7 +91,8 @@ def test_clicking_submit_button_posts_empty_value_if_value_not_present(self):
def test_clicking_submit_button_doesnt_post_button_value_if_empty(self):
self.browser.find_by_css("button.submit-button-empty").click()
self.assertEqual(
- self.browser.find_by_xpath("/descendant-or-self::*").text.strip(), ""
+ self.browser.find_by_xpath("/descendant-or-self::*").text.strip(),
+ "",
)
@skip_if_zope
@@ -212,7 +214,7 @@ def test_can_fill_more_than_one_field_in_form(self):
"uf": "rj",
"some-check": True,
"checked-checkbox": False,
- }
+ },
)
query_value = self.browser.find_by_name("query").value
self.assertEqual("another new query", query_value)
@@ -240,7 +242,8 @@ def test_can_fill_unknown_text_field(self):
def test_can_fill_form_by_id(self):
"should be able to fill a form by its id"
self.browser.fill_form(
- {"firstname": "John", "lastname": "Doe"}, form_id="login"
+ {"firstname": "John", "lastname": "Doe"},
+ form_id="login",
)
value = self.browser.find_by_name("firstname").value
self.assertEqual("John", value)
@@ -252,7 +255,7 @@ def test_fill_form_missing_values(self):
{"query": "new query", "missing_form": "doesn't exist"},
)
- assert 'missing_form' in str(e.value)
+ assert "missing_form" in str(e.value)
def test_fill_form_missing_values_ignore_missing(self):
"""Missing values are ignores when ignore_missing is True."""
diff --git a/tests/get_browser.py b/tests/get_browser.py
index 812b0237b..6d510c734 100644
--- a/tests/get_browser.py
+++ b/tests/get_browser.py
@@ -17,33 +17,24 @@ def get_browser(browser_name, config=None, **kwargs):
config = config or Config()
config.headless = True
- if browser_name in ['chrome', 'chrome_fullscreen']:
- if browser_name == 'chrome_fullscreen':
+ if browser_name in ["chrome", "chrome_fullscreen"]:
+ if browser_name == "chrome_fullscreen":
config.fullscreen = True
options = webdriver.chrome.options.Options()
options.add_argument("--disable-dev-shm-usage")
- return Browser(
- "chrome",
- options=options,
- config=config,
- **kwargs
- )
+ return Browser("chrome", options=options, config=config, **kwargs)
- elif browser_name in ['firefox', 'firefox_fullscreen']:
- if browser_name == 'firefox_fullscreen':
+ elif browser_name in ["firefox", "firefox_fullscreen"]:
+ if browser_name == "firefox_fullscreen":
config.fullscreen = True
- return Browser(
- "firefox",
- config=config,
- **kwargs
- )
+ return Browser("firefox", config=config, **kwargs)
- elif browser_name == 'remote':
+ elif browser_name == "remote":
return Browser("remote")
- elif browser_name == 'django':
+ elif browser_name == "django":
components = parse.urlparse(EXAMPLE_APP)
return Browser(
"django",
@@ -52,21 +43,22 @@ def get_browser(browser_name, config=None, **kwargs):
client_SERVER_PORT=components.port,
)
- elif browser_name == 'flask':
+ elif browser_name == "flask":
return Browser("flask", app=app, wait_time=0.1)
- elif browser_name == 'zope.testbrowser':
+ elif browser_name == "zope.testbrowser":
return Browser("zope.testbrowser", wait_time=0.1)
- elif browser_name == 'edge':
+ elif browser_name == "edge":
# Github Actions Windows EdgeDriver path
service = None
- driver_path = os.getenv('EDGEWEBDRIVER')
+ driver_path = os.getenv("EDGEWEBDRIVER")
if driver_path:
from selenium.webdriver.edge.service import Service as EdgeService
- edgedriver_path = os.path.join(driver_path, 'msedgedriver.exe')
+
+ edgedriver_path = os.path.join(driver_path, "msedgedriver.exe")
service = EdgeService(executable_path=edgedriver_path)
- return Browser('edge', service=service, config=config, **kwargs)
+ return Browser("edge", service=service, config=config, **kwargs)
- raise ValueError('Unknown browser name')
+ raise ValueError("Unknown browser name")
diff --git a/tests/is_element_present.py b/tests/is_element_present.py
index 73f3aa381..2ff897f66 100644
--- a/tests/is_element_present.py
+++ b/tests/is_element_present.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2015 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
@@ -15,7 +13,7 @@ def test_is_element_present_by_css_using_a_custom_wait_time(self):
"should is element present by css verify if element is present using a custom wait time"
self.browser.find_by_css(".add-async-element").click()
self.assertTrue(
- self.browser.is_element_present_by_css(".async-element2", wait_time=3)
+ self.browser.is_element_present_by_css(".async-element2", wait_time=3),
)
def test_is_element_present_by_css_returns_false_if_element_is_not_present(self):
@@ -33,7 +31,7 @@ def test_is_element_not_present_by_css_returns_false_if_element_is_present(self)
def test_is_element_not_present_by_css_using_a_custom_wait_time(self):
"should is element not present by css verify if element is not present using a custom wait time"
self.assertTrue(
- self.browser.is_element_not_present_by_css(".async-element", wait_time=3)
+ self.browser.is_element_not_present_by_css(".async-element", wait_time=3),
)
def test_is_element_present_by_xpath(self):
@@ -59,7 +57,7 @@ def test_is_element_not_present_by_xpath_returns_false_if_element_is_present(sel
def test_is_element_not_present_by_xpath_using_a_custom_wait_time(self):
"should is element not present by xpath verify if element is not present using a custom wait time"
self.assertTrue(
- self.browser.is_element_not_present_by_xpath("//h4", wait_time=3)
+ self.browser.is_element_not_present_by_xpath("//h4", wait_time=3),
)
def test_is_element_present_by_tag(self):
@@ -115,7 +113,7 @@ def test_is_element_present_by_value_using_a_custom_wait_time(self):
"should is element present by value verify if element is present using a custom wait time"
self.browser.find_by_css(".add-async-element").click()
self.assertTrue(
- self.browser.is_element_present_by_value("async-header-value", wait_time=3)
+ self.browser.is_element_present_by_value("async-header-value", wait_time=3),
)
def test_is_element_present_by_value_returns_false_if_element_is_not_present(self):
@@ -125,15 +123,16 @@ def test_is_element_present_by_value_returns_false_if_element_is_not_present(sel
def test_is_element_not_present_by_value(self):
"should is element not present by value verify if element is not present"
self.assertTrue(
- self.browser.is_element_not_present_by_value("async-header-value")
+ self.browser.is_element_not_present_by_value("async-header-value"),
)
def test_is_element_not_present_by_value_using_a_custom_wait_time(self):
"should is element not present by value verify if element is not present using a custom wait time"
self.assertTrue(
self.browser.is_element_not_present_by_value(
- "async-header-value", wait_time=3
- )
+ "async-header-value",
+ wait_time=3,
+ ),
)
def test_is_element_not_present_by_value_returns_false_if_element_is_present(self):
@@ -150,7 +149,7 @@ def test_is_element_present_by_id_using_a_custom_wait_time(self):
"should is element present by id verify if element is present using a custom wait time"
self.browser.find_by_css(".add-async-element").click()
self.assertTrue(
- self.browser.is_element_present_by_id("async-header", wait_time=3)
+ self.browser.is_element_present_by_id("async-header", wait_time=3),
)
def test_is_element_present_by_id_returns_false_if_element_is_not_present(self):
@@ -164,7 +163,7 @@ def test_is_element_not_present_by_id(self):
def test_is_element_not_present_by_id_using_a_custom_wait_time(self):
"should is element not present by id verify if element is not present using a custom wait time"
self.assertTrue(
- self.browser.is_element_not_present_by_id("async-header", wait_time=3)
+ self.browser.is_element_not_present_by_id("async-header", wait_time=3),
)
def test_is_element_not_present_by_id_returns_false_if_element_is_present(self):
@@ -182,7 +181,7 @@ def test_is_element_present_by_name_using_a_custom_wait_time(self):
"should is element present by name verify if element is present using a custom wait time"
self.browser.find_by_css(".add-async-element").click()
self.assertTrue(
- self.browser.is_element_present_by_name("async-input", wait_time=3)
+ self.browser.is_element_present_by_name("async-input", wait_time=3),
)
def test_is_element_present_by_name_returns_false_if_element_is_not_present(self):
@@ -196,7 +195,7 @@ def test_is_element_not_present_by_name(self):
def test_is_element_not_present_by_name_using_a_custom_wait_time(self):
"should is element not present by name verify if element is not present using a custom wait time"
self.assertTrue(
- self.browser.is_element_not_present_by_name("async-input", wait_time=3)
+ self.browser.is_element_not_present_by_name("async-input", wait_time=3),
)
def test_is_element_not_present_by_name_returns_false_if_element_is_present(self):
diff --git a/tests/is_text_present.py b/tests/is_text_present.py
index 5ad531822..c12de3e11 100644
--- a/tests/is_text_present.py
+++ b/tests/is_text_present.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
diff --git a/tests/mockfile.txt b/tests/mockfile.txt
index 1e8ff1f26..d1c396d9a 100644
--- a/tests/mockfile.txt
+++ b/tests/mockfile.txt
@@ -1 +1 @@
-splinter mock file
\ No newline at end of file
+splinter mock file
diff --git a/tests/static/jquery-ui-1.8.16.custom.min.js b/tests/static/jquery-ui-1.8.16.custom.min.js
index 4f90fd366..ff656be54 100755
--- a/tests/static/jquery-ui-1.8.16.custom.min.js
+++ b/tests/static/jquery-ui-1.8.16.custom.min.js
@@ -125,4 +125,4 @@ i&&e<=k||g>=i&&g<=k||ek);default:return false}};d.ui.ddmanager={current:nu
a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},dragStart:function(a,b){a.element.parents(":not(body,html)").bind("scroll.droppable",function(){a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,b)})},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);
if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e=d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})},dragStop:function(a,b){a.element.parents(":not(body,html)").unbind("scroll.droppable");
a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,b)}}})(jQuery);
-;
\ No newline at end of file
+;
diff --git a/tests/static/type.html b/tests/static/type.html
index d13464ba2..2a62f7946 100644
--- a/tests/static/type.html
+++ b/tests/static/type.html
@@ -14,7 +14,7 @@
};
name_input.onkeyup = showSuggest;
textarea_input.onkeyup = showSuggest;
-
+
};
diff --git a/tests/status_code.py b/tests/status_code.py
index ad6150562..3acc9545a 100644
--- a/tests/status_code.py
+++ b/tests/status_code.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from .fake_webapp import EXAMPLE_APP
@@ -14,6 +11,6 @@ def test_should_visit_index_of_example_app_and_get_200_status_code(self):
self.assertEqual("200 - OK", str(self.browser.status_code))
def test_should_visit_error_of_example_app_and_not_get_200_status_code(self):
- self.browser.visit(EXAMPLE_APP + 'error.html')
+ self.browser.visit(EXAMPLE_APP + "error.html")
self.assertNotEqual(200, self.browser.status_code)
- self.assertEqual('404 - Not Found', str(self.browser.status_code))
+ self.assertEqual("404 - Not Found", str(self.browser.status_code))
diff --git a/tests/test_async_finder.py b/tests/test_async_finder.py
index 5ad422eca..215584a46 100644
--- a/tests/test_async_finder.py
+++ b/tests/test_async_finder.py
@@ -1,16 +1,13 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
+import pytest
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_css_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -21,7 +18,7 @@ def test_find_by_css_should_found_an_async_element(get_new_browser, browser_name
assert 1 == len(elements)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_xpath_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -32,7 +29,7 @@ def test_find_by_xpath_should_found_an_async_element(get_new_browser, browser_na
assert 1 == len(elements)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_tag_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -43,7 +40,7 @@ def test_find_by_tag_should_found_an_async_element(get_new_browser, browser_name
assert 1 == len(elements)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_id_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -54,7 +51,7 @@ def test_find_by_id_should_found_an_async_element(get_new_browser, browser_name)
assert 1 == len(elements)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_name_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -65,7 +62,7 @@ def test_find_by_name_should_found_an_async_element(get_new_browser, browser_nam
assert 1 == len(elements)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_find_by_value_should_found_an_async_element(get_new_browser, browser_name):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
diff --git a/tests/test_browser.py b/tests/test_browser.py
index 53ddd6b25..0da66e514 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -1,17 +1,13 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-
import builtins
from importlib import reload
-from splinter.exceptions import DriverNotFoundError
-
import pytest
+from splinter.exceptions import DriverNotFoundError
+
def patch_driver(pattern):
old_import = builtins.__import__
@@ -40,7 +36,7 @@ def test_browser_should_work_even_without_zope_testbrowser():
from splinter import browser
reload(browser)
- assert None is browser._DRIVERS['zope.testbrowser']
+ assert None is browser._DRIVERS["zope.testbrowser"]
unpatch_driver(browser, old_import)
@@ -56,7 +52,7 @@ def test_browser_message_on_missing_driver():
Browser("zope.testbrowser")
- assert 'Driver for zope.testbrowser was not found.' == str(e.value)
+ assert "Driver for zope.testbrowser was not found." == str(e.value)
unpatch_driver(browser, old_import)
@@ -72,12 +68,14 @@ def test_browser_driver_retry_count():
"""Checks that the retry count is being used"""
from splinter.browser import _DRIVERS
from splinter import Browser
+
global test_retry_count
def test_driver(*args, **kwargs):
global test_retry_count
test_retry_count += 1
- raise IOError("test_retry_count: " + str(test_retry_count))
+ raise OSError("test_retry_count: " + str(test_retry_count))
+
_DRIVERS["test_driver"] = test_driver
test_retry_count = 0
@@ -97,6 +95,7 @@ def test_driver(*args, **kwargs):
def test_browser_log_missing_drivers(caplog):
"""Missing drivers are logged at the debug level."""
import logging
+
caplog.set_level(logging.DEBUG)
old_import = patch_driver("flask")
from splinter import browser
@@ -107,5 +106,5 @@ def test_browser_log_missing_drivers(caplog):
assert 7 == len(caplog.records)
for i in range(0, 6):
record = caplog.records[i]
- assert record.levelname == 'DEBUG'
- assert 'Import Warning' in record.message
+ assert record.levelname == "DEBUG"
+ assert "Import Warning" in record.message
diff --git a/tests/test_djangoclient.py b/tests/test_djangoclient.py
index bf79a9fa9..ad89c69c9 100644
--- a/tests/test_djangoclient.py
+++ b/tests/test_djangoclient.py
@@ -1,20 +1,18 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2015 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
import sys
import time
import unittest
+import django
import pytest
-import django
-from splinter import Browser
-from .base import BaseBrowserTests, get_browser
+from .base import BaseBrowserTests
+from .base import get_browser
from .fake_webapp import EXAMPLE_APP
+from splinter import Browser
sys.path.append("tests/fake_django")
@@ -24,12 +22,10 @@
django.setup()
-class DjangoClientDriverTest(
- BaseBrowserTests, unittest.TestCase
-):
- @pytest.fixture(autouse=True, scope='class')
+class DjangoClientDriverTest(BaseBrowserTests, unittest.TestCase):
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('django')
+ request.cls.browser = get_browser("django")
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
@@ -43,7 +39,8 @@ def test_should_support_with_statement(self):
def test_attach_file(self):
"should provide a way to change file field value"
file_path = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), "mockfile.txt"
+ os.path.abspath(os.path.dirname(__file__)),
+ "mockfile.txt",
)
self.browser.attach_file("file", file_path)
self.browser.find_by_name("upload").click()
@@ -139,10 +136,10 @@ def test_links_with_nested_tags_xpath(self):
def test_finding_all_links_by_non_ascii_text(self):
"should find links by non ascii text"
non_ascii_encodings = {
- "pangram_pl": u"Jeżu klątw, spłódź Finom część gry hańb!",
- "pangram_ja": u"天 地 星 空",
- "pangram_ru": u"В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
- "pangram_eo": u"Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
+ "pangram_pl": "Jeżu klątw, spłódź Finom część gry hańb!",
+ "pangram_ja": "天 地 星 空",
+ "pangram_ru": "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
+ "pangram_eo": "Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
}
for key, text in non_ascii_encodings.items():
link = self.browser.links.find_by_text(text)
@@ -151,9 +148,9 @@ def test_finding_all_links_by_non_ascii_text(self):
def test_cookies_extra_parameters(self):
"""Cookie can be created with extra parameters."""
timestamp = int(time.time() + 120)
- self.browser.cookies.add({'sha': 'zam'}, expires=timestamp)
- cookie = self.browser._browser.cookies['sha']
- assert timestamp == cookie['expires']
+ self.browser.cookies.add({"sha": "zam"}, expires=timestamp)
+ cookie = self.browser._browser.cookies["sha"]
+ assert timestamp == cookie["expires"]
class DjangoClientDriverTestWithCustomHeaders(unittest.TestCase):
@@ -168,7 +165,7 @@ def setUpClass(cls):
def test_create_a_phantomjs_with_custom_headers(self):
self.browser.visit(EXAMPLE_APP + "headers")
self.assertTrue(
- self.browser.is_text_present("X-Splinter-Customheaders-1: Hello")
+ self.browser.is_text_present("X-Splinter-Customheaders-1: Hello"),
)
self.assertTrue(self.browser.is_text_present("X-Splinter-Customheaders-2: Bye"))
diff --git a/tests/test_element_is_visible.py b/tests/test_element_is_visible.py
index 156f704c6..1f82dbdd1 100644
--- a/tests/test_element_is_visible.py
+++ b/tests/test_element_is_visible.py
@@ -1,13 +1,13 @@
# Copyright 2022 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
+import pytest
+
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_visible(browser_name, get_new_browser):
"""WebDriverElement.is_visible() should verify if element is visible."""
browser = get_new_browser(browser_name)
@@ -17,7 +17,7 @@ def test_element_is_visible(browser_name, get_new_browser):
assert browser.find_by_css("#invisible").is_visible()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_visible_custom_wait_time(browser_name, get_new_browser):
"""WebDriverElement.is_visible()'s wait_time argument should be respected."""
browser = get_new_browser(browser_name)
@@ -27,7 +27,7 @@ def test_element_is_visible_custom_wait_time(browser_name, get_new_browser):
assert browser.find_by_css("#invisible").is_visible(wait_time=3)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_visible_return_false(browser_name, get_new_browser):
"""WebDriverElement.is_visible() should return False if element is not visible."""
browser = get_new_browser(browser_name)
@@ -36,7 +36,7 @@ def test_element_is_visible_return_false(browser_name, get_new_browser):
assert not browser.find_by_css("#invisible").is_visible()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_not_visible(browser_name, get_new_browser):
"""WebDriverElement.is_not_visible() should verify if element is not visible."""
browser = get_new_browser(browser_name)
@@ -45,7 +45,7 @@ def test_element_is_not_visible(browser_name, get_new_browser):
assert browser.find_by_css("#invisible").is_not_visible()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_not_visible_return_false(browser_name, get_new_browser):
"""WebDriverElement.is_not_visible() should return False if element is visible."""
browser = get_new_browser(browser_name)
@@ -55,7 +55,7 @@ def test_element_is_not_visible_return_false(browser_name, get_new_browser):
assert not browser.find_by_css("#invisible").is_not_visible()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_is_not_visible_custom_wait_time(browser_name, get_new_browser):
"""WebDriverElement.is_not_visible()'s wait_time argument should be respected."""
browser = get_new_browser(browser_name)
diff --git a/tests/test_element_list.py b/tests/test_element_list.py
index 1247f6b98..4a6f2dad9 100644
--- a/tests/test_element_list.py
+++ b/tests/test_element_list.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import pytest
from splinter.element_list import ElementList
@@ -64,7 +61,7 @@ def test_raise_exception_on_indexerror():
def test_raise_exception_on_indexerror_with_unicode_query():
"should raise ElementDoesNotExist exception on IndexError"
with pytest.raises(ElementDoesNotExist):
- ElementList([], query=u".element[title=título]").first
+ ElementList([], query=".element[title=título]").first
def test_raise_attribute_error():
@@ -111,8 +108,7 @@ def test_not_found_exception_with_query_and_method():
def test_elementlist_repr():
- """repr() of ElementList is identical to repr() of the internal container.
- """
+ """repr() of ElementList is identical to repr() of the internal container."""
the_list = [Person(), Person()]
elementlist = ElementList(the_list)
diff --git a/tests/test_flaskclient.py b/tests/test_flaskclient.py
index 07794b638..49ee5c04b 100644
--- a/tests/test_flaskclient.py
+++ b/tests/test_flaskclient.py
@@ -1,21 +1,17 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
import time
import unittest
-from splinter import Browser
from .base import BaseBrowserTests
-from .fake_webapp import app, EXAMPLE_APP
+from .fake_webapp import app
+from .fake_webapp import EXAMPLE_APP
+from splinter import Browser
-class FlaskClientDriverTest(
- BaseBrowserTests, unittest.TestCase
-):
+class FlaskClientDriverTest(BaseBrowserTests, unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.browser = Browser("flask", app=app, wait_time=0.1)
@@ -34,7 +30,8 @@ def test_should_support_with_statement(self):
def test_attach_file(self):
"should provide a way to change file field value"
file_path = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), "mockfile.txt"
+ os.path.abspath(os.path.dirname(__file__)),
+ "mockfile.txt",
)
self.browser.attach_file("file", file_path)
self.browser.find_by_name("upload").click()
@@ -152,10 +149,10 @@ def test_links_with_nested_tags_xpath(self):
def test_finding_all_links_by_non_ascii_text(self):
"should find links by non ascii text"
non_ascii_encodings = {
- "pangram_pl": u"Jeżu klątw, spłódź Finom część gry hańb!",
- "pangram_ja": u"天 地 星 空",
- "pangram_ru": u"В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
- "pangram_eo": u"Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
+ "pangram_pl": "Jeżu klątw, spłódź Finom część gry hańb!",
+ "pangram_ja": "天 地 星 空",
+ "pangram_ru": "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
+ "pangram_eo": "Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
}
for key, text in non_ascii_encodings.items():
link = self.browser.links.find_by_text(text)
@@ -173,8 +170,8 @@ def test_redirection_on_post(self):
def test_cookies_extra_parameters(self):
"""Cookie can be created with extra parameters."""
timestamp = int(time.time() + 120)
- self.browser.cookies.add({'sha': 'zam'}, expires=timestamp)
- cookie = {c.name: c for c in self.browser._browser.cookie_jar}['sha']
+ self.browser.cookies.add({"sha": "zam"}, expires=timestamp)
+ cookie = {c.name: c for c in self.browser._browser.cookie_jar}["sha"]
assert timestamp == cookie.expires
@@ -190,7 +187,7 @@ def setUpClass(cls):
def test_create_a_flask_client_with_custom_headers(self):
self.browser.visit(EXAMPLE_APP + "headers")
self.assertTrue(
- self.browser.is_text_present("X-Splinter-Customheaders-1: Hello")
+ self.browser.is_text_present("X-Splinter-Customheaders-1: Hello"),
)
self.assertTrue(self.browser.is_text_present("X-Splinter-Customheaders-2: Bye"))
diff --git a/tests/test_html_snapshot.py b/tests/test_html_snapshot.py
index f3f60ab81..9fef5ef55 100644
--- a/tests/test_html_snapshot.py
+++ b/tests/test_html_snapshot.py
@@ -1,26 +1,26 @@
import os
import tempfile
+import pytest
+
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_snapshot_no_unique_file(get_new_browser, browser_name):
"""When the unique_file parameter is false,
Then the filename should match the name parameter exactly.
"""
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
- browser.html_snapshot(name='test_html_snap', unique_file=False)
+ browser.html_snapshot(name="test_html_snap", unique_file=False)
- expected_filepath = os.path.abspath('test_html_snap.html')
+ expected_filepath = os.path.abspath("test_html_snap.html")
assert os.path.isfile(expected_filepath)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_html_snapshot(get_new_browser, browser_name):
"""Should take an html snapshot of the current page."""
browser = get_new_browser(browser_name)
@@ -30,7 +30,7 @@ def test_html_snapshot(get_new_browser, browser_name):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_html_snapshot_with_prefix(get_new_browser, browser_name):
"""Should add the prefix to the snapshot filename"""
browser = get_new_browser(browser_name)
@@ -40,7 +40,7 @@ def test_html_snapshot_with_prefix(get_new_browser, browser_name):
assert "foobar" in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_html_snapshot_with_suffix(get_new_browser, browser_name):
"""Should add the suffix to the snapshot filename"""
browser = get_new_browser(browser_name)
diff --git a/tests/test_iframes.py b/tests/test_iframes.py
index e421a08fd..c4aabd470 100644
--- a/tests/test_iframes.py
+++ b/tests/test_iframes.py
@@ -1,16 +1,13 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
+import pytest
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_can_work_on_iframes_by_name(get_new_browser, browser_name):
"""can work on iframes and switch back to the page"""
browser = get_new_browser(browser_name)
@@ -24,7 +21,7 @@ def test_can_work_on_iframes_by_name(get_new_browser, browser_name):
assert "Example Header" == value
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_can_work_on_iframes_by_id(get_new_browser, browser_name):
"""can work on iframes and switch back to the page"""
browser = get_new_browser(browser_name)
@@ -38,13 +35,13 @@ def test_can_work_on_iframes_by_id(get_new_browser, browser_name):
assert "Example Header" == value
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_can_work_on_iframes_by_webelement(get_new_browser, browser_name):
"""can work on iframes and switch back to the page"""
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
- elem = browser.find_by_id('iframemodal').first
+ elem = browser.find_by_id("iframemodal").first
with browser.get_iframe(elem) as frame:
value = frame.find_by_tag("h1").value
@@ -54,7 +51,7 @@ def test_can_work_on_iframes_by_webelement(get_new_browser, browser_name):
assert "Example Header" == value
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_can_work_on_iframes_by_index(get_new_browser, browser_name):
"""can work on iframes and switch back to the page"""
browser = get_new_browser(browser_name)
diff --git a/tests/test_is_element_present_nojs.py b/tests/test_is_element_present_nojs.py
index 2072bf81e..824954281 100644
--- a/tests/test_is_element_present_nojs.py
+++ b/tests/test_is_element_present_nojs.py
@@ -1,21 +1,19 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2015 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
+import pytest
from .fake_webapp import EXAMPLE_APP
-import pytest
-
supported_browsers = [
- 'django', 'flask', 'zope.testbrowser',
+ "django",
+ "flask",
+ "zope.testbrowser",
]
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_css(get_new_browser, browser_name):
"should is element present by css verify if element is present"
browser = get_new_browser(browser_name)
@@ -24,8 +22,11 @@ def test_is_element_present_by_css(get_new_browser, browser_name):
assert browser.is_element_present_by_css("h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_css_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_css_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by css returns False if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -33,7 +34,7 @@ def test_is_element_present_by_css_returns_false_if_element_is_not_present(get_n
assert not browser.is_element_present_by_css(".async-elementzz")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_css(get_new_browser, browser_name):
"should is element not present by css verify if element is not present"
browser = get_new_browser(browser_name)
@@ -42,8 +43,11 @@ def test_is_element_not_present_by_css(get_new_browser, browser_name):
assert browser.is_element_not_present_by_css(".async-element")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_css_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_css_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by css returns False if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -51,7 +55,7 @@ def test_is_element_not_present_by_css_returns_false_if_element_is_present(get_n
assert not browser.is_element_not_present_by_css("h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_xpath(get_new_browser, browser_name):
"should is element present by xpath verify if element is present"
browser = get_new_browser(browser_name)
@@ -60,8 +64,11 @@ def test_is_element_present_by_xpath(get_new_browser, browser_name):
assert browser.is_element_present_by_xpath("//h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_xpath_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_xpath_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by xpath returns false if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -69,8 +76,11 @@ def test_is_element_present_by_xpath_returns_false_if_element_is_not_present(get
assert browser.is_element_not_present_by_xpath("//h4")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_xpath_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_xpath_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by xpath returns false if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -78,7 +88,7 @@ def test_is_element_not_present_by_xpath_returns_false_if_element_is_present(get
assert not browser.is_element_not_present_by_xpath("//h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_tag(get_new_browser, browser_name):
"should is element present by tag verify if element is present"
browser = get_new_browser(browser_name)
@@ -87,8 +97,11 @@ def test_is_element_present_by_tag(get_new_browser, browser_name):
assert browser.is_element_present_by_tag("h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_tag_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_tag_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by tag returns false if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -96,7 +109,7 @@ def test_is_element_present_by_tag_returns_false_if_element_is_not_present(get_n
assert not browser.is_element_present_by_tag("h4")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_tag(get_new_browser, browser_name):
"should is element not present by tag verify if element is not present"
browser = get_new_browser(browser_name)
@@ -105,8 +118,11 @@ def test_is_element_not_present_by_tag(get_new_browser, browser_name):
assert browser.is_element_not_present_by_tag("h4")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_tag_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_tag_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by tag returns false if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -114,7 +130,7 @@ def test_is_element_not_present_by_tag_returns_false_if_element_is_present(get_n
assert not browser.is_element_not_present_by_tag("h1")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_text(get_new_browser, browser_name):
"should is element present by text verify if element is present"
browser = get_new_browser(browser_name)
@@ -123,8 +139,11 @@ def test_is_element_present_by_text(get_new_browser, browser_name):
assert browser.is_element_present_by_text("Complex")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_text_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_text_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by text verify if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -132,7 +151,7 @@ def test_is_element_present_by_text_returns_false_if_element_is_not_present(get_
assert not browser.is_element_present_by_text("Not present")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_text(get_new_browser, browser_name):
"should is element not present by text verify if element is not present"
browser = get_new_browser(browser_name)
@@ -141,8 +160,11 @@ def test_is_element_not_present_by_text(get_new_browser, browser_name):
assert browser.is_element_not_present_by_text("Not present")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_text_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_text_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by text returns False if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -150,7 +172,7 @@ def test_is_element_not_present_by_text_returns_false_if_element_is_present(get_
assert not browser.is_element_not_present_by_text("Complex")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_value(get_new_browser, browser_name):
"should is element present by value verify if element is present"
browser = get_new_browser(browser_name)
@@ -159,8 +181,11 @@ def test_is_element_present_by_value(get_new_browser, browser_name):
assert browser.is_element_present_by_value("M")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_value_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_value_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by value returns False if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -168,7 +193,7 @@ def test_is_element_present_by_value_returns_false_if_element_is_not_present(get
assert not browser.is_element_present_by_value("async-header-value")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_value(get_new_browser, browser_name):
"should is element not present by value verify if element is not present"
browser = get_new_browser(browser_name)
@@ -177,8 +202,11 @@ def test_is_element_not_present_by_value(get_new_browser, browser_name):
assert browser.is_element_not_present_by_value("async-header-value")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_value_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_value_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by value returns False if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -186,7 +214,7 @@ def test_is_element_not_present_by_value_returns_false_if_element_is_present(get
assert not browser.is_element_not_present_by_value("default value")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_id(get_new_browser, browser_name):
"should is element present by id verify if element is present"
browser = get_new_browser(browser_name)
@@ -195,8 +223,11 @@ def test_is_element_present_by_id(get_new_browser, browser_name):
assert browser.is_element_present_by_id("firstheader")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_id_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_id_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by id returns False if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -204,7 +235,7 @@ def test_is_element_present_by_id_returns_false_if_element_is_not_present(get_ne
assert not browser.is_element_present_by_id("async-header")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_id(get_new_browser, browser_name):
"should is element not present by id verify if element is not present"
browser = get_new_browser(browser_name)
@@ -213,8 +244,11 @@ def test_is_element_not_present_by_id(get_new_browser, browser_name):
assert browser.is_element_not_present_by_id("async-header")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_id_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_id_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by id returns False if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -222,7 +256,7 @@ def test_is_element_not_present_by_id_returns_false_if_element_is_present(get_ne
assert not browser.is_element_not_present_by_id("firstheader")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_present_by_name(get_new_browser, browser_name):
"should is element present by name verify if element is present"
browser = get_new_browser(browser_name)
@@ -231,8 +265,11 @@ def test_is_element_present_by_name(get_new_browser, browser_name):
assert browser.is_element_present_by_name("query")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_present_by_name_returns_false_if_element_is_not_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_present_by_name_returns_false_if_element_is_not_present(
+ get_new_browser,
+ browser_name,
+):
"should is element present by name returns false if element is not present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -240,7 +277,7 @@ def test_is_element_present_by_name_returns_false_if_element_is_not_present(get_
assert not browser.is_element_present_by_name("async-input")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_is_element_not_present_by_name(get_new_browser, browser_name):
"should is element not present by name verify if element is not present"
browser = get_new_browser(browser_name)
@@ -249,8 +286,11 @@ def test_is_element_not_present_by_name(get_new_browser, browser_name):
assert browser.is_element_not_present_by_name("async-input")
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_element_not_present_by_name_returns_false_if_element_is_present(get_new_browser, browser_name):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_element_not_present_by_name_returns_false_if_element_is_present(
+ get_new_browser,
+ browser_name,
+):
"should is element not present by name returns false if element is present"
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
diff --git a/tests/test_meta.py b/tests/test_meta.py
index 43aaa83e3..5b19d45d4 100644
--- a/tests/test_meta.py
+++ b/tests/test_meta.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import unittest
from splinter.meta import InheritedDocs
diff --git a/tests/test_mouse_interaction.py b/tests/test_mouse_interaction.py
index 75c52fcbf..82ec206e2 100644
--- a/tests/test_mouse_interaction.py
+++ b/tests/test_mouse_interaction.py
@@ -3,13 +3,13 @@
# license that can be found in the LICENSE file.
import time
+import pytest
+
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_mouse_over(browser_name, get_new_browser):
"Should be able to perform a mouse over on an element"
browser = get_new_browser(browser_name)
@@ -24,7 +24,7 @@ def test_mouse_over(browser_name, get_new_browser):
element.mouse_out()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_mouse_out(browser_name, get_new_browser):
"Should be able to perform a mouse out on an element"
browser = get_new_browser(browser_name)
@@ -36,13 +36,13 @@ def test_mouse_out(browser_name, get_new_browser):
assert browser.is_element_not_present_by_id("what-is-your-name")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_mouse_out_top_left(browser_name, get_new_browser):
"""Should be able to perform a mouse out on an element,
even if the element is at the top left corner of the screen.
"""
browser = get_new_browser(browser_name)
- browser.visit(EXAMPLE_APP + '/mouse')
+ browser.visit(EXAMPLE_APP + "/mouse")
element = browser.find_by_css(".add-element-mouseover")
element.mouse_over()
@@ -51,7 +51,7 @@ def test_mouse_out_top_left(browser_name, get_new_browser):
assert browser.is_element_not_present_by_id("what-is-your-name")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_double_click(browser_name, get_new_browser):
"""Test: WebDriverElement.double_click()
@@ -64,11 +64,13 @@ def test_double_click(browser_name, get_new_browser):
button = browser.find_by_css(".db-button")
button.double_click()
- assert browser.find_by_css(".should-be-visible-after-double-click").is_visible(wait_time=5)
+ assert browser.find_by_css(".should-be-visible-after-double-click").is_visible(
+ wait_time=5,
+ )
assert browser.is_element_not_present_by_id("what-is-your-name")
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_right_click(browser_name, get_new_browser):
"should be able to perform a right click on an element"
browser = get_new_browser(browser_name)
@@ -84,7 +86,7 @@ def test_right_click(browser_name, get_new_browser):
assert result_1 == result_2 == "right clicked"
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_drag_and_drop(browser_name, get_new_browser):
"""
should be able to perform a drag an element and drop in another element
diff --git a/tests/test_popups.py b/tests/test_popups.py
index aa6b5ce38..c28e06b6f 100644
--- a/tests/test_popups.py
+++ b/tests/test_popups.py
@@ -1,17 +1,15 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2015 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import time
+import pytest
+
from .base import supported_browsers
from .fake_webapp import EXAMPLE_APP
-import pytest
-
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_lists_all_windows_as_window_instances(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -28,22 +26,26 @@ def test_lists_all_windows_as_window_instances(browser_name, get_new_browser):
assert 2 == windows_count
- for window, handle in zip(
- browser.windows, browser.driver.window_handles
- ):
+ for window, handle in zip(browser.windows, browser.driver.window_handles):
assert window.name == handle
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_current_is_a_window_instance_pointing_to_current_window(browser_name, get_new_browser):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_current_is_a_window_instance_pointing_to_current_window(
+ browser_name,
+ get_new_browser,
+):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
assert browser.windows.current.name == browser.driver.current_window_handle
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_set_current_to_window_instance_sets_current_window(browser_name, get_new_browser):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_set_current_to_window_instance_sets_current_window(
+ browser_name,
+ get_new_browser,
+):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
browser.find_by_id("open-popup").click()
@@ -53,7 +55,7 @@ def test_set_current_to_window_instance_sets_current_window(browser_name, get_ne
assert browser.windows.current != last_current_window
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_next_prev_return_next_prev_windows(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -63,8 +65,11 @@ def test_next_prev_return_next_prev_windows(browser_name, get_new_browser):
assert browser.windows.current != browser.windows.current.next
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_is_current_returns_true_if_current_window_else_false(browser_name, get_new_browser):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_is_current_returns_true_if_current_window_else_false(
+ browser_name,
+ get_new_browser,
+):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
browser.find_by_id("open-popup").click()
@@ -76,7 +81,7 @@ def test_is_current_returns_true_if_current_window_else_false(browser_name, get_
browser.windows.current.close_others()
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_set_is_current_to_true_sets_window_to_current(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -89,7 +94,7 @@ def test_set_is_current_to_true_sets_window_to_current(browser_name, get_new_bro
assert next_window.is_current
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_get_window_by_index(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -98,7 +103,7 @@ def test_get_window_by_index(browser_name, get_new_browser):
assert browser.windows[0].name == browser.driver.window_handles[0]
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_get_window_by_name(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -108,7 +113,7 @@ def test_get_window_by_name(browser_name, get_new_browser):
assert browser.windows[window_handle].name == window_handle
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_close_closes_window(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -120,8 +125,11 @@ def test_close_closes_window(browser_name, get_new_browser):
assert browser.windows.current == current
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_close_current_window_expect_previous_window_becomes_current(browser_name, get_new_browser):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_close_current_window_expect_previous_window_becomes_current(
+ browser_name,
+ get_new_browser,
+):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
browser.find_by_id("open-popup").click()
@@ -134,8 +142,11 @@ def test_close_current_window_expect_previous_window_becomes_current(browser_nam
assert browser.windows.current == prev
-@pytest.mark.parametrize('browser_name', supported_browsers)
-def test_close_others_expect_close_all_other_open_windows(browser_name, get_new_browser):
+@pytest.mark.parametrize("browser_name", supported_browsers)
+def test_close_others_expect_close_all_other_open_windows(
+ browser_name,
+ get_new_browser,
+):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
diff --git a/tests/test_request_handler.py b/tests/test_request_handler.py
index e551651d1..2212ed783 100644
--- a/tests/test_request_handler.py
+++ b/tests/test_request_handler.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import unittest
from splinter.request_handler.status_code import StatusCode
diff --git a/tests/test_screenshot.py b/tests/test_screenshot.py
index 7d4b342b2..a10af70c1 100644
--- a/tests/test_screenshot.py
+++ b/tests/test_screenshot.py
@@ -1,21 +1,17 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
import tempfile
-from .base import supported_browsers
-from .fake_webapp import EXAMPLE_APP
-
import pytest
-
from selenium.common.exceptions import WebDriverException
+from .base import supported_browsers
+from .fake_webapp import EXAMPLE_APP
+
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_screenshot_no_unique_file(browser_name, get_new_browser):
"""When the unique_file parameter is false,
Then the screenshot filename should match the name parameter exactly.
@@ -23,12 +19,12 @@ def test_take_screenshot_no_unique_file(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
- browser.screenshot(name='test_screenshot', unique_file=False)
- expected_filepath = os.path.abspath('test_screenshot.png')
+ browser.screenshot(name="test_screenshot", unique_file=False)
+ expected_filepath = os.path.abspath("test_screenshot.png")
assert os.path.isfile(expected_filepath)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_screenshot(browser_name, get_new_browser):
"""Should take a screenshot of the current page"""
browser = get_new_browser(browser_name)
@@ -38,7 +34,7 @@ def test_take_screenshot(browser_name, get_new_browser):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_screenshot_full_screen(browser_name, get_new_browser):
"""Should take a full screen screenshot of the current page"""
browser = get_new_browser(browser_name)
@@ -48,7 +44,7 @@ def test_take_screenshot_full_screen(browser_name, get_new_browser):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_screenshot_with_prefix(browser_name, get_new_browser):
"""Should add the prefix to the screenshot file name"""
browser = get_new_browser(browser_name)
@@ -58,7 +54,7 @@ def test_take_screenshot_with_prefix(browser_name, get_new_browser):
assert "foobar" in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_screenshot_with_suffix(browser_name, get_new_browser):
"""Should add the suffix to the screenshot file name"""
browser = get_new_browser(browser_name)
@@ -68,7 +64,7 @@ def test_take_screenshot_with_suffix(browser_name, get_new_browser):
assert ".jpg" in filename[-4:]
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_element_screenshot(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -78,7 +74,7 @@ def test_take_element_screenshot(browser_name, get_new_browser):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_element_screenshot_with_prefix(browser_name, get_new_browser):
"""Should add the prefix to the screenshot file name"""
browser = get_new_browser(browser_name)
@@ -89,7 +85,7 @@ def test_take_element_screenshot_with_prefix(browser_name, get_new_browser):
assert "foobar" in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_element_screenshot_full_screen(browser_name, get_new_browser):
"""Should resize the window before taking screenshot of the element"""
browser = get_new_browser(browser_name)
@@ -100,7 +96,7 @@ def test_take_element_screenshot_full_screen(browser_name, get_new_browser):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_take_nested_element_screenshot(browser_name, get_new_browser):
browser = get_new_browser(browser_name)
browser.visit(EXAMPLE_APP)
@@ -110,7 +106,7 @@ def test_take_nested_element_screenshot(browser_name, get_new_browser):
assert tempfile.gettempdir() in filename
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_element_screenshot_zero_size(browser_name, get_new_browser):
"""Elements with 0 width and 0 height should crash."""
browser = get_new_browser(browser_name)
diff --git a/tests/test_shadow_root.py b/tests/test_shadow_root.py
index c6fcf46f5..7d9cf64e0 100644
--- a/tests/test_shadow_root.py
+++ b/tests/test_shadow_root.py
@@ -1,14 +1,13 @@
-from .fake_webapp import EXAMPLE_APP
-
import pytest
+from .fake_webapp import EXAMPLE_APP
from splinter.driver.webdriver import ShadowRootElement
-supported_browsers = ['chrome', 'chrome_fullscreen']
+supported_browsers = ["chrome", "chrome_fullscreen"]
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_shadow_root(browser_name, get_new_browser):
"""The shadow_root property will return a ShadowRootElement."""
browser = get_new_browser(browser_name)
@@ -19,7 +18,7 @@ def test_shadow_root(browser_name, get_new_browser):
assert isinstance(shadow_root, ShadowRootElement)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_shadow_root_element_find_by_css(browser_name, get_new_browser):
"""ShadowRootElement implements ElementAPI.find_by_css."""
browser = get_new_browser(browser_name)
@@ -32,7 +31,7 @@ def test_shadow_root_element_find_by_css(browser_name, get_new_browser):
assert "Inside a shadow root" == inner_element.value
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_shadow_root_element_find_by_name(browser_name, get_new_browser):
"""ShadowRootElement implements ElementAPI.find_by_value."""
browser = get_new_browser(browser_name)
diff --git a/tests/test_webdriver.py b/tests/test_webdriver.py
index 96c945efc..ec04f1eed 100644
--- a/tests/test_webdriver.py
+++ b/tests/test_webdriver.py
@@ -1,15 +1,14 @@
import os
+import pytest
from selenium.common.exceptions import WebDriverException
from .base import supported_browsers
-from .get_browser import get_browser
from .fake_webapp import EXAMPLE_APP
-
-import pytest
+from .get_browser import get_browser
-@pytest.mark.parametrize('browser_name', ['chrome', 'firefox'])
+@pytest.mark.parametrize("browser_name", ["chrome", "firefox"])
def test_webdriver_local_driver_not_present(browser_name):
"""When chromedriver/geckodriver are not present on the system."""
from splinter import Browser
@@ -17,10 +16,10 @@ def test_webdriver_local_driver_not_present(browser_name):
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
- if browser_name == 'chrome':
- service = ChromeService(executable_path='failpath')
+ if browser_name == "chrome":
+ service = ChromeService(executable_path="failpath")
else:
- service = FirefoxService(executable_path='failpath')
+ service = FirefoxService(executable_path="failpath")
with pytest.raises(WebDriverException) as e:
Browser(browser_name, service=service)
@@ -28,15 +27,13 @@ def test_webdriver_local_driver_not_present(browser_name):
assert "Message: 'failpath' executable needs to be in PATH." in str(e.value)
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_attach_file(request, browser_name):
"""Should provide a way to change file field value"""
browser = get_browser(browser_name)
request.addfinalizer(browser.quit)
- file_path = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), "mockfile.txt"
- )
+ file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "mockfile.txt")
browser.visit(EXAMPLE_APP)
browser.attach_file("file", file_path)
@@ -45,17 +42,17 @@ def test_attach_file(request, browser_name):
html = browser.html
assert "text/plain" in html
- with open(file_path, "r") as f:
+ with open(file_path) as f:
assert str(f.read().encode("utf-8")) in html
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_should_support_with_statement(browser_name):
with get_browser(browser_name):
pass
-@pytest.mark.parametrize('browser_name', supported_browsers)
+@pytest.mark.parametrize("browser_name", supported_browsers)
def test_browser_config(request, browser_name):
"""Splinter's drivers get the Config object when it's passed through the Browser function."""
from splinter import Config
@@ -64,4 +61,4 @@ def test_browser_config(request, browser_name):
browser = get_browser(browser_name, config=config)
request.addfinalizer(browser.quit)
- assert browser.config.user_agent == 'agent_smith'
+ assert browser.config.user_agent == "agent_smith"
diff --git a/tests/test_webdriver_chrome.py b/tests/test_webdriver_chrome.py
index 6ed730017..e69f4e886 100644
--- a/tests/test_webdriver_chrome.py
+++ b/tests/test_webdriver_chrome.py
@@ -1,21 +1,19 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import unittest
import pytest
+from .base import get_browser
+from .base import WebDriverTests
from .fake_webapp import EXAMPLE_APP
-from .base import WebDriverTests, get_browser
class ChromeBrowserTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('chrome', fullscreen=False)
+ request.cls.browser = get_browser("chrome", fullscreen=False)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
@@ -25,9 +23,9 @@ def visit_example_app(self, request):
class ChromeBrowserFullscreenTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('chrome', fullscreen=True)
+ request.cls.browser = get_browser("chrome", fullscreen=True)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
diff --git a/tests/test_webdriver_edge_chromium.py b/tests/test_webdriver_edge_chromium.py
index b7e49b56c..684702d28 100644
--- a/tests/test_webdriver_edge_chromium.py
+++ b/tests/test_webdriver_edge_chromium.py
@@ -1,21 +1,19 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2021 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import unittest
import pytest
+from .base import get_browser
+from .base import WebDriverTests
from .fake_webapp import EXAMPLE_APP
-from .base import WebDriverTests, get_browser
class EdgeChromiumBrowserTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('edge', fullscreen=False)
+ request.cls.browser = get_browser("edge", fullscreen=False)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
@@ -25,9 +23,9 @@ def visit_example_app(self, request):
class EdgeChromiumBrowserFullscreenTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('edge', fullscreen=True)
+ request.cls.browser = get_browser("edge", fullscreen=True)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
diff --git a/tests/test_webdriver_firefox.py b/tests/test_webdriver_firefox.py
index 6991ffd36..440fdefd8 100644
--- a/tests/test_webdriver_firefox.py
+++ b/tests/test_webdriver_firefox.py
@@ -1,24 +1,21 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
import unittest
import pytest
-from splinter.config import Config
-
+from .base import get_browser
+from .base import WebDriverTests
from .fake_webapp import EXAMPLE_APP
-from .base import WebDriverTests, get_browser
+from splinter.config import Config
class FirefoxBrowserTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('firefox', fullscreen=False)
+ request.cls.browser = get_browser("firefox", fullscreen=False)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
@@ -27,9 +24,9 @@ def visit_example_app(self, request):
class FirefoxBrowserFullScreenTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = get_browser('firefox', fullscreen=True)
+ request.cls.browser = get_browser("firefox", fullscreen=True)
request.addfinalizer(request.cls.browser.quit)
@pytest.fixture(autouse=True)
@@ -44,19 +41,19 @@ def test_firefox_create_instance_with_extension(request):
"""
extension_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
- 'dummy_extension',
- 'borderify-1.0-an+fx.xpi',
+ "dummy_extension",
+ "borderify-1.0-an+fx.xpi",
)
config = Config(extensions=[extension_path])
- browser = get_browser('firefox', config=config)
+ browser = get_browser("firefox", config=config)
request.addfinalizer(browser.quit)
browser.visit(EXAMPLE_APP)
- elem = browser.find_by_css('body')
+ elem = browser.find_by_css("body")
elem.is_visible(wait_time=5)
- style = elem._element.get_attribute('style')
+ style = elem._element.get_attribute("style")
assert "border: 5px solid red;" == style
@@ -66,7 +63,7 @@ def test_preference_set(request):
"dom.max_script_run_time": 213,
"devtools.inspector.enabled": True,
}
- browser = get_browser('firefox', profile_preferences=preferences)
+ browser = get_browser("firefox", profile_preferences=preferences)
request.addfinalizer(browser.quit)
# Rip the preferences out of firefox's config page
@@ -78,7 +75,7 @@ def test_preference_set(request):
def test_capabilities_set(request):
- browser = get_browser('firefox', capabilities={"pageLoadStrategy": "eager"})
+ browser = get_browser("firefox", capabilities={"pageLoadStrategy": "eager"})
request.addfinalizer(browser.quit)
capabilities = browser.driver.capabilities
diff --git a/tests/test_webdriver_remote.py b/tests/test_webdriver_remote.py
index 12039ff42..12f835dfa 100644
--- a/tests/test_webdriver_remote.py
+++ b/tests/test_webdriver_remote.py
@@ -1,34 +1,30 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
-
-from urllib.request import urlopen
import unittest
-
-from splinter import Browser
-from .fake_webapp import EXAMPLE_APP
-from .base import WebDriverTests
+from urllib.request import urlopen
import pytest
+from .base import WebDriverTests
+from .fake_webapp import EXAMPLE_APP
+from splinter import Browser
+
def selenium_server_is_running():
try:
from splinter.driver.webdriver.remote import WebDriver
page_contents = urlopen(WebDriver.DEFAULT_URL).read()
- except IOError:
+ except OSError:
return False
return "WebDriver Hub" in page_contents
class RemoteBrowserFirefoxTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = Browser('remote', browser='firefox')
+ request.cls.browser = Browser("remote", browser="firefox")
request.addfinalizer(request.cls.browser.quit)
def setUp(self):
@@ -45,9 +41,9 @@ def test_should_be_able_to_change_user_agent(self):
class RemoteBrowserChromeTest(WebDriverTests, unittest.TestCase):
- @pytest.fixture(autouse=True, scope='class')
+ @pytest.fixture(autouse=True, scope="class")
def setup_browser(self, request):
- request.cls.browser = Browser('remote', browser='chrome')
+ request.cls.browser = Browser("remote", browser="chrome")
request.addfinalizer(request.cls.browser.quit)
def setUp(self):
diff --git a/tests/test_xpath_concat.py b/tests/test_xpath_concat.py
index d7bf3a953..afb0f5c3f 100644
--- a/tests/test_xpath_concat.py
+++ b/tests/test_xpath_concat.py
@@ -1,11 +1,9 @@
-# -*- coding: utf-8 -*-
-
from splinter.driver.xpath_utils import _concat_xpath_from_str
-WRAPPED_SINGLE_QUOTE = '\"\'\"'
-WRAPPED_DOUBLE_QUOTE = "\'\"\'"
-XPATH_START = '//*[text()=concat('
+WRAPPED_SINGLE_QUOTE = '"\'"'
+WRAPPED_DOUBLE_QUOTE = "'\"'"
+XPATH_START = "//*[text()=concat("
def test_build_xpath_concat_normal():
@@ -13,8 +11,8 @@ def test_build_xpath_concat_normal():
When I build a concat xpath
Then the xpath string is correctly built
"""
- result = _concat_xpath_from_str('No quotation marks.')
- expected = "{}'No quotation marks.', \"\")]".format(XPATH_START)
+ result = _concat_xpath_from_str("No quotation marks.")
+ expected = f"{XPATH_START}'No quotation marks.', \"\")]"
assert result == expected
@@ -23,9 +21,11 @@ def test_build_xpath_concat_double_quote():
When I build a concat xpath
Then the xpath string is correctly built
"""
- result = _concat_xpath_from_str('Denis \"Snake\" Bélanger')
+ result = _concat_xpath_from_str('Denis "Snake" Bélanger')
expected = "{}'Denis ',{},'Snake',{},' Bélanger', \"\")]".format(
- XPATH_START, WRAPPED_DOUBLE_QUOTE, WRAPPED_DOUBLE_QUOTE,
+ XPATH_START,
+ WRAPPED_DOUBLE_QUOTE,
+ WRAPPED_DOUBLE_QUOTE,
)
assert result == expected
@@ -35,9 +35,10 @@ def test_build_xpath_concat_single_quote():
When I build a concat xpath
Then the xpath string is correctly built
"""
- result = _concat_xpath_from_str('Text with a single \' quotation mark.')
- expected = "{}\"Text with a single \",{},\" quotation mark.\", \"\")]".format(
- XPATH_START, WRAPPED_SINGLE_QUOTE,
+ result = _concat_xpath_from_str("Text with a single ' quotation mark.")
+ expected = '{}"Text with a single ",{}," quotation mark.", "")]'.format(
+ XPATH_START,
+ WRAPPED_SINGLE_QUOTE,
)
assert result == expected
@@ -47,9 +48,13 @@ def test_build_xpath_concat_multiple_types():
When I build a concat xpath
Then the xpath string is correctly built
"""
- result = _concat_xpath_from_str('Text with a single \' quotation mark and double " quotation mark.')
- expected = "{}\"Text with a single \",{},\" quotation mark and double \",{},\' quotation mark.\', \"\")]".format(
- XPATH_START, WRAPPED_SINGLE_QUOTE, WRAPPED_DOUBLE_QUOTE,
+ result = _concat_xpath_from_str(
+ "Text with a single ' quotation mark and double \" quotation mark.",
+ )
+ expected = '{}"Text with a single ",{}," quotation mark and double ",{},\' quotation mark.\', "")]'.format(
+ XPATH_START,
+ WRAPPED_SINGLE_QUOTE,
+ WRAPPED_DOUBLE_QUOTE,
)
assert result == expected
@@ -60,7 +65,10 @@ def test_build_xpath_concat_nested():
Then the xpath string is correctly built
"""
result = _concat_xpath_from_str('A "real ol\' mess" of text.')
- expected = "{}\'A \',{},\"real ol\",{},\" mess\",{},\' of text.\', \"\")]".format(
- XPATH_START, WRAPPED_DOUBLE_QUOTE, WRAPPED_SINGLE_QUOTE, WRAPPED_DOUBLE_QUOTE,
+ expected = '{}\'A \',{},"real ol",{}," mess",{},\' of text.\', "")]'.format(
+ XPATH_START,
+ WRAPPED_DOUBLE_QUOTE,
+ WRAPPED_SINGLE_QUOTE,
+ WRAPPED_DOUBLE_QUOTE,
)
assert result == expected
diff --git a/tests/test_zopetestbrowser.py b/tests/test_zopetestbrowser.py
index 0d74bd174..cb8d4ba35 100644
--- a/tests/test_zopetestbrowser.py
+++ b/tests/test_zopetestbrowser.py
@@ -1,22 +1,17 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
import os
import unittest
import pytest
-from splinter import Browser
from .base import BaseBrowserTests
from .fake_webapp import EXAMPLE_APP
+from splinter import Browser
-class ZopeTestBrowserDriverTest(
- BaseBrowserTests, unittest.TestCase
-):
+class ZopeTestBrowserDriverTest(BaseBrowserTests, unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.browser = Browser("zope.testbrowser", wait_time=0.1)
@@ -35,7 +30,8 @@ def test_should_support_with_statement(self):
def test_attach_file(self):
"should provide a way to change file field value"
file_path = os.path.join(
- os.path.abspath(os.path.dirname(__file__)), "mockfile.txt"
+ os.path.abspath(os.path.dirname(__file__)),
+ "mockfile.txt",
)
self.browser.attach_file("file", file_path)
self.browser.find_by_name("upload").click()
@@ -149,10 +145,10 @@ def test_links_with_nested_tags_xpath(self):
def test_finding_all_links_by_non_ascii_text(self):
"should find links by non ascii text"
non_ascii_encodings = {
- "pangram_pl": u"Jeżu klątw, spłódź Finom część gry hańb!",
- "pangram_ja": u"天 地 星 空",
- "pangram_ru": u"В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
- "pangram_eo": u"Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
+ "pangram_pl": "Jeżu klątw, spłódź Finom część gry hańb!",
+ "pangram_ja": "天 地 星 空",
+ "pangram_ru": "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!",
+ "pangram_eo": "Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.",
}
for key, text in non_ascii_encodings.items():
link = self.browser.links.find_by_text(text)
@@ -167,7 +163,7 @@ def test_fill_form_missing_values(self):
def test_cookies_extra_parameters(self):
"""Cookie can be created with extra parameters."""
- comment = 'Ipsum lorem'
- self.browser.cookies.add({'sha': 'zam'}, comment=comment)
- cookie = self.browser._browser.cookies.getinfo('sha')
- assert 'Ipsum%20lorem' == cookie['comment']
+ comment = "Ipsum lorem"
+ self.browser.cookies.add({"sha": "zam"}, comment=comment)
+ cookie = self.browser._browser.cookies.getinfo("sha")
+ assert "Ipsum%20lorem" == cookie["comment"]
diff --git a/tests/type.py b/tests/type.py
index 705d0e5f6..7a5707f1f 100644
--- a/tests/type.py
+++ b/tests/type.py
@@ -1,9 +1,6 @@
-# -*- coding: utf-8 -*-
-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-
from .fake_webapp import EXAMPLE_APP