Skip to content

Commit

Permalink
[py]: lint conftest.py
Browse files Browse the repository at this point in the history
  • Loading branch information
symonk committed Oct 4, 2022
1 parent d20db99 commit cbf98cd
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 64 deletions.
130 changes: 70 additions & 60 deletions py/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,63 +20,65 @@
import socket
import subprocess
import time
from test.selenium.webdriver.common.network import get_lan_ip
from test.selenium.webdriver.common.webserver import SimpleWebServer
from urllib.request import urlopen

import pytest

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from test.selenium.webdriver.common.webserver import SimpleWebServer
from test.selenium.webdriver.common.network import get_lan_ip

from urllib.request import urlopen

drivers = (
'chrome',
'edge',
'firefox',
'ie',
'remote',
'safari',
'webkitgtk',
'chromiumedge',
'wpewebkit',
"chrome",
"edge",
"firefox",
"ie",
"remote",
"safari",
"webkitgtk",
"chromiumedge",
"wpewebkit",
)


def pytest_addoption(parser):
parser.addoption('--driver', action='append', choices=drivers, dest='drivers',
metavar='DRIVER',
help='driver to run tests against ({})'.format(', '.join(drivers)))
parser.addoption('--browser-binary', action='store', dest='binary',
help='location of the browser binary')
parser.addoption('--driver-binary', action='store', dest='executable',
help='location of the service executable binary')
parser.addoption('--browser-args', action='store', dest='args',
help='arguments to start the browser with')
parser.addoption('--headless', action='store', dest='headless',
help="Allow tests to run in headless")
parser.addoption(
"--driver",
action="append",
choices=drivers,
dest="drivers",
metavar="DRIVER",
help="driver to run tests against ({})".format(", ".join(drivers)),
)
parser.addoption("--browser-binary", action="store", dest="binary", help="location of the browser binary")
parser.addoption(
"--driver-binary", action="store", dest="executable", help="location of the service executable binary"
)
parser.addoption("--browser-args", action="store", dest="args", help="arguments to start the browser with")
parser.addoption("--headless", action="store", dest="headless", help="Allow tests to run in headless")


def pytest_ignore_collect(path, config):
drivers_opt = config.getoption('drivers')
drivers_opt = config.getoption("drivers")
_drivers = set(drivers).difference(drivers_opt or drivers)
if drivers_opt:
_drivers.add('unit')
_drivers.add("unit")
parts = path.dirname.split(os.path.sep)
return len([d for d in _drivers if d.lower() in parts]) > 0


driver_instance = None


@pytest.fixture(scope='function')
@pytest.fixture(scope="function")
def driver(request):
kwargs = {}

try:
driver_class = request.param.capitalize()
except AttributeError:
raise Exception('This test requires a --driver to be specified.')
raise Exception("This test requires a --driver to be specified.")

# skip tests if not available on the platform
_platform = platform.system()
Expand All @@ -88,7 +90,7 @@ def driver(request):
pytest.skip("Webkit tests can only run on Linux")

# conditionally mark tests as expected to fail based on driver
marker = request.node.get_closest_marker(f'xfail_{driver_class.lower()}')
marker = request.node.get_closest_marker(f"xfail_{driver_class.lower()}")

if marker is not None:
if "run" in marker.kwargs:
Expand All @@ -105,31 +107,32 @@ def fin():
if driver_instance is not None:
driver_instance.quit()
driver_instance = None

request.addfinalizer(fin)

driver_path = request.config.option.executable
options = None

global driver_instance
if driver_instance is None:
if driver_class == 'Firefox':
if driver_class == "Firefox":
options = get_options(driver_class, request.config)
if driver_class == 'Chrome':
if driver_class == "Chrome":
options = get_options(driver_class, request.config)
if driver_class == 'Remote':
if driver_class == "Remote":
capabilities = DesiredCapabilities.FIREFOX.copy()
kwargs.update({'desired_capabilities': capabilities})
options = get_options('Firefox', request.config)
if driver_class == 'WebKitGTK':
kwargs.update({"desired_capabilities": capabilities})
options = get_options("Firefox", request.config)
if driver_class == "WebKitGTK":
options = get_options(driver_class, request.config)
if driver_class == 'Edge':
if driver_class == "Edge":
options = get_options(driver_class, request.config)
if driver_class == 'WPEWebKit':
if driver_class == "WPEWebKit":
options = get_options(driver_class, request.config)
if driver_path is not None:
kwargs['executable_path'] = driver_path
kwargs["executable_path"] = driver_path
if options is not None:
kwargs['options'] = options
kwargs["options"] = options

driver_instance = getattr(webdriver, driver_class)(**kwargs)
yield driver_instance
Expand All @@ -144,13 +147,13 @@ def get_options(driver_class, config):
headless = bool(config.option.headless)
options = None

if driver_class == 'ChromiumEdge':
options = getattr(webdriver, 'EdgeOptions')()
if driver_class == "ChromiumEdge":
options = getattr(webdriver, "EdgeOptions")()

if browser_path or browser_args:
if not options:
options = getattr(webdriver, f'{driver_class}Options')()
if driver_class == 'WebKitGTK':
options = getattr(webdriver, f"{driver_class}Options")()
if driver_class == "WebKitGTK":
options.overlay_scrollbars_enabled = False
if browser_path is not None:
options.binary_location = browser_path
Expand All @@ -166,13 +169,14 @@ def get_options(driver_class, config):
return options


@pytest.fixture(scope='session', autouse=True)
@pytest.fixture(scope="session", autouse=True)
def stop_driver(request):
def fin():
global driver_instance
if driver_instance is not None:
driver_instance.quit()
driver_instance = None

request.addfinalizer(fin)


Expand All @@ -192,20 +196,23 @@ def url(self, name, localhost=False):

def load(self, name):
driver.get(self.url(name))

return Pages()


@pytest.fixture(autouse=True, scope='session')
@pytest.fixture(autouse=True, scope="session")
def server(request):
drivers = request.config.getoption('drivers')
if drivers is None or 'remote' not in drivers:
drivers = request.config.getoption("drivers")
if drivers is None or "remote" not in drivers:
yield None
return

_host = 'localhost'
_host = "localhost"
_port = 4444
_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'java/src/org/openqa/selenium/grid/selenium_server_deploy.jar')
_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"java/src/org/openqa/selenium/grid/selenium_server_deploy.jar",
)

def wait_for_server(url, timeout):
start = time.time()
Expand All @@ -218,24 +225,26 @@ def wait_for_server(url, timeout):
return 0

_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = f'http://{_host}:{_port}/status'
url = f"http://{_host}:{_port}/status"
try:
_socket.connect((_host, _port))
print('The remote driver server is already running or something else'
'is using port {}, continuing...'.format(_port))
print(
"The remote driver server is already running or something else"
"is using port {}, continuing...".format(_port)
)
except Exception:
print('Starting the Selenium server')
process = subprocess.Popen(['java', '-jar', _path, 'standalone', '--port', '4444'])
print(f'Selenium server running as process: {process.pid}')
assert wait_for_server(url, 10), f'Timed out waiting for Selenium server at {url}'
print('Selenium server is ready')
print("Starting the Selenium server")
process = subprocess.Popen(["java", "-jar", _path, "standalone", "--port", "4444"])
print(f"Selenium server running as process: {process.pid}")
assert wait_for_server(url, 10), f"Timed out waiting for Selenium server at {url}"
print("Selenium server is ready")
yield process
process.terminate()
process.wait()
print('Selenium server has been terminated')
print("Selenium server has been terminated")


@pytest.fixture(autouse=True, scope='session')
@pytest.fixture(autouse=True, scope="session")
def webserver():
webserver = SimpleWebServer(host=get_lan_ip())
webserver.start()
Expand All @@ -246,4 +255,5 @@ def webserver():
@pytest.fixture
def edge_service():
from selenium.webdriver.edge.service import Service as EdgeService

return EdgeService
8 changes: 4 additions & 4 deletions py/tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ deps =
flake8-typing-imports==1.13.0
commands =
; execute isort in check only mode.
isort --check-only --diff selenium/ test/
isort --check-only --diff selenium/ test/ conftest.py
; execute black in check only mode with diff.
black --check --diff selenium/ test/ -l 120
black --check --diff selenium/ test/ conftest.py -l 120
flake8 selenium/ test/ --min-python-version=3.7

[testenv:linting]
Expand All @@ -54,6 +54,6 @@ deps =
flake8==5.0.4
flake8-typing-imports==1.13.0
commands =
isort selenium/ test/
black selenium/ test/ -l 120
isort selenium/ test/ conftest.py
black selenium/ test/ conftest.py -l 120
flake8 selenium/ test/ --min-python-version=3.7

0 comments on commit cbf98cd

Please sign in to comment.