| 1 |
import sys |
| 2 |
import unittest |
| 3 |
from contextlib import contextmanager |
| 4 |
from functools import wraps |
| 5 |
from pathlib import Path |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.test import LiveServerTestCase, override_settings, tag |
| 9 |
from django.utils.functional import classproperty |
| 10 |
from django.utils.module_loading import import_string |
| 11 |
from django.utils.text import capfirst |
| 12 |
|
| 13 |
|
| 14 |
class SeleniumTestCaseBase(type(LiveServerTestCase)): |
| 15 |
# List of browsers to dynamically create test classes for. |
| 16 |
browsers = [] |
| 17 |
# A selenium hub URL to test against. |
| 18 |
selenium_hub = None |
| 19 |
# The external host Selenium Hub can reach. |
| 20 |
external_host = None |
| 21 |
# Sentinel value to differentiate browser-specific instances. |
| 22 |
browser = None |
| 23 |
# Run browsers in headless mode. |
| 24 |
headless = False |
| 25 |
|
| 26 |
def __new__(cls, name, bases, attrs): |
| 27 |
""" |
| 28 |
Dynamically create new classes and add them to the test module when |
| 29 |
multiple browsers specs are provided (e.g. --selenium=firefox,chrome). |
| 30 |
""" |
| 31 |
test_class = super().__new__(cls, name, bases, attrs) |
| 32 |
# If the test class is either browser-specific or a test base, return it. |
| 33 |
if test_class.browser or not any( |
| 34 |
name.startswith("test") and callable(value) for name, value in attrs.items() |
| 35 |
): |
| 36 |
return test_class |
| 37 |
elif test_class.browsers: |
| 38 |
# Reuse the created test class to make it browser-specific. |
| 39 |
# We can't rename it to include the browser name or create a |
| 40 |
# subclass like we do with the remaining browsers as it would |
| 41 |
# either duplicate tests or prevent pickling of its instances. |
| 42 |
first_browser = test_class.browsers[0] |
| 43 |
test_class.browser = first_browser |
| 44 |
# Listen on an external interface if using a selenium hub. |
| 45 |
host = test_class.host if not test_class.selenium_hub else "0.0.0.0" |
| 46 |
test_class.host = host |
| 47 |
test_class.external_host = cls.external_host |
| 48 |
# Create subclasses for each of the remaining browsers and expose |
| 49 |
# them through the test's module namespace. |
| 50 |
module = sys.modules[test_class.__module__] |
| 51 |
for browser in test_class.browsers[1:]: |
| 52 |
browser_test_class = cls.__new__( |
| 53 |
cls, |
| 54 |
"%s%s" % (capfirst(browser), name), |
| 55 |
(test_class,), |
| 56 |
{ |
| 57 |
"browser": browser, |
| 58 |
"host": host, |
| 59 |
"external_host": cls.external_host, |
| 60 |
"__module__": test_class.__module__, |
| 61 |
}, |
| 62 |
) |
| 63 |
setattr(module, browser_test_class.__name__, browser_test_class) |
| 64 |
return test_class |
| 65 |
# If no browsers were specified, skip this class (it'll still be discovered). |
| 66 |
return unittest.skip("No browsers specified.")(test_class) |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def import_webdriver(cls, browser): |
| 70 |
return import_string("selenium.webdriver.%s.webdriver.WebDriver" % browser) |
| 71 |
|
| 72 |
@classmethod |
| 73 |
def import_options(cls, browser): |
| 74 |
return import_string("selenium.webdriver.%s.options.Options" % browser) |
| 75 |
|
| 76 |
@classmethod |
| 77 |
def get_capability(cls, browser): |
| 78 |
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities |
| 79 |
|
| 80 |
return getattr(DesiredCapabilities, browser.upper()) |
| 81 |
|
| 82 |
def create_options(self): |
| 83 |
options = self.import_options(self.browser)() |
| 84 |
if self.headless: |
| 85 |
match self.browser: |
| 86 |
case "chrome" | "edge": |
| 87 |
options.add_argument("--headless=new") |
| 88 |
case "firefox": |
| 89 |
options.add_argument("-headless") |
| 90 |
return options |
| 91 |
|
| 92 |
def create_webdriver(self): |
| 93 |
options = self.create_options() |
| 94 |
if self.selenium_hub: |
| 95 |
from selenium import webdriver |
| 96 |
|
| 97 |
for key, value in self.get_capability(self.browser).items(): |
| 98 |
options.set_capability(key, value) |
| 99 |
|
| 100 |
return webdriver.Remote(command_executor=self.selenium_hub, options=options) |
| 101 |
return self.import_webdriver(self.browser)(options=options) |
| 102 |
|
| 103 |
|
| 104 |
class ChangeWindowSize: |
| 105 |
def __init__(self, width, height, selenium): |
| 106 |
self.selenium = selenium |
| 107 |
self.new_size = (width, height) |
| 108 |
|
| 109 |
def __enter__(self): |
| 110 |
self.old_size = self.selenium.get_window_size() |
| 111 |
self.selenium.set_window_size(*self.new_size) |
| 112 |
return self |
| 113 |
|
| 114 |
def __exit__(self, exc_type, exc_value, traceback): |
| 115 |
self.selenium.set_window_size(self.old_size["width"], self.old_size["height"]) |
| 116 |
|
| 117 |
|
| 118 |
@tag("selenium") |
| 119 |
class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): |
| 120 |
implicit_wait = 10 |
| 121 |
external_host = None |
| 122 |
screenshots = False |
| 123 |
|
| 124 |
@classmethod |
| 125 |
def __init_subclass__(cls, **kwargs): |
| 126 |
super().__init_subclass__(**kwargs) |
| 127 |
if not cls.screenshots: |
| 128 |
return |
| 129 |
|
| 130 |
for name, func in list(cls.__dict__.items()): |
| 131 |
if not hasattr(func, "_screenshot_cases"): |
| 132 |
continue |
| 133 |
# Remove the main test. |
| 134 |
delattr(cls, name) |
| 135 |
# Add separate tests for each screenshot type. |
| 136 |
for screenshot_case in getattr(func, "_screenshot_cases"): |
| 137 |
|
| 138 |
@wraps(func) |
| 139 |
def test(self, *args, _func=func, _case=screenshot_case, **kwargs): |
| 140 |
with getattr(self, _case)(): |
| 141 |
return _func(self, *args, **kwargs) |
| 142 |
|
| 143 |
test.__name__ = f"{name}_{screenshot_case}" |
| 144 |
test.__qualname__ = f"{test.__qualname__}_{screenshot_case}" |
| 145 |
test._screenshot_name = name |
| 146 |
test._screenshot_case = screenshot_case |
| 147 |
setattr(cls, test.__name__, test) |
| 148 |
|
| 149 |
@classproperty |
| 150 |
def live_server_url(cls): |
| 151 |
return "http://%s:%s" % (cls.external_host or cls.host, cls.server_thread.port) |
| 152 |
|
| 153 |
@classproperty |
| 154 |
def allowed_host(cls): |
| 155 |
return cls.external_host or cls.host |
| 156 |
|
| 157 |
@classmethod |
| 158 |
def setUpClass(cls): |
| 159 |
cls.selenium = cls.create_webdriver() |
| 160 |
cls.selenium.implicitly_wait(cls.implicit_wait) |
| 161 |
super().setUpClass() |
| 162 |
cls.addClassCleanup(cls._quit_selenium) |
| 163 |
|
| 164 |
@contextmanager |
| 165 |
def desktop_size(self): |
| 166 |
with ChangeWindowSize(1280, 720, self.selenium): |
| 167 |
yield |
| 168 |
|
| 169 |
@contextmanager |
| 170 |
def small_screen_size(self): |
| 171 |
with ChangeWindowSize(1024, 768, self.selenium): |
| 172 |
yield |
| 173 |
|
| 174 |
@contextmanager |
| 175 |
def mobile_size(self): |
| 176 |
with ChangeWindowSize(360, 800, self.selenium): |
| 177 |
yield |
| 178 |
|
| 179 |
@contextmanager |
| 180 |
def rtl(self): |
| 181 |
with self.desktop_size(): |
| 182 |
with override_settings(LANGUAGE_CODE=settings.LANGUAGES_BIDI[-1]): |
| 183 |
yield |
| 184 |
|
| 185 |
@contextmanager |
| 186 |
def dark(self): |
| 187 |
# Navigate to a page before executing a script. |
| 188 |
self.selenium.get(self.live_server_url) |
| 189 |
self.selenium.execute_script("localStorage.setItem('theme', 'dark');") |
| 190 |
with self.desktop_size(): |
| 191 |
try: |
| 192 |
yield |
| 193 |
finally: |
| 194 |
self.selenium.execute_script("localStorage.removeItem('theme');") |
| 195 |
|
| 196 |
def set_emulated_media(self, *, media=None, features=None): |
| 197 |
if self.browser not in {"chrome", "edge"}: |
| 198 |
self.skipTest( |
| 199 |
"Emulation.setEmulatedMedia is only supported on Chromium and " |
| 200 |
"Chrome-based browsers. See https://chromedevtools.github.io/devtools-" |
| 201 |
"protocol/1-3/Emulation/#method-setEmulatedMedia for more details." |
| 202 |
) |
| 203 |
params = {} |
| 204 |
if media is not None: |
| 205 |
params["media"] = media |
| 206 |
if features is not None: |
| 207 |
params["features"] = features |
| 208 |
|
| 209 |
# Not using .execute_cdp_cmd() as it isn't supported by the remote web driver |
| 210 |
# when using --selenium-hub. |
| 211 |
self.selenium.execute( |
| 212 |
driver_command="executeCdpCommand", |
| 213 |
params={"cmd": "Emulation.setEmulatedMedia", "params": params}, |
| 214 |
) |
| 215 |
|
| 216 |
@contextmanager |
| 217 |
def high_contrast(self): |
| 218 |
self.set_emulated_media(features=[{"name": "forced-colors", "value": "active"}]) |
| 219 |
with self.desktop_size(): |
| 220 |
try: |
| 221 |
yield |
| 222 |
finally: |
| 223 |
self.set_emulated_media( |
| 224 |
features=[{"name": "forced-colors", "value": "none"}] |
| 225 |
) |
| 226 |
|
| 227 |
def take_screenshot(self, name): |
| 228 |
if not self.screenshots: |
| 229 |
return |
| 230 |
test = getattr(self, self._testMethodName) |
| 231 |
filename = f"{test._screenshot_name}--{name}--{test._screenshot_case}.png" |
| 232 |
path = Path.cwd() / "screenshots" / filename |
| 233 |
path.parent.mkdir(exist_ok=True, parents=True) |
| 234 |
self.selenium.save_screenshot(path) |
| 235 |
|
| 236 |
@classmethod |
| 237 |
def _quit_selenium(cls): |
| 238 |
# quit() the WebDriver before attempting to terminate and join the |
| 239 |
# single-threaded LiveServerThread to avoid a dead lock if the browser |
| 240 |
# kept a connection alive. |
| 241 |
if hasattr(cls, "selenium"): |
| 242 |
cls.selenium.quit() |
| 243 |
|
| 244 |
@contextmanager |
| 245 |
def disable_implicit_wait(self): |
| 246 |
"""Disable the default implicit wait.""" |
| 247 |
self.selenium.implicitly_wait(0) |
| 248 |
try: |
| 249 |
yield |
| 250 |
finally: |
| 251 |
self.selenium.implicitly_wait(self.implicit_wait) |
| 252 |
|
| 253 |
|
| 254 |
def screenshot_cases(method_names): |
| 255 |
if isinstance(method_names, str): |
| 256 |
method_names = method_names.split(",") |
| 257 |
|
| 258 |
def wrapper(func): |
| 259 |
func._screenshot_cases = method_names |
| 260 |
setattr(func, "tags", {"screenshot"}.union(getattr(func, "tags", set()))) |
| 261 |
return func |
| 262 |
|
| 263 |
return wrapper |