12 hours ago - edited 12 hours ago
UI Test Automation Framework Cookbook
Contents
2 UI Test Automation Framework. 2
2.1 Scenario specific config files. 2
2.2 Implementation files for each keyword. 4
2.2.1 PO object creation and initialization of constructor in keyword class. 4
2.2.1.1 Accessing keyword base class. 4
2.2.1.2 Create PO Object from keyword class. 5
2.2.2 Mandatory parameters for PO constructor. 5
2.2.3 Definition of constructor parameters for PO Object. 5
2.2.4 Getting reference to 'page' object. 5
2.2.6 Commonly used keyword base class functions. 7
2.2.7 Example keyword class. 7
2.3 Object Repository and PO files. 8
2.3.1 PageObject base class. 9
2.3.2 Why to extend PageObject base class?. 9
2.8 The test-data directory. 11
2.9 The test-hierarchy and test-specs. 12
2.13 Run Test from Command line. 13
2.14 Parallel test Execution. 13
2.15 Automation Framework Installation. 13
2.16 Developing and running an automation suite. 15
3. Quick Start Guide with Example
Syndigo has developed the UI automation framework using Playwright framework. This document provides details about how to utilize the framework. This Automation framework will be updated for every release if there are any changes and will be available for download in this article (ui-automation-playwright.zip).
The UI Test Automation framework contains the following components:
Playwright maintains a global config file which is ‘playwright.config.js’.
Each workbook is considered as a scenario file and for each scenario file, a config file should be created under config/scenarios directory. The config file name should be always 'config-<scenario_name>.js', where scenario_name is same as the workbook name.
Note: Users have the option to define local configuration under config/scenarios. Here override only the required settings from the global config.
A few other config parameters like email, password, incognitoMode, genAutoRandomValue etc. can be added as explained below.
All the other local config file parameters are used to override the Playwright global config, which is available in ‘playwright.config.js’ file.
Refer the below example for user defined config file that provides all the config parameters that can be used and information about them
module.exports =
{
/*----
If this is intended to include multiple specs, then each of the
parameters below will apply to all specs. However if these
parameters are defined in those spec config files, they will
override the below
-----*/
baseURL : '{{specify the url}}', //MANDATORY
viewport: { width: 900, height: 1200 }, //OPTIONAL
headless:true, //MANDATORY
screenshot:'only-on-failure', //OPTIONAL
actionTimeout:60000, //OPTIONAL
trace:'on-first-retry', //OPTIONAL
acceptDownloads:true, //OPTIONAL
video:'off', //OPTIONAL
// incognitoMode - set this to false to run browser in normal mode
// set this to true or do not specify, to run browser in incognito
// mode
incognitoMode:true, //OPTIONAL
// regressionRun = true - Only test cases in each scenario/spec that
// is marked with Regression=yes will be run.
//regressionRun:true, //OPTIONAL
// sanityRun = true - Only test cases in each scenario/spec that
// is marked with Sanity=yes will be run.
//sanityRun:true //OPTIONAL
// If neither sanityRun and regressionRun are not specified or both is set to false,
// then ALL test cases will be run
// specs - required only if multiple specs need
// to run as part of this suite
specs :'test-bvt,test-login', // OPTIONAL
//When set to true, a randomValue per testcase of the scenario will be generated
//randomValue can be used in keywords of the testcase as data
//for executing specific actions
getAutoRandomValue :true, // OPTIONAL
/*-------
serialExecution:true - Will run all testcases in the above specs in serial mode
serialExecution:false - Will run all testcases in the above specs in parallel mode
This setting can/will be overriden with the that in specific spec's config file
by providing/not providing this parameter in that spec's config file
To run testcases in parallel, either do not specify this parameter
or set it to false
---------*/
//serialExecution : true //OPTIONAL
// Comma separated list of email address to which automation run
//status and report will be notified. Do not specify if email
// notification is not needed
//emailRecipients:'[email protected],[email protected]' //OPTIONAL
//Comma separated list of tag names. Only the testcases tagged by these tags in the scenario spreadsheet, will be run
//tcSelectorTags:'tag1,tag2' //OPTIONAL
//noRetry - if set to 'true', failed testcases of this scenario will
//NOT be retried when global config(set in playwright.config.js
//or specified on command line) for retries > 0
//noRetry: true //OPTIONAL
}
The Playwright framework maintains different JavaScript classes for different keywords. So, while migrating the existing keyword or creating a new keyword, consider below points:
Example: For mdmLogin keyword, the keyword file name should be mdmLogin.js.
class <className> extends Keyword {
process = async () => {
// <write the normal keyword functionality here>
}
}
module.exports = <className>
Any new keyword implementation class need to extend the Keyword base class. So, import the base Keyword file by using 'require'.
Example:
const Keyword = require("../test-hierarchy/keyword")
From the keyword class, a PO Object can be instantiated as below:
let <po_class_object>= new
<PO_class_name>(this.scenarioName,this.testcaseName,this.name,this.context);
PO class extends PageObject base class, and this base class contains a constructor which requires following parameters:
As the PO extends PageObject class, it refers to the base class constructor while initializing the object. So, always initialize the object with above parameters.
As these parameters are defined as base class variables, no need to pass it explicitly when PO class functions are called from keyword class. In other words, all these data will be accessible in PO class and it can be accessed using 'this'.
The < po_class_object > will be used in keyword class to call the PO functions.
scenarioName, testCaseName, and name are the private variables in the base keyword class, which represents the following:
To get the ‘page’ object from base keyword class, use ‘context’. Follow the below syntax for accessing the page object in keyword class:
let page = this.context.page.
page object provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
In simple words, to perform some action on some locators in a browser tab, always use
page.locator(<locator>)<action>
For example:
await page.locator('div[class="my_class"]').click()
//this will click on the locator with class name 'my_class'.
If any scenario/test case needs to perform imports make sure to create a folder with the same name as the scenario sheet name inside the test-data folder there are a few folders already created for a couple of scenarios like Imports, prereqs, relationship etc.,
Note: we have kept only a few import files in these folders due to size constraint
Keyword base class contains functions like getParams, getParam, getParamCount, logInfo, logError etc. These functions can be used to read data from json scenarios and for logging.
For example, getParam can be used to get the parameter value from json scenario as follows:
let param1 = this.getParam("param1")
Similarly for logging purpose, logInfo , logError , logDebug , logFatal , logWarn etc can be used.
Example:
this.logInfo(‘log message’);
Commonly used assertions in keyword class
let param1 = this.getParam("param1");
await expect(param1, this.testcaseName+" >>Parameters are missing in the sheet").not.toBeNull()
await PO_createEntity.fn_createEntity(loc_attribute, loc_displayType, loc_attributeValue, loc_attributeAction
expect(isStatus).toBe(true);
this.logInfo('Entity Creation- Attributes filled successfully');
});
See the below example of createEntitySetClassification keyword class which is already created in Playwright framework.
const Keyword = require("../test-hierarchy/keyword")
const { create_entity_po } = require('../objectRepository/create-entity-po');
const { expect } = require('@playwright/test');
class createEntitySetClassification extends Keyword {
process = async () => {
let page = this.context.page;
let param1 = this.getParam("param1");
let param2 =this.getParam("param2");
await expect(param1, this.testcaseName +
" >>First paramter is missing in the sheet for the keyword createEntityFillAttributes").not.toBeNull()
await expect(param2, this.testcaseName +
" >>Second parameter is missing in the sheet for the keyword createEntityFillAttributes").not.toBeNull()
let loc_setClassification = null;
let loc_setClassificationAction = null;
let PO_createEntity = new create_entity_po
(page, this.scenarioName, this.testcaseName, this.name);
loc_setClassification = this.getParam("param1").toString().trim();
if (loc_setClassification.toLowerCase() != "na")
loc_setClassification =
this.getParam("param1").split("#@#").join("||");
else
loc_setClassification = null;
loc_setClassificationAction =
param2.toString().trim().split("#@#").join("||");
expect(loc_setClassificationAction,'Param ')
await PO_createEntity.fn_createEntity(null, null, null, null,
loc_setClassification,
loc_setClassificationAction).then((isStatus) => {
expect(isStatus).toBe(true);
this.logInfo('Entity Creation- classification set successfully');
});;
}
}
module.exports = createEntitySetClassification
The PO files should be created under 'objectRepository' directory in the project with the file name as <file_name>_po.js. All the functions related to a particular scenario should be available in one PO file.
For example, if there is a search_po.js, all the search related functions like resetSearchPage, setSearGridActions, refineFilterNestedAttribute etc. should be written in the same PO file.
Refer the below syntax for writing a PO file:
exports.<class_name> = class <class_name> extends PageObject {
async <function1>(arg1, arg2...){
}
async <function2>(arg1, arg2...){
}
}
All the PO class extends the PageObject base class which should be pulled into the PO file by using 'require'.
const PageObject = require("./page-object")
The PageObject base class contains a constructor which is initializing scenarioName, testCaseName, keywordName, contxt etc. It also has logging functions like logInfo, logError , logDebug , logFatal , logWarn etc.
From the keyword class, the PageObject constructor is initialized, so scenarioName, testCaseName, keywordName, context and the logging functions will be available to the classes which are extending PageObject.
This will simplify the coding as these data will be available to all the functions in PO class without passing it externally from the keyword class.
To access these data, use 'this' keyword. For example:
let scenarioName = this.scenarioName
let keyword = this.keywordName
let page = this.page
this.logInfo(<log message here>)
Refer the below PO class and function which is already created playwright framework:
const PageObject = require("./page-object")
const { expect } = require('@playwright/test');
let rsLib = require('../utils/rs-generic-lib');
exports.navigation_po = class navigation_po extends PageObject {
async fn_toastMessage(message) {
let toast_mess = false;
let elm_pebbleToast_closed = await this.page.locator('pebble-toast-v2[id="pebbleAppToast"][class="toast-bottom-right"]');
let elm_pebbleToast_open = await this.page.locator('pebble-toast-v2[id="pebbleAppToast"][class="toast-bottom-right paper-toast-open"]');
let elm_message = await elm_pebbleToast_open.locator('div[id = "bind-html"]');
for (let i = 0; i < 30; i++) {
if (await elm_pebbleToast_open.isVisible()) {
await elm_message.innerText().then(async (text) => {
await console.log("text", text);
await expect(text).toBe(message);
toast_mess=true;
});
break;
} else {
await this.page.waitForTimeout(500)
}
}
if (!toast_mess) {
this.logInfo("Waiting for toast message display:'" + toast_mess + "'");
}
return true;
};
}
The Playwright framework converts the Excel workbook scenarios into a Json file.
To convert Excel to Json, use the command:
npm run build-scenarios
Which will autogenerate a Json file under json-scenarios directory and playwright will be reading keywords and parameters from this Json file.
UI Test Automation framework generates a custom UI report which will get generated automatically after each test under 'custom-reports' directory.
Custom report provides the following information:
UI Test Automation Framework uses log4j logging. All the logging related methods can be found in utils/logger.js. The Keyword base class and PageObject base classes are calling the methods from this logger.js. So, this logger methods can be used from all the keyword functions and PO functions as keyword and PO classes are extending Keyword base class and PageObject base class.
Following are the log functions which can be used in our framework:
The log will be written to the logs directory.
Syndigo uses a hybrid testing framework, and the test data should be created in Excel workbook with two sheets. The first sheet is the master sheet, which provides details of all the test cases and decides whether a particular test needs to be executed or not. The second sheet is the actual test case sheet in which all the test cases are created. Refer to the below scenario workbook which is already created for UI Test Automation Framework.
Note: All the columns in the newly created master workbook and scenario sheet should be same as in the given example and it is case sensitive.
The test-data directory contains data files that are required for creating the test data for the scenarios
In test-data directory, create directories for the scenarios that need test data and add all the data files specific to scenarios in the directories. The directory name must match the name of the scenario sheet (second sheet in the scenario workbook)
Example: If the scenario sheet name is relationship, then create a directory named ‘relationship’ under the test-data directory, then add all the relationship scenario specific data files in that directory.
The test-hierarchy directory contains the framework files which will be creating a well formatted and easy to use test-hierarchy. To create the test hierarchy, the JavaScript files in test-hierarchy directory use the files in the json-scenarios directory which is created from excel scenarios as mentioned earlier.
test-specs directory has a bootstrap-spec file which manages the spec file creation for all the specs. So, the user doesn’t need to create any spec file as the framework itself will take care of everything.
The Utils directory contains the common utility files, which contains commonly used functions. These functions can be used across various PO files so the code duplications can be avoided.
For example, rs-generic-lib.js is a utility file, in which many commonly used functions like objClick(), waitForElement() etc are available, which can be used anywhere in the project files to avoid duplication and to improve readability.
A few other utility files available under utils directory are:
Constants.js, logger.js, notifier.js, rs-attributes.js etc.
package.json contains all the nodejs dependencies required for the project.
As mentioned in the beginning of this document, the playwright.config.js file contains global configuration for Playwright. Most of these global configuration parameters can be overridden in local config file under config/scenarios directory. This global config file will be created automatically during the playwright installation.
Following are the list of test options and all configuration properties:
To run the playwright test, use the following command:
node runpw [-consoleout] [-url=<>] [-testType=] [-emailRecipients= [-- =<> --=<> …]
Typical usage:
node runpw <suite/scenario name>
// Ex: node runpw search
//(Here the suite/scenario name corresponds to the config/scenarios/config-<suite/scenario name>.js)
To get the console messages, provide '-consoleout' option:
node runpw <suite/scenario name> - consoleout
// Ex: node runpw search -consoleout
UI Test Automation Framework has capability for parallel test execution. It provides scenario level as well as test level parallelism.
To run tests or scenarios in parallel, change the 'workers' config parameter in playwright.config.js. Workers count is the number of browsers instances running in parallel. It is highly recommended to have workers:2 to get better test execution times. To disable parallelism, use workers : 1.
By default testcases of a scenario are run in parallel when workers > 1. If testcases of a scenario needs to run in serial, then in the config_<scnearioname>.js file set serialExecution:true. This is also equivalent to running scenarios in parallel i.e. for example if workers:2 and serialExecution:true and if the suite contains two scenarios, then all testcases of one scenario will run serially on one worker and all testcases of other scenario will run serially on the other worker and the two scenarios are running in parallel across two workers.
If the suite contains more than one scenarios and workers:1 then scenarios will run in serial with all the testcases in each of those scenarios running in serial
The automation framework is provided as zip package - ui-automation-playwright-dist.zip Kindly refer to the attachment. The following are the steps to install the automation framework
node runpw -h
The output of this provides detailed help for running the automation suite. The details are provided below:
|
Usage: node runpw <suite-name> [-consoleout] [-domain=<eds,ces,apps>] [-url=<>] [-testType=<Regression or Sanity or All>][-emailRecipients=<emailAddr1,emailAddr2,...>[-tcSelectorTags=<tag1,tag2,...>] [--<playwrightOption>=<> --<playwrightOption>=<> ...]
Options: -consoleout Display console messages -domain Domain to use - eds/ces/apps; if not specified or blank defaults to eds -url URL for the Syndigo Domain Web -testType Test run type - can be Regression/Sanity/All -emailRecipients Comma separated list of email address to which automation run status and report will be notified -tcSelectorTags Comma separated list of tag names. Only the testcases tagged by these tags will be run --<playwrightOption> Any playwright command line option like --workers=1
|
Examples:
Run test automation for suite named dsvexports with Syndigo MDM Web URL, test type and email recipients options specified in the config/scenarios/conf-dsvexports.js file and on chromium browser(default)-
node runpw dsvexports -consoleout
Run with parallel execution of testcases across 2 browser instances -
node runpw dsvexports -consoleout --workers=2
Run with overriding the configured testType option with commandline option -
node runpw dsvexports -consoleout -testType=Regression
Run without parallel execution of testcases with a single instance of browser-
node runpw dsvexports -consoleout --workers=1
Run with firefox browser -
node runpw dsvexports -consoleout --project=firefox
Run with msedge browser with parallel execution across 2 browser instances -
node runpw dsvexports -consoleout --project=msedge --workers=2
Run with chrome browser with parallel execution across 2 browser instances with email notification of run status and report to [email protected] and [email protected] and for Sanity run(will override the values for these options specified in the config file) -
node runpw dsvexports -consoleout [email protected],[email protected] -testType=Sanity --project=chrome --workers=2
Run all testcases of dsvexports scenario that are tagged with 'prereq,entity' -
node runpw dsvexports -consoleout -tcSelectorTags=prereq,entity
Run ALL testcases of dsvexports scenario -
node runpw dsvexports -consoleout
Run testcases of dsvexports scenario for apps domain that are tagged with 'prereq,entity' and retry failed testcases once -
node runpw dsvexports -consoleout -domain=apps -tcSelectorTags=prereq,entity --retries=1
Follow the steps as indicated in the sections in this document to develop and run an automation suite, as outlined below:
Please find the video links here for below topics which will help to familiarize with the process:
1. Automation Framework Installation
2. Apply Filter through Automation
3. Mapping Tenant and User Details
5. Perform Workflow Transition
6. Installing Updates After Upgrade
Here is the links for PPTs related to above videos:
1. Automation Framework Installation
2. Apply Filter through Automation
3. Mapping Tenant and User Details
Please post your questions in the comments section.