### Development Environment Setup and Testing Source: https://github.com/telefonica/toolium/blob/master/README.rst Commands for contributors to clone the repository, install development dependencies, lint code using Ruff, and execute unit tests. ```console git clone git@github.com:/toolium.git cd toolium pip install -r requirements.txt pip install -r requirements_dev.txt ruff check --fix . ruff format . python -m pytest ``` -------------------------------- ### Install and Setup Toolium Template Source: https://github.com/telefonica/toolium/blob/master/README.rst Commands to clone the Toolium template repository and install necessary project dependencies for starting a new testing project. ```console git clone git@github.com:Telefonica/toolium-template.git cd toolium-template pip install -r requirements.txt ``` -------------------------------- ### Run Toolium Examples Source: https://github.com/telefonica/toolium/blob/master/README.rst Commands to clone the examples repository and set up the environment to run provided test scenarios for web, Android, and iOS. ```console git clone git@github.com:Telefonica/toolium-examples.git cd toolium-examples pip install -r requirements.txt ``` -------------------------------- ### Install Toolium Source: https://github.com/telefonica/toolium/blob/master/docs/index.md Installs the latest version of Toolium from PyPi. It is recommended to use a virtual environment for installation. ```bash pip install toolium ``` -------------------------------- ### Install and Configure AI Dependencies Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Provides the command-line instructions to install Toolium AI dependencies and configure necessary environment variables for API access. ```bash pip install toolium[ai] python -m spacy download en_core_web_sm export OPENAI_API_KEY= ``` -------------------------------- ### Install Toolium Dependencies Source: https://context7.com/telefonica/toolium/llms.txt Commands to install the base Toolium library and optional components like Playwright support, AI utilities, or development tools. ```bash pip install toolium pip install toolium[playwright] pip install toolium[ai] pip install toolium[dev] ``` -------------------------------- ### Configure Firefox Extensions and Arguments Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Installs Firefox extensions via file paths and sets command-line arguments like private browsing mode. ```ini [Driver] type: firefox [FirefoxExtensions] firebug: resources/firebug-3.0.0-beta.3.xpi [FirefoxArguments] -private: ``` -------------------------------- ### Configure Visual Baseline Directory Source: https://github.com/telefonica/toolium/blob/master/docs/visual_testing.md Demonstrates how to configure the baseline directory for visual testing. This can be done via environment variables, or within the 'before_all' method for behave tests, and the 'setUp' method for nose2 tests. ```bash $ export TOOLIUM_VISUAL_BASELINE_DIRECTORY=resources/baseline ``` ```python from toolium.behave.environment import before_all as toolium_before_all from toolium.config_files import ConfigFiles def before_all(context): context.config_files = ConfigFiles() context.config_files.set_visual_baseline_directory('resources/baseline') toolium_before_all(context) ``` ```python from toolium import test_cases class SeleniumTestCase(test_cases.SeleniumTestCase): def setUp(self): self.config_files.set_visual_baseline_directory('resources/baseline') super(SeleniumTestCase, self).setUp() ``` -------------------------------- ### Install Toolium with AI Support Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Command to install the Toolium library with AI capabilities. The '[ai]' extra ensures that all necessary dependencies for AI features are included. ```bash pip install toolium[ai] ``` -------------------------------- ### Configure Toolium Drivers Source: https://context7.com/telefonica/toolium/llms.txt Examples of configuring browser, mobile, and remote grid drivers using the properties.cfg file format. ```ini [Driver] type: chrome window_width: 1920 window_height: 1080 [ChromePreferences] download.default_directory: /tmp/downloads [ChromeArguments] headless: disable-gpu: [Capabilities] pageLoadStrategy: eager ``` ```ini [Driver] type: ios [Capabilities] platformName: iOS [AppiumCapabilities] automationName: XCUITest deviceName: iPhone 14 platformVersion: 16.1 app: http://server_url/TestApp.zip ``` ```ini [Driver] type: chrome [Server] enabled: true ssl: false host: selenium-grid.example.com port: 4444 username: griduser password: gridpassword video_enabled: true logs_enabled: true [Capabilities] browserVersion: 120 platformName: linux ``` -------------------------------- ### INI: Selenium Grid Configuration for Toolium Source: https://context7.com/telefonica/toolium/llms.txt Configuration file example for setting up remote execution on a Selenium Grid server using Toolium. It specifies driver type, server details, and desired capabilities. ```ini # conf/properties.cfg - Selenium Grid configuration [Driver] type: chrome [Server] enabled: true ssl: false host: selenium-hub.example.com port: 4444 username: griduser password: gridpassword video_enabled: true logs_enabled: true log_types: browser,driver base_path: /wd/hub [Capabilities] browserVersion: 120 platformName: linux se:recordVideo: true ``` -------------------------------- ### Install Playwright Dependencies for Toolium Source: https://github.com/telefonica/toolium/blob/master/docs/playwright_configuration.md This command installs the necessary Playwright dependencies for Toolium. It is a prerequisite for running Playwright-based tests. ```bash pip install toolium[playwright] ``` -------------------------------- ### Python: Accessing Remote Server Info in Toolium Tests Source: https://context7.com/telefonica/toolium/llms.txt Example demonstrating how to access information about the remote execution environment within Toolium test cases. It shows how to retrieve the server type, node details, and check if video recording is enabled. ```python # Accessing remote server info in tests from toolium.test_cases import SeleniumTestCase class TestRemote(SeleniumTestCase): def test_remote_info(self): """Access remote server information""" # Get remote node details server_type, node = self.utils.get_remote_node() print(f"Server type: {server_type}") # local, grid, ggr, selenoid print(f"Remote node: {node}") # Check if video recording is enabled video_enabled = self.utils.is_remote_video_enabled(server_type, node) print(f"Video enabled: {video_enabled}") ``` -------------------------------- ### INI: Selenoid Configuration for Toolium Source: https://context7.com/telefonica/toolium/llms.txt Configuration file example for setting up remote execution on a Selenoid server using Toolium. It includes driver type, server host/port, and Selenoid-specific options for VNC and video recording. ```ini # conf/properties.cfg - Selenoid configuration [Driver] type: chrome [Server] enabled: true host: selenoid.example.com port: 4444 video_enabled: true [Capabilities] browserVersion: 120.0 selenoid:options: {"enableVNC": true, "enableVideo": true, "videoName": "test.mp4"} ``` -------------------------------- ### Install Chrome Extensions Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Adds Chrome extensions by specifying the file path to the .crx file in the [ChromeExtensions] section. ```ini [Driver] type: chrome [ChromeExtensions] firebug: resources/firebug-lite.crx ``` -------------------------------- ### Set Toolium Configuration Environment via System Property Source: https://github.com/telefonica/toolium/blob/master/docs/driver_configuration.md Select different Toolium configuration files based on the environment by setting the TOOLIUM_CONFIG_ENVIRONMENT system property. This example shows how to load configurations for an 'android' environment. ```console $ TOOLIUM_CONFIG_ENVIRONMENT=android python -m nose2 web/tests/test_web.py ``` ```console $ TOOLIUM_CONFIG_ENVIRONMENT=android python -m pytest web_pytest/tests/test_web_pytest.py ``` ```bash $ behave -D TOOLIUM_CONFIG_ENVIRONMENT=android ``` -------------------------------- ### Initialize PageElements Collection Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.pageelements.md Example of how to define a collection of page elements using the PageElements class or its specialized subclasses. This allows for bulk interaction with elements identified by a shared locator. ```python from toolium.pageelements import PageElements, InputTexts # Using the base class all_elements = PageElements(by='id', value='my-element-id') # Using a specialized subclass text_inputs = InputTexts(by='css selector', value='.input-field') ``` -------------------------------- ### Web Application Login Tests with Pytest Fixtures Source: https://context7.com/telefonica/toolium/llms.txt These Python examples showcase web application testing using Toolium with Pytest fixtures. They cover successful login, invalid credentials handling, and demonstrating element wait methods. ```python # conftest.py import pytest from toolium.pytest_fixtures import driver_wrapper, session_driver_fixture, module_driver_fixture # Fixtures are auto-registered when importing from toolium.pytest_fixtures # test_web.py import pytest from selenium.webdriver.common.by import By from project.pageobjects.login import LoginPageObject from project.pageobjects.dashboard import DashboardPageObject class TestWebApplication: """Web application tests using pytest with Toolium""" def test_successful_login(self, driver_wrapper): """Test user can login successfully""" # driver_wrapper fixture provides configured driver driver_wrapper.driver.get('https://example.com/login') login_page = LoginPageObject() login_page.login('valid_user', 'valid_password') dashboard = DashboardPageObject() assert dashboard.welcome_text.is_visible() def test_invalid_credentials(self, driver_wrapper): """Test error message on invalid login""" driver_wrapper.driver.get('https://example.com/login') login_page = LoginPageObject() login_page.login('invalid_user', 'wrong_password') assert login_page.error_message.is_visible() assert 'Invalid credentials' in login_page.error_message.text def test_page_element_waits(self, driver_wrapper): """Demonstrate wait methods""" driver_wrapper.driver.get('https://example.com') # Wait for element to be visible with custom timeout element = PageElement(By.ID, 'dynamic-content') element.wait_until_visible(timeout=15) # Wait for element to be clickable button = Button(By.ID, 'async-button') button.wait_until_clickable(timeout=10) button.click() # Run tests # pytest tests/ -v # TOOLIUM_CONFIG_ENVIRONMENT=staging pytest tests/ ``` -------------------------------- ### Initialize Toolium Environment in Behave Source: https://github.com/telefonica/toolium/blob/master/docs/bdd_integration.md This Python code demonstrates how to initialize Toolium's environment methods within Behave's environment.py file. It ensures that Toolium's setup procedures are called before and after Behave test execution, making Toolium's functionalities available in the Behave context. ```python from toolium.behave.environment import ( before_all as toolium_before_all, before_feature as toolium_before_feature, before_scenario as toolium_before_scenario, after_scenario as toolium_after_scenario, after_feature as toolium_after_feature, after_all as toolium_after_all ) def before_all(context): toolium_before_all(context) def before_feature(context, feature): toolium_before_feature(context, feature) def before_scenario(context, scenario): toolium_before_scenario(context, scenario) def after_scenario(context, scenario): toolium_after_scenario(context, scenario) def after_feature(context, feature): toolium_after_feature(context, feature) def after_all(context): toolium_after_all(context) ``` -------------------------------- ### GET /config/option Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Retrieves a specific configuration option from a given section, with support for fallbacks and default values. ```APIDOC ## GET /config/option ### Description Retrieves the value of a configuration option. Supports optional fallbacks if the section or option is missing. ### Method GET ### Parameters #### Query Parameters - **section** (string) - Required - The configuration section name. - **option** (string) - Required - The configuration option key. - **default** (any) - Optional - The value to return if the option is not found. ### Response #### Success Response (200) - **value** (any) - The configuration value or the provided default. ### Response Example { "value": "chrome" } ``` -------------------------------- ### Web and Mobile Tests with unittest Source: https://context7.com/telefonica/toolium/llms.txt This Python code demonstrates web and mobile testing using Toolium's unittest base classes. It includes examples for SeleniumTestCase, AppiumTestCase, and BasicTestCase for API testing. ```python from toolium.test_cases import SeleniumTestCase, AppiumTestCase, BasicTestCase from project.pageobjects.login import LoginPageObject from selenium.webdriver.common.by import By class TestSeleniumWeb(SeleniumTestCase): """Selenium web tests inheriting from SeleniumTestCase""" def test_login_page_loads(self): """Test login page loads correctly""" # self.driver is automatically available self.driver.get('https://example.com/login') login_page = LoginPageObject() assert login_page.username.is_visible() assert login_page.password.is_visible() def test_form_submission(self): """Test form can be submitted""" self.driver.get('https://example.com/login') login_page = LoginPageObject() login_page.login('user@example.com', 'securepass') # self.utils provides helper methods self.utils.wait_until_element_visible((By.CLASS_NAME, 'dashboard')) class TestAppiumMobile(AppiumTestCase): """Appium mobile tests inheriting from AppiumTestCase""" def test_app_launches(self): """Test mobile app launches successfully""" # self.driver is Appium driver # self.app_strings contains app string resources welcome_text = self.driver.find_element(By.ID, 'welcome') assert welcome_text.is_displayed() class TestAPIOnly(BasicTestCase): """API tests that don't need a driver""" def test_api_endpoint(self): """Test API without browser/app driver""" # No driver is started for BasicTestCase import requests response = requests.get('https://api.example.com/health') assert response.status_code == 200 # Run with unittest # python -m pytest tests/test_selenium.py ``` -------------------------------- ### Toolium Driver Management and Configuration Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Provides methods for managing WebDriver instances, configuring directories for logs, screenshots, and videos, and connecting to default drivers. It also includes utilities for getting configured values and checking the status of driver wrappers. ```python from toolium import driver_wrapper # Example usage: # driver_wrapper.close_drivers(scope='function', test_name='my_test') # driver_wrapper.configure_common_directories(tc_config_files=['config.yaml']) # driver_wrapper.connect_default_driver_wrapper(config_files=['driver_config.yaml']) # default_driver = driver_wrapper.get_default_wrapper() # configured_value = driver_wrapper.get_configured_value('my_prop', 'specific_value', 'default_value') # is_pool_empty = driver_wrapper.is_empty() # driver_wrapper.remove_drivers() # driver_wrapper.stop_drivers() ``` -------------------------------- ### Configure Dynamic Environment Actions in Behave Source: https://github.com/telefonica/toolium/blob/master/docs/bdd_integration.md This example demonstrates how to define dynamic environment hooks in a Behave feature file. It includes the @reuse_driver decorator, which is mandatory for these hooks to function correctly, and shows how to use tables and internal steps within these blocks. ```Gherkin @reuse_driver Feature: Tests with the dynamic environment As a behave operator using multiples scenarios I want to append actions before the feature, before each scenario, after each scenario and after the feature. Actions Before the Feature: Given wait 3 seconds And waitrty 3 seconds And wait 3 seconds And step with a table | parameter | value | | sub_fields_1 | sub_value 1 | | sub_fields_2 | sub_value 2 | Actions Before each Scenario: Given the user navigates to the "www.google.es" url When the user logs in with username and password And wait 1 seconds And wait 1 seconds Actions After each Scenario: Then wait 2 seconds And wait 2 seconds Actions After the Feature: Then wait 4 seconds And step with another step executed dynamically And wait 4 seconds ``` -------------------------------- ### Execute Tests with Environment Configurations Source: https://context7.com/telefonica/toolium/llms.txt Demonstrates how to run tests using different configurations via environment variables or CLI arguments. ```python # TOOLIUM_CONFIG_ENVIRONMENT=android python -m pytest tests/ # behave -D Driver_type=firefox ``` -------------------------------- ### Configure Basic Browser and Window Settings Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Sets the browser type and custom window dimensions in the properties.cfg file. ```ini [Driver] type: firefox window_width: 1024 window_height: 768 ``` -------------------------------- ### Configure Element Hierarchy and Shadowroot Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md Illustrates how to define parent containers for elements and configure shadowroot selectors. ```python form = PageElement(By.XPATH, "//form[@id='login']") login_button = Button(By.XPATH, "./button", parent=form) # Shadowroot example login_button = Button(By.CSS_SELECTOR, "css_selector", shadowroot="shadowroot_css_selector") ``` -------------------------------- ### Behave Lifecycle Hooks Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.behave.md Methods for managing the setup and teardown of test features and scenarios. ```APIDOC ## Lifecycle Hooks ### Description These methods are used within the behave environment.py file to manage the lifecycle of test execution. ### Methods - **before_all(context)**: Initialization before test execution. - **after_all(context)**: Cleanup after all features finish. - **before_feature(context, feature)**: Feature initialization. - **after_feature(context, feature)**: Cleanup after each feature. - **before_scenario(context, scenario)**: Scenario initialization. - **after_scenario(context, scenario)**: Cleanup after each scenario. ### Parameters - **context** (object) - Required - The behave context object. - **feature/scenario** (object) - Required - The current feature or scenario being processed. ``` -------------------------------- ### GET /utils/poeditor/search_terms Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.utils.md Retrieves and saves POEditor terms for a specified language into the test context. ```APIDOC ## GET /utils/poeditor/search_terms ### Description Saves POEditor terms for a given existing language in the project to the context.poeditor_terms variable. ### Method GET ### Endpoint toolium.utils.poeditor.search_terms_with_string ### Parameters #### Path Parameters - **lang** (string) - Required - A valid language code existing in the POEditor project. ### Response #### Success Response (200) - **context.poeditor_terms** (object) - The retrieved terms saved to the test context. ``` -------------------------------- ### Creating and Executing AI ReAct Agents Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Shows how to initialize a ReAct agent using Toolium's ai_agent module and execute it against a specific tool method. It requires defining a system message, the tool function, and the AI provider configuration. ```python from toolium.utils.ai_utils.ai_agent import create_react_agent, execute_agent # Create a ReAct agent with a system message and a tool method system_message = "You are an assistant that helps users find TV content based on their preferences." tool_method = tv_recommendations provider = 'azure' model_name = 'gpt-4o-mini' agent = create_react_agent(system_message, tool_method=tool_method, provider=provider, model_name=model_name) # Execute the agent and log all interactions final_state = execute_agent(agent) ``` -------------------------------- ### Configure Toolium Environment Source: https://context7.com/telefonica/toolium/llms.txt Initializes the Toolium environment by setting up configuration files and defining the visual baseline directory for automated testing. ```python from toolium.behave.environment import before_all as toolium_before_all from toolium.config_files import ConfigFiles def before_all(context): context.config_files = ConfigFiles() context.config_files.set_visual_baseline_directory('resources/visual_baseline') toolium_before_all(context) ``` -------------------------------- ### Interact with Page Elements Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md Shows how to get or set values for page elements and access the underlying web element for advanced interactions. ```python username = InputText(By.ID, 'username') input_value = username.text username.text = 'username' # Accessing underlying web element enabled = username.web_element.is_enabled() ``` -------------------------------- ### Configure Mobile Webview Context Selection Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md Demonstrates how to define a page element within a webview context using custom selection callbacks and arguments for mobile automation. ```python login_button = Button(By.XPATH, "//*[@data-qsysid='subscription-counters']/div/div/", webview=True, webview_context_selection_callback = webview_context_selector_per_url, webview_csc_args = [driver_wrapper, WebviewConfigHelper.get_helper().account]) ``` -------------------------------- ### Driver Configuration and Connection Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Methods for initializing the driver environment, configuring logging, properties, and establishing connections to Selenium or Playwright servers. ```APIDOC ## POST /configure ### Description Configures the initial selenium instance using logging and properties files for Selenium or Appium tests. ### Method POST ### Endpoint /configure ### Parameters #### Request Body - **tc_config_files** (list) - Required - Test case specific config files - **is_selenium_test** (boolean) - Optional - True if test is a selenium or appium test case - **behave_properties** (dict) - Optional - Behave user data properties ## POST /connect ### Description Sets up the driver and connects to the server. ### Method POST ### Endpoint /connect ### Response #### Success Response (200) - **driver** (object) - Returns the initialized selenium or playwright driver instance ``` -------------------------------- ### File Download Utilities Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.utils.md Utilities for managing file downloads, including getting base directories, file paths, and retrieving remote files. ```APIDOC ## GET /toolium/utils/download_files/get_download_directory_base ### Description Get base folder to download files. ### Method GET ### Endpoint /toolium/utils/download_files/get_download_directory_base ### Parameters #### Query Parameters - **context** (object) - Required - behave context ### Response #### Success Response (200) - **base_folder** (string) - The base folder path for downloads. ## GET /toolium/utils/download_files/get_downloaded_file_path ### Description Get local downloaded file path and retrieve remote file if necessary. ### Method GET ### Endpoint /toolium/utils/download_files/get_downloaded_file_path ### Parameters #### Query Parameters - **context** (object) - Required - behave context - **file_name** (string) - Required - The name of the downloaded file. ### Response #### Success Response (200) - **local_file_path** (string) - The local path to the downloaded file. ## GET /toolium/utils/download_files/get_downloaded_files_list ### Description Get a list of downloaded files. ### Method GET ### Endpoint /toolium/utils/download_files/get_downloaded_files_list ### Parameters #### Query Parameters - **context** (object) - Required - behave context ### Response #### Success Response (200) - **files_list** (array) - A list of downloaded file names. ## POST /toolium/utils/download_files/retrieve_remote_downloaded_file ### Description Retrieves a file downloaded in a remote node and saves it in the output folder. ### Method POST ### Endpoint /toolium/utils/download_files/retrieve_remote_downloaded_file ### Parameters #### Request Body - **context** (object) - Required - behave context - **filename** (string) - Required - The name of the downloaded file on the remote node. - **destination_filename** (string) - Optional - The desired local destination name for the file. ### Response #### Success Response (200) - **destination_file_path** (string) - The path where the file was saved locally. ## POST /toolium/utils/download_files/wait_until_remote_file_downloaded ### Description Wait until a remote file is downloaded. ### Method POST ### Endpoint /toolium/utils/download_files/wait_until_remote_file_downloaded ### Parameters #### Request Body - **context** (object) - Required - behave context - **filename** (string) - Required - The name of the file to wait for. - **wait_sec** (integer) - Optional - The time to wait in seconds (default is 15). ### Response #### Success Response (200) - **status** (string) - Indicates if the file was successfully downloaded within the waiting period. ``` -------------------------------- ### Defining a Toolium Page Element Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.pageelements.md Example of how to instantiate a basic Toolium page element class. These classes typically require a locator strategy and value to identify elements in the DOM. ```python from toolium.pageelements import InputText # Define an input text element using a CSS selector username_field = InputText(by='css', value='#username') # Perform actions on the element username_field.set_focus() username_field.clear() ``` -------------------------------- ### Modify Toolium Configuration Programmatically (Python) Source: https://github.com/telefonica/toolium/blob/master/docs/driver_configuration_modification.md Configuration can be modified programmatically before the driver starts by monkey patching the finalize_properties_configuration method of DriverWrapper. This allows for dynamic configuration based on application logic or other conditions. ```python from toolium.driver_wrapper import DriverWrapper def finalize_properties_configuration(self): if self.config.getboolean_optional('Server', 'enabled'): self.config.set('Capabilities', 'selenoid:options', "{'enableVideo': True}"): DriverWrapper.finalize_properties_configuration = finalize_properties_configuration ``` -------------------------------- ### Python: Toolium Driver Utilities for Web and Mobile Source: https://context7.com/telefonica/toolium/llms.txt Demonstrates various utility methods provided by Toolium for common testing operations such as waiting for elements, capturing screenshots, performing mobile gestures, and managing webview contexts. These utilities simplify interaction with web elements and mobile-specific features. ```python from toolium.test_cases import SeleniumTestCase from toolium.pageelements import PageElement from selenium.webdriver.common.by import By class TestUtilities(SeleniumTestCase): def test_wait_utilities(self): """Demonstrate wait utilities""" self.driver.get('https://example.com') # Wait for element to be visible self.utils.wait_until_element_visible((By.ID, 'content'), timeout=10) # Wait for element to be clickable self.utils.wait_until_element_clickable((By.ID, 'button'), timeout=10) # Wait for element to not be visible self.utils.wait_until_element_not_visible((By.CLASS_NAME, 'loading')) def test_screenshot_capture(self): """Capture screenshots manually""" self.driver.get('https://example.com') # Capture screenshot with custom name screenshot_path = self.utils.capture_screenshot('homepage_test') print(f"Screenshot saved: {screenshot_path}") def test_mobile_gestures(self): """Mobile swipe gestures (Appium only)""" element = PageElement(By.ID, 'scrollable-content') # Swipe on element self.utils.swipe(element, x=0, y=-500, duration=500) # Swipe up self.utils.swipe(element, x=500, y=0, duration=300) # Swipe right def test_element_interactions(self): """Additional element utilities""" element = PageElement(By.ID, 'target') # Get element center coordinates center = self.utils.get_center(element) print(f"Element center: {center}") # Focus on element self.utils.focus_element(element.web_element) # Focus and click self.utils.focus_element(element.web_element, click=True) def test_webview_context(self): """Switch between native and webview contexts (mobile)""" # Get first webview context webview = self.utils.get_first_webview_context() # Switch to webview self.utils.switch_to_first_webview_context() # Convert web coords to native coords native_coords = self.utils.get_native_coords({'x': 100, 'y': 200}) ``` -------------------------------- ### Initialize Additional Driver Instances Source: https://github.com/telefonica/toolium/blob/master/docs/multiple_drivers.md Demonstrates how to create a secondary driver instance using the DriverWrapper class. This allows tests to manage multiple browser or device sessions independently. ```python second_wrapper = DriverWrapper() second_wrapper.connect() ``` -------------------------------- ### Configure Environment for Test Execution Source: https://github.com/telefonica/toolium/blob/master/CHANGELOG.rst Demonstrates how to set the 'Config_environment' system property to select specific configuration files (e.g., android-properties.cfg) when running tests with nose2 or behave. ```console $ Config_environment=android nose2 web/tests/test_web.py ``` ```console $ behave -D Config_environment=android ``` -------------------------------- ### Use @accuracy Tag in Behave Scenarios Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Example of applying the @accuracy tag in a Behave scenario to enforce specific accuracy levels and execution counts for AI-generated content. The tag format is @accuracy__. ```gherkin @accuracy_80_10 Scenario: Validate AI-generated response accuracy Given the AI model generates a response When the user sends a message Then the AI response should be accurate ``` -------------------------------- ### Initialize Elements for Concurrency Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md Demonstrates defining page elements as instance attributes using init_page_elements to support multiple simultaneous driver instances. ```python from toolium.pageobjects.page_object import PageObject from toolium.pageelements import InputText, Button class LoginPageObject(PageObject): def init_page_elements(self): self.username = InputText(By.ID, 'username') self.password = InputText(By.ID, 'password') self.login_button = Button(By.XPATH, "//form[@id='login']/button") def login(self, username, password): self.username.text = username self.password.text = password self.login_button.click() ``` -------------------------------- ### Configure Chrome Options and Binary Path Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Sets additional Chrome options and specifies the custom binary location for the Chrome executable. ```ini [Driver] type: chrome [Chrome] options: {'excludeSwitches': ['enable-automation'], 'perfLoggingPrefs': {'enableNetwork': True}} [Driver] type: chrome [Chrome] binary: /usr/local/chrome_beta/chrome ``` -------------------------------- ### ExtendedConfigParser: Get Optional Configuration Value (Python) Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Retrieves an optional configuration value from a given section. If the section or option is not found, it returns a specified default value. This is useful for accessing configuration settings that may not always be present. ```python def get_optional(self, section, option, default=None): """Get an option value for a given section If the section or the option are not found, the default value is returned :param section: config section :param option: config option :param default: default value :return: config value """ pass ``` -------------------------------- ### Toolium Configuration and Context Mapping Source: https://context7.com/telefonica/toolium/llms.txt This section details how Toolium maps parameters from various sources, including environment variables, project configuration files, Toolium-specific configurations, behave context storage, and external files. It also covers base64 encoding and localized string retrieval. ```python map_param('[ENV:HOME]') # Value of HOME environment variable map_param('[CONF:database.host]') # Value from project config map_param('[TOOLIUM:Driver_type]') # Value from toolium config map_param('[CONTEXT:user_id]') # Value from behave context storage map_param('[FILE:data/test.json]') # Content of file map_param('[BASE64:images/logo.png]') # Base64 encoded file content map_param('[LANG:buttons.submit]') # Localized string from language file map_param('[POE:welcome_message]') # Translation from POEditor ``` -------------------------------- ### ExtendedConfigParser: Get Optional Boolean Configuration Value (Python) Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Retrieves an optional boolean configuration value from a given section. If the section or option is not found, it returns a specified default boolean value. This method is specifically designed for boolean settings. ```python def getboolean_optional(self, section, option, default=False): """Get an optional boolean value for a given section If the section or the option are not found, the default value is returned :param section: config section :param option: config option :param default: default value :return: boolean config value """ pass ``` -------------------------------- ### Execute Behave Tests via CLI Source: https://context7.com/telefonica/toolium/llms.txt Common command-line instructions for running Behave tests, including passing environment variables and driver configurations. ```bash behave features/login.feature behave -D Driver_type=firefox features/ behave -D TOOLIUM_CONFIG_ENVIRONMENT=staging features/ ``` -------------------------------- ### Configure Firefox Profile and Binary Path Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Specifies a custom Firefox profile directory and the path to the Firefox binary executable. ```ini [Driver] type: firefox [Firefox] profile: resources/firefox-profile.default binary: /usr/local/firefox_beta/firefox ``` -------------------------------- ### LLM Answer Evaluation with Structured Pydantic Response Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Shows how to evaluate an LLM answer using Azure OpenAI and receive the response structured as a Pydantic model. This example uses a `SimilarityEvaluation` model to ensure the output includes similarity score and explanation. ```python from pydantic import BaseModel, Field from toolium.utils.ai_utils.evaluate_answer import get_answer_evaluation_with_azure_openai class SimilarityEvaluation(BaseModel): """Model for text similarity evaluation response""" similarity: float = Field(description='Similarity score between 0.0 and 1.0', ge=0.0, le=1.0) explanation: str = Field(description='Brief justification for the similarity score') llm_answer = "Paris is the capital of France and has a population of over 2 million people." reference_answer = "The capital of France is Paris." question = "What is the capital of France?" similarity, response = get_answer_evaluation_with_azure_openai( llm_answer=llm_answer, reference_answer=reference_answer, question=question, model_name='gpt-4o', response_format=SimilarityEvaluation ) print(f"Similarity score: {similarity}") print(f"Explanation: {response.explanation}") ``` -------------------------------- ### Configure Toolium Environment via Behave Source: https://github.com/telefonica/toolium/blob/master/CHANGELOG.rst Demonstrates how to pass configuration properties to Toolium when running tests through the Behave command-line interface. ```console $ behave -D env=android $ behave -D Driver_type=chrome ``` -------------------------------- ### Advanced LLM Answer Evaluation with Custom Criteria Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md This example demonstrates advanced LLM answer evaluation using Azure OpenAI with a custom Pydantic model (`AnswerEvaluation`) that includes multiple criteria: similarity, accuracy, completeness, and relevance. It allows for a more comprehensive assessment of the LLM's response. ```python from pydantic import BaseModel, Field from toolium.utils.ai_utils.evaluate_answer import get_answer_evaluation_with_azure_openai class AnswerEvaluation(BaseModel): """Comprehensive evaluation model""" similarity: float = Field(description='Similarity score between 0.0 and 1.0', ge=0.0, le=1.0) explanation: str = Field(description='Detailed evaluation feedback') accuracy: float = Field(description='Factual correctness score 1-5') completeness: float = Field(description='Information completeness score 1-5') relevance: float = Field(description='Relevance to question score 1-5') llm_answer = "Paris is the capital of France and has a population of over 2 million people." reference_answer = "The capital of France is Paris." question = "What is the capital of France?" similarity, response = get_answer_evaluation_with_azure_openai( llm_answer=llm_answer, reference_answer=reference_answer, question=question, model_name='gpt-4o', response_format=AnswerEvaluation ) print(f"Similarity: {similarity}") print(f"Accuracy: {response.accuracy}/5") print(f"Completeness: {response.completeness}/5") print(f"Relevance: {response.relevance}/5") ``` -------------------------------- ### Configure AI Utilities in properties.cfg Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Shows the configuration structure for AI utilities in the properties.cfg file, allowing users to define models and methods for text analysis. ```ini [AI] text_similarity_method: openai spacy_model: en_core_web_lg sentence_transformers_model: all-MiniLM-L6-v2 openai_model: gpt-3.5-turbo ``` -------------------------------- ### BasicTestCase Source: https://github.com/telefonica/toolium/blob/master/docs/index.md A basic test case class with utilities for configuration, driver management, and method name retrieval. ```APIDOC ## BasicTestCase ### Description Base class for basic test cases. ### Attributes - **config_files** (list): List of configuration files. - **driver_wrapper** (DriverWrapper): Wrapper for the WebDriver. ### Methods - **get_method_name()**: Returns the name of the current test method. - **get_subclass_name()**: Returns the name of the subclass. - **get_subclassmethod_name()**: Returns the name of the current subclassmethod. - **setUp()**: Sets up the test environment. - **tearDown()**: Tears down the test environment. - **tearDownClass()**: Tears down the test class. ``` -------------------------------- ### PageElement Base Class - Toolium Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.pageelements.md The base PageElement class in Toolium provides fundamental methods for interacting with web and mobile elements. It includes functionalities for asserting screenshots, getting attributes, checking presence and visibility, scrolling, setting focus, and waiting for elements to become visible or clickable. It also manages element locators and parent-child relationships. ```python class PageElement: def __init__(self, by, value, parent=None, order=None, wait=False, shadowroot=None, webview=False, webview_context_selection_callback=None, webview_csc_args=None): pass def assert_screenshot(self, filename, threshold=0, exclude_elements=None, force=False): pass def get_attribute(self, name): pass def is_present(self): pass def is_visible(self): pass def parent_locator_str(self): pass def reset_object(self, driver_wrapper=None): pass def scroll_element_into_view(self): pass def set_focus(self): pass def wait_until_clickable(self, timeout=None): pass def wait_until_not_visible(self, timeout=None): pass def wait_until_visible(self, timeout=None): pass @property def web_element(self): pass ``` -------------------------------- ### DriverWrapper Configuration and Connection Source: https://github.com/telefonica/toolium/blob/master/docs/index.md Methods for configuring the driver environment and establishing connections to Selenium or Playwright drivers. ```APIDOC ## POST /DriverWrapper/configure ### Description Configures the driver environment settings, including logging, properties, and visual baseline parameters. ### Method POST ### Endpoint /DriverWrapper/configure ### Parameters #### Request Body - **config_properties** (dict) - Optional - Configuration properties for the driver session. ### Request Example { "config_properties": {"browser": "chrome", "remote": false} } ### Response #### Success Response (200) - **status** (string) - Configuration success status. ## POST /DriverWrapper/connect ### Description Initializes the connection to the underlying driver (Selenium or Playwright) based on the current configuration. ### Method POST ### Endpoint /DriverWrapper/connect ### Parameters #### Request Body - **driver_type** (string) - Required - The type of driver to connect (selenium or playwright). ### Request Example { "driver_type": "playwright" } ### Response #### Success Response (200) - **session_id** (string) - The active session ID for the driver. ``` -------------------------------- ### Configure Browser Driver Paths Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Manually sets the executable path for various browser drivers in the [Driver] section of the properties.cfg file. ```ini [Driver] type: firefox gecko_driver_path: C:\Drivers\geckodriver.exe [Driver] type: chrome chrome_driver_path: C:\Drivers\chromedriver.exe [Driver] type: iexplore explorer_driver_path: C:\Drivers\IEDriverServer.exe [Driver] type: edge edge_driver_path: C:\Drivers\msedgedriver.exe [Driver] type: safari safari_driver_path: /usr/bin/safaridriver ``` -------------------------------- ### Configure Secondary Driver with Custom Settings Source: https://github.com/telefonica/toolium/blob/master/docs/multiple_drivers.md Shows how to override default configuration settings for a specific DriverWrapper instance before connecting. This is useful for running different driver types like Android and Firefox in the same test suite. ```python second_wrapper = DriverWrapper() second_wrapper.config.set('Driver', 'type', 'firefox') second_wrapper.connect() ``` -------------------------------- ### Execute Commands and Assign Drivers to Page Objects Source: https://github.com/telefonica/toolium/blob/master/docs/multiple_drivers.md Illustrates how to interact with the secondary driver instance directly or pass it to a PageObject constructor. When using custom drivers, page elements must be initialized within the init_page_elements method. ```python second_wrapper.driver.find_element(BY.XPATH, '//form') login_page = LoginPageObject(second_wrapper) class LoginPageObject(PageObject): def init_page_elements(self): self.username = InputText(By.ID, 'username') self.password = InputText(By.ID, 'password') ``` -------------------------------- ### Webview Element Configuration Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md This snippet demonstrates how to configure a page element to be within a webview context, including custom callback functions for selecting the webview context. ```APIDOC ## Webview Element Configuration ### Description Page elements can optionally be configured to exist within a webview context using the `webview` argument. This is particularly useful for mobile testing where switching to a webview is necessary to locate an element. The `automatic_context_selection` property must be enabled for this to function. If a custom selection logic is needed beyond the default Android or iOS behavior, `webview_context_selection_callback` and `webview_csc_args` can be provided. ### Parameters - **webview** (boolean) - Optional - Indicates if the page element is in a webview context. Defaults to False. - **webview_context_selection_callback** (function) - Optional - A method to select the desired webview context when `automatic_context_selection` is enabled. Must return a tuple (context, window_handle) for Android, and a context for iOS. - **webview_csc_args** (list) - Optional - Arguments list for the `webview_context_selection_callback`. ### Request Example ```python login_button = Button(By.XPATH, "//*[@data-qsysid='subscription-counters']/div/div/", webview=True, webview_context_selection_callback = webview_context_selector_per_url, webview_csc_args = [driver_wrapper, WebviewConfigHelper.get_helper().account]) ``` ### Notes - Requires Appium version 1.17 or higher. - Default behavior for context selection varies between Android and iOS if no callback is provided. ``` -------------------------------- ### Define and Use a Page Object Source: https://github.com/telefonica/toolium/blob/master/docs/page_objects.md Demonstrates how to create a class inheriting from PageObject and define elements with locators, followed by a test implementation. ```python from toolium.pageobjects.page_object import PageObject from toolium.pageelements import InputText, Button class LoginPageObject(PageObject): username = InputText(By.ID, 'username') password = InputText(By.ID, 'password') login_button = Button(By.XPATH, "//form[@id='login']/button") def login(self, username, password): self.username.text = username self.password.text = password self.login_button.click() def test_login(self): LoginPageObject().login('user', 'pass') ``` -------------------------------- ### Configure Chrome Arguments Source: https://github.com/telefonica/toolium/blob/master/docs/browser_configuration.md Sets command-line arguments for Chrome, such as defining a custom user data directory. ```ini [Driver] type: chrome [ChromeArguments] user-data-dir: C:\Users\USERNAME\AppData\Local\Google\Chrome\User Data ``` -------------------------------- ### ConfigDriver - Create Driver Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Creates a Selenium WebDriver instance based on the provided configuration properties. ```APIDOC ## Create Driver ### Description Creates a selenium driver using specified config properties. ### Method N/A (This is a class method or constructor behavior) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **driver** (selenium.webdriver.remote.webdriver.WebDriver) - A new selenium driver instance. #### Response Example N/A ``` -------------------------------- ### Configure Selenoid Capabilities Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Configuration format for Selenoid integration within properties files. Defines mandatory server connection details and browser capabilities. ```ini [Capabilities] selenoid___options: {'enableVideo': True, 'enableVNC': True, 'enableLog': True} [Server] enabled: true host: selenoid.example.com port: 4444 username: user password: password ``` -------------------------------- ### Configure Toolium Environment via CLI Source: https://github.com/telefonica/toolium/blob/master/CHANGELOG.rst Demonstrates how to set the configuration environment for Behave tests using system properties. This replaces the deprecated 'Config_environment' property. ```console behave -D TOOLIUM_CONFIG_ENVIRONMENT=android ``` -------------------------------- ### ConfigFiles - Configuration Management Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.md Functions to set directories and filenames for configuration and output files. ```APIDOC ## ConfigFiles - Configuration Management ### Description Provides methods to configure the directories and filenames used by Toolium for configuration, logging, and visual baselines. ### Method N/A (These are likely static or class methods) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A (These methods typically return None or modify internal state) #### Response Example N/A ``` -------------------------------- ### Context and Configuration Mapping Source: https://github.com/telefonica/toolium/blob/master/docs/toolium.utils.md Utilities to resolve values from dictionaries or Behave context objects using dot notation. Supports nested property access and list filtering. ```python from toolium.utils import dataset # Resolve value from context value = dataset.get_value_from_context("last_request.result", context) # Map value from config dictionary config = {"services": {"vamps": {"user": "user@example.com"}}} email = dataset.map_json_param("services.vamps.user", config) ``` -------------------------------- ### Configuring AI Provider Settings Source: https://github.com/telefonica/toolium/blob/master/docs/ai_utils.md Defines the configuration structure for AI providers and models within the properties.cfg file. This allows setting global defaults for the AI testing framework. ```ini [AI] provider: azure openai_model: gpt-3.5-turbo ```