Please check this article if you are new to Custom Functions - How to create and use Custom Functions in Testsigma?


Here's a list of Sample Custom Functions created for Testsigma

  1. Custom Function to check specified error is present partially or fully in Browser log(Developer Console)

  2. Custom Function to change attribute value for HTML Element in a Webpage

  3. Custom Function to display the Console log errors in Test Step Results Metadata

  4. Custom Function to update value of Run-time Test Data by replacing given text

  5. Custom Function to execute file located on local Windows machine

  6. Custom Function to verify the text displayed in a dynamic Web page Element

  7. Custom Function to generate Random String and concatenate it to the given Data

  8. Custom Function to generate Time based OTP Code if the secret key is provided

  9. Custom Function to convert the date format


1. Custom Function to check specified error is present partially or fully in Console log


import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;

/* The step with this function should fail if the Console log contains specified error message
and pass if error message is not present in the Console log or if the Console log is empty.
Add this as a minor step if you don't want the Test Case to fail even if the step fails.*/

public class ConsoleLogs extends TestsigmaCustomFunctions{
  @CustomTestStep
  public TestStepResult verifyErrorMsgIsPresent(String errorMessage){
   
//your custom code starts here
    TestStepResult result = new TestStepResult();
    LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
    for (LogEntry entry : logEntries) {
      if(entry.getMessage().contains(errorMessage)) {
        result.setMessage("Specified error message present in Console Logs");
        result.setStatus(ResultConstants.FAILURE);
        break;
      }
      else{
        result.setStatus(ResultConstants.SUCCESS);
        result.setMessage("Specified error message absent in Console Logs or Console Logs Empty");
      }
    }
    return result;
  }
}


2. Custom Function to change attribute value for HTML Element


import java.lang.Exception;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;

/*
The step containing this function should modify the attribute 'attribute_name'
of the Web Element located by the xpath 'locator' with the value 'final_value'.
If the modification of attribute value fails, the step will fail else it passes. Create
this step as minor step if the Test Case shouldn't fail even if modify attribute fails.
*/

public class ModifyHTMLAttribute extends TestsigmaCustomFunctions{
  @CustomTestStep
  public TestStepResult modifyAttribute(String locator, String attribute_name, String final_value){
    //your custom code starts here
    TestStepResult result = new TestStepResult();
    try{
      WebElement element=driver.findElement(By.xpath(locator));
      JavascriptExecutor js=(JavascriptExecutor)driver;
      js.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attribute_name, final_value);
      result.setMessage("Attribute value changed successfully");
      result.setStatus(ResultConstants.SUCCESS);
    }catch(Exception e){
      result.setMessage("Attribute value not changed");
      result.setStatus(ResultConstants.FAILURE);  
    }
    finally{
    return result;
    }
  }
}


3. Custom Function to update the Console log errors in Test Step Results Metadata


import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;

/*
The step containing this function should export the Browser Console logs
to the Test Step metadata. If there is some issue with exporting the log,
the Test Step should fail. Create this as minor step if the Test Case should
pass even if the export doesn't work.
*/

public class ConsoleLogsOutput extends TestsigmaCustomFunctions{
  @CustomTestStep
  public TestStepResult printConsoleErrorMsgsToMetadata(){
    //your custom code starts here
    TestStepResult result = new TestStepResult();
    try{
      LogEntries logentries = driver.manage().logs().get(LogType.BROWSER);
      result.getMetadata().put("console_log", logentries.getAll());
      result.setStatus(ResultConstants.SUCCESS);
      result.setMessage("Console log exported to Metadata successfully");
    }
    catch(Exception e)
    {
      result.setStatus(ResultConstants.FAILURE);
      result.setMessage("Failed to export Console log to Metadata");
    }
    finally{
    return result;
    }  
  }
}






4. Custom Function to update Run-time Test Data by replacing text

import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.testengine.exceptions.TestEngineException;

public class RuntimeDataUpdate extends TestsigmaCustomFunctions {

  @CustomTestStep
  public TestStepResult updateRuntimeData(String runtimeVariableName, String searchtext, String replacetext) throws TestEngineException {
    TestStepResult result = new TestStepResult();
    try{
      String inittext = getRuntimeData(runtimeVariableName);
      if(inittext.contains(searchtext)){
        String finaltext = inittext.replace(searchtext, replacetext);
        setRuntimeData(runtimeVariableName, finaltext);
        result.setStatus(ResultConstants.SUCCESS);
        result.setMessage("Given search text '"+searchtext+"' replaced with '"+replacetext+"' in runtime variable '"+runtimeVariableName+"'");
      }
      else{
        result.setStatus(ResultConstants.FAILURE);
        result.setMessage("Given search Text '"+searchtext+"' not found in runtime variable with value '"+inittext+"'");
      }
    }catch(TestEngineException testengex){
      result.setStatus(ResultConstants.FAILURE);
      result.setMessage("Failed to update runtime variable - TestEngineException");
    }
  return result;
  }
}



5. Custom Function to execute file located on local Windows machine

import java.io.IOException;
import java.lang.InterruptedException;

import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;

public class FileExecution extends TestsigmaCustomFunctions {
  @CustomTestStep
  public TestStepResult runBatFile(String file_path){
      int returnValue;
      TestStepResult result= new TestStepResult();
      try {
        Process proc = Runtime.getRuntime().exec(file_path);
        proc.waitFor();
        returnValue = proc.exitValue();
        result.setStatus(ResultConstants.SUCCESS);
        result.setMessage("Ran file successfully with exit code "+returnValue);
      }catch (InterruptedException intrex) {
        result.setStatus(ResultConstants.FAILURE);
        result.setMessage("Failed to execute file - Timed out waiting for file execution");
      }catch (IOException ioex) {
        result.setStatus(ResultConstants.FAILURE);
        result.setMessage("Failed to execute file - Check whether file is present in the directory");
      }
      return result;
    }
}



6. Custom Function to verify the text displayed in a dynamic Web page Element

import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.testengine.exceptions.TestEngineException;
import com.testsigma.testengine.utilities.UiIdentifierProvider;
import org.openqa.selenium.By;

/* This Custom Function can be used to check whether the text displayed inside
a Webpage Element is same as the given verification text. The Webpage Element has
a dynamic XPath and the dynamic part is fetched from another Element in a previous step
and stored in a runtime variable.

Custom Function Parameters:
1. A runtime variable containing the dynamic value part of xpath,
2. XPath of the Element where the text is to be verified with '1replace_text1' at the
part to be replaced,
3. Text to be verified
*/

public class ElementTextVerification extends TestsigmaCustomFunctions {
  @CustomTestStep
  public TestStepResult verifyElementDisplaysText(String runtimeVariableName, String UIIdentifierXpath, String texttoVerify) throws TestEngineException {
    TestStepResult result = new TestStepResult();
        String newUIIdentifierxpath="";
        String dynamicText="";
        String elementText="";
    try{
          dynamicText= getRuntimeData(runtimeVariableName);
          if(UIIdentifierXpath.contains("1replace_text1")){
            newUIIdentifierxpath = UIIdentifierXpath.replace("1replace_text1",dynamicText);
          }
          elementText = driver.findElement(By.xpath(newUIIdentifierxpath)).getText();
          if(elementText.trim().contains(texttoVerify.trim())){
            result.setStatus(ResultConstants.SUCCESS);
            result.setMessage("UI Identifier '"+newUIIdentifierxpath+"' contains text "+texttoVerify);
          }
          else{
            result.setStatus(ResultConstants.FAILURE);
      result.setMessage("UI Identifier '"+newUIIdentifierxpath+"' doesn't contain text "+texttoVerify);
      }
        }catch(TestEngineException testengex){
          result.setStatus(ResultConstants.FAILURE);
      result.setMessage("Failed to get runtime variable - TestEngineException");
        }
  return result;
  }
}



7. Custom Function to generate Random String and concatenate it to the given Data

import org.apache.commons.lang3.RandomStringUtils;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestData;
public class StringConcatenation extends TestsigmaCustomFunctions{
@CustomTestData
public String concatWithRandomString(String Data, int randomStringLength){
String finalString=Data+RandomStringUtils.randomAlphabetic(randomStringLength).toLowerCase();
System.out.println(finalString);
return finalString;
}
}



8. Custom Function to generate Time based OTP Code if the secret key is provided

import org.jboss.aerogear.security.otp.Totp;

import com.testsigma.customfunc.common.TestsigmaCustomFunctions;
import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;
import com.testsigma.testengine.exceptions.TestsigmaTestdataNotFoundException;


public class TOTPGenerator extends TestsigmaCustomFunctions{

@CustomTestStep
public TestStepResult generateOTP(String secretkey , String runtime_variable_name) throws TestsigmaTestdataNotFoundException {
TestStepResult result= new TestStepResult();
try{
Totp otpgenerator = new Totp(secretkey);
String newotp = otpgenerator.now();
//storing to runtime variable given as argument in Custom Step
setRuntimeData(runtime_variable_name, newotp);

result.setStatus(ResultConstants.SUCCESS);
result.setMessage("OTP generated and stored in runtime variable named "+runtime_variable_name);
}
catch(Exception e){
result.setStatus(ResultConstants.FAILURE);
result.setMessage("otp not generated");
}
return result;
}
}


9. Custom Function to convert the date format

import com.testsigma.customfunc.common.CustomTestStep;
import com.testsigma.customfunc.result.ResultConstants;
import com.testsigma.customfunc.result.TestStepResult;
import com.testsigma.customfunc.common.TestsigmaCustomFunctions;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConversion extends TestsigmaCustomFunctions{

@CustomTestStep
public TestStepResult parse2Format(String runtimevarname, String currentFormat, String parseFormat) throws Exception {
TestStepResult result = new TestStepResult();

try {
String dateStr = getRuntimeData(runtimevarname);
SimpleDateFormat parser = new
SimpleDateFormat(currentFormat);
Date thedate = parser.parse(dateStr);
SimpleDateFormat formatter = new SimpleDateFormat(parseFormat);
String convertedDate = formatter.format(thedate);
setRuntimeData(runtimevarname, convertedDate);

result.setStatus(ResultConstants.SUCCESS);
result.setMessage("Custom Step Executed successfully");
} catch (Exception ex) {
result.setStatus(ResultConstants.FAILURE);
result.setMessage(ex.getMessage());
}
return result;
}
}