Source code for Karana.WebUI.selenium

# Copyright (c) 2024-2026 Karana Dynamics Pty Ltd. All rights reserved.
#
# NOTICE TO USER:
#
# This source code and/or documentation (the "Licensed Materials") is
# the confidential and proprietary information of Karana Dynamics Inc.
# Use of these Licensed Materials is governed by the terms and conditions
# of a separate software license agreement between Karana Dynamics and the
# Licensee ("License Agreement"). Unless expressly permitted under that
# agreement, any reproduction, modification, distribution, or disclosure
# of the Licensed Materials, in whole or in part, to any third party
# without the prior written consent of Karana Dynamics is strictly prohibited.
#
# THE LICENSED MATERIALS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
# KARANA DYNAMICS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, AND
# FITNESS FOR A PARTICULAR PURPOSE.
#
# IN NO EVENT SHALL KARANA DYNAMICS BE LIABLE FOR ANY DAMAGES WHATSOEVER,
# INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS, DATA, OR USE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, WHETHER IN CONTRACT, TORT,
# OR OTHERWISE ARISING OUT OF OR IN CONNECTION WITH THE LICENSED MATERIALS.
#
# U.S. Government End Users: The Licensed Materials are a "commercial item"
# as defined at 48 C.F.R. 2.101, and are provided to the U.S. Government
# only as a commercial end item under the terms of this license.
#
# Any use of the Licensed Materials in individual or commercial software must
# include, in the user documentation and internal source code comments,
# this Notice, Disclaimer, and U.S. Government Use Provision.

"""Functions to setup selenium for frontend testing."""

from platform import system
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver

__all__ = ["setup"]


def _setViewportSizeFirefox(driver, width, height):
    """Set Firefox viewport size.

    Firefox has some extra UI elements that make the viewport size different than the
    window size. This function accounts for that.

    Parameters
    ----------
    driver :
        the driver to set the size for.
    width : int
        desired width of the viewport size.
    height :
        desired height of the viewport size.
    """
    # initial guess
    driver.set_window_size(width, height)

    # measure current viewport
    inner_width = driver.execute_script("return window.innerWidth;")
    inner_height = driver.execute_script("return window.innerHeight;")

    # compute deltas
    delta_width = width - inner_width
    delta_height = height - inner_height

    # resize again to correct
    driver.set_window_size(width + delta_width, height + delta_height)


def _setViewportSizeChrome(driver, width, height):
    selenium_driver.execute_cdp_cmd(
        "Emulation.setDeviceMetricsOverride",
        {
            "width": width,
            "height": height,
            "deviceScaleFactor": 1,
            "mobile": False,
        },
    )


def _setupDriverLinux() -> WebDriver:
    from selenium.webdriver.chrome.options import Options

    options = Options()
    options.add_argument("--headless=new")
    options.add_argument("--no-sandbox")
    # Needed for WebGL to work in docker
    options.add_argument("--use-angle=swiftshader")
    # Records dev console messages for debugging
    options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
    selenium_driver = webdriver.Chrome(options=options)


def _setupDriverDarwin() -> WebDriver:
    # Need to use Firefox on MacOS
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.common.by import By

    options = Options()
    options.add_argument("--headless")
    options.set_preference("network.dns.native-is-localhost", True)
    selenium_driver = webdriver.Firefox(options=options)


[docs] def setup(url: str, width: int = 800, height: int = 600) -> WebDriver: """Create and setup a selenium WebDriver for frontend testing. Parameters ---------- url: str The url of the frontend to load. width: int Viewport width. Defaults to 800. height: int Viewport height. Defaults to 600. Returns ------- WebDriver The selenium driver. """ if system() == "Darwin": # Chrome was hanging when trying to run reg tests. I could not # figure out the exact reason why, but some likely explanations # are: When Selenium "hangs" on macOS, it is almost always stuck # in one of these during Chrome startup: # # 1. System proxy / network service initialization # 2. First-run Chrome profile creation # 3. Keychain / codesigning / quarantine check # 4. ChromeDriver waiting for DevTools socket that never # opens # # We verified some of these were definitive actual problems with # user forums, but didn't bother to check all of them. Switching # to firefox fixed the hang. driver = _setupDriverDarwin() # Needed for consistent canvas dimensions _setViewportSizeFirefox(driver, width, height) else: driver = _setupDriverLinux() # Without this we were getting inconsistent canvas dimensions # between native and docker _setViewportSizeChrome(driver, width, height) # Tell the driver to connect to the server driver.get(url) return driver