Util (Common Tool Functions)

Util is an object containing various commonly used tool functions that help us complete common operations in automation scripts. For example, it can be used to delay and wait for a period of time, start or stop processes, operate the clipboard, or handle files.

You can import the Util object as follows:

JavaScript
Python
const { Util } = require('leanpro.common');
from leanproAuto import Util

Util provides the following methods:

Method Name Description
delay Wait for the specified number of milliseconds before continuing execution.
launchProcess Launch an executable file at the specified path with arguments and optional startup options.
stopProcess Stop the specified child process.
loadPlugin Load the specified plugin into the specified process.
takeScreenshot Capture the entire screen image, save it in PNG format, and return the base64 encoding of the screenshot.
loadCsvFile Read a CSV file and return an array of JSON objects.
saveToCsvFile Save data in JSON format as a CSV file.
getClipboard Get the contents of the clipboard.
setClipboard Set the contents of the clipboard.
copyDir Copy the source directory and its contents to the target directory.
reportStep Display custom information in CukeTest's run output.
runJavaScript Run the specified JavaScript code.
runPython Run the specified Python code.

Type Definitions

JavaScript
Python
class Util {
    static delay(milliseconds: number): Promise<void>;
    static launchProcess(exePath: string, ...args: string[]): ChildProcess; 
    static launchProcess(exePaths: string, args: string[], options?: SpawnOptions): ChildProcess;
    static stopProcess(proc: ChildProcess| pid): boolean;
    static loadPlugin(proc: ChildProcess | number | string, plugins: string | string[]): Promise<void>;
    static takeScreenshot(filePath: string = null, monitor: number = 0): string | void;
    static loadCsvFile(filePath: string): Promise<RowCsv[]>;
    static saveToCsvFile(rows: RowCsv[], filePath: string): boolean;
    static getClipboard(): Promise<string>;
    static setClipboard(text: string): Promise<void>;
    static copyDir(source: string, target: string): Promise<void>;
    static reportStep(stepTitle: string | Buffer): Promise<void>;
    static runJavaScript(source: string): Promise<any>;
    static runPython(source: string, options?: object): Promise<any>;
}
class Util:
    def copyDir(source: str, target: str) -> None
    def delay(milliseconds: int) -> None
    def launchProcess(exePath: str, *args: List[str]) -> "ChildProcess"
    def stopProcess(proc: Union[ChildProcess, pid]) -> bool
    def loadPlugin(pidOrName: Union[str, int], plugins: Union[str, List[str]]) -> None
    def getClipboard() -> str
    def setClipboard(text: str) -> None
    def reportStep(stepTitle: Union[str, bytearray]) -> None
    def runJavaScript(source: str) -> Any
    def runPython(source: str, *options: Optional[Dict]) -> Any

API Introduction

delay(milliseconds)

Wait for the specified time before continuing execution.

Parameters:

  • milliseconds: number type, indicating the time to delay (in milliseconds).

Return Value:

  • Returns no value.

Usage Example:

JavaScript
Python
// Wait 1 second before executing the next step
await Util.delay(1000);
# Wait 1 second before executing the next step
Util.delay(1000)

launchProcess(exePath, args, options)

Launch the specified executable file, optionally passing arguments and startup options.

Parameters:

  • exePath: string type, the path to the executable file.
  • args: (Optional) string[] type, an array of arguments to pass to the executable file, used similarly to child_process.spawn().
  • options: (Optional) SpawnOptions type, additional parameters to control process execution, such as environment variables, working directory, etc.
    • cwd: string type, the working directory of the child process. Default is the running project directory, i.e., the value of process.cwd().
    • env: Object type. Environment key-value pairs. Default: process.env, i.e., the environment variables when CukeTest is running.
    • detached: boolean type. The child process runs independently of its parent process (runs detached from parent process control).
    • shell: boolean or string type. If true, run the command inside a shell. Uses '/bin/sh' on Unix and process.env.ComSpec on Windows. A different shell can be specified as a string. Default: false (no shell).
    • plugins: string[] type. Specifies automation plugins to load (such as "qt", "guiText", etc.) to enable corresponding technology support.

Return Value:

  • Returns a ChildProcess object to record information about the started process, which can later be used with the stopProcess() method to close the process. For more information about the ChildProcess class, see child_process class.

Usage Examples:

JavaScript
Python
// Launch Calculator
await Util.launchProcess('C:/Windows/System32/calc.exe');

// Launch Notepad and open a specified file
await Util.launchProcess('C:/Windows/System32/notepad.exe', ['C:/path/to/your/file.txt']);

// Launch a custom application and set the working directory
await Util.launchProcess('C:/path/to/your/app.exe', [], { cwd: 'C:/path/to/your/app_directory' });

// Launch an application and set environment variables
await Util.launchProcess('C:/path/to/your/app.exe', [], { env: { MY_ENV_VAR: 'value' } });

// Launch an application in an independent shell
await Util.launchProcess('C:/path/to/your/app.exe', [], { shell: true });

// Launch an application and load specified plugins
await Util.launchProcess('C:/path/to/your/app.exe', [], { plugins: ['qt', 'guiText'] });
# Launch Calculator
Util.launchProcess('C:/Windows/System32/calc.exe')

# Launch Notepad and open a specified file
Util.launchProcess('C:/Windows/System32/notepad.exe', ['C:/path/to/your/file.txt'])

# Launch a custom application and set the working directory
Util.launchProcess('C:/path/to/your/app.exe', [], { 'cwd': 'C:/path/to/your/app_directory' })

# Launch an application and set environment variables
Util.launchProcess('C:/path/to/your/app.exe', [], { 'env': { 'MY_ENV_VAR': 'value' } })

# Launch an application in an independent shell
Util.launchProcess('C:/path/to/your/app.exe', [], { 'shell': True })

# Launch an application and load specified plugins
Util.launchProcess('C:/path/to/your/app.exe', [], { 'plugins': ['qt', 'guiText'] })

stopProcess(proc)

Stop the specified child process.

Parameters:

  • proc: ChildProcess object or process ID (pid). Usually the child process object returned by the launchProcess() method or its pid.

Return Value:

  • Returns boolean, indicating whether the process was successfully stopped.

Usage Examples:

JavaScript
Python
const proc = await Util.launchProcess('C:/Windows/System32/calc.exe');
Util.stopProcess(proc);     // Terminate via process object
Util.stopProcess(proc.pid); // Terminate via pid
proc = Util.launchProcess('C:/Windows/System32/calc.exe')
Util.stopProcess(proc)      # Terminate via process object
Util.stopProcess(proc.pid)  # Terminate via pid

Note: Some applications are multi-process. The interface window is opened by the main process. In this case, stopping the main process may not close the application interface. The Calculator app in Windows 10 is an example of this.

loadPlugin(pidOrNameOrProcess, plugins)

Load plugins into the specified process. Some automation operations require the application under test to load specific plugins to work properly (for example, Qt automation requires loading the qt plugin). If you launch the application through CukeTest, the tool will automatically load the required plugins based on the current automation type.

However, in some special cases, you may need to manually load plugins:

  • Application auto-restart: If the application automatically restarts during execution, the restarted application may not load any plugins.
  • Plugin loading failure: Due to different startup methods of the application under test, plugins may fail to load. If CukeTest attempts to automatically load plugins multiple times without success, you can manually load the plugins.

Parameters:

  • pidOrNameOrProcess: Supports three types:
    • ChildProcess: The object returned after launching the application via the Util.launchProcess() method.
    • number: The process PID (process number). If the target process may have multiple instances, it's recommended to use the PID to ensure the plugin is loaded into the correct process.
    • string: The process name.
  • plugins: string | string[] type, the name(s) of the plugin(s) to load. The plugin list can be viewed in the launch application dialog.

Return Value:

  • Returns no value.

Usage Examples:

If you need to use Text Recognition Technology in a running Windows application, you need to load the guitext plugin via loadPlugin():

JavaScript
Python
// Launch a Windows application (e.g., Dialer)
let proc = Util.launchProcess("C:/Windows/System32/dialer.exe");

// Method 1: Load plugin via ChildProcess object
await Util.loadPlugin(proc, 'guitext');

// Method 2: Load plugin via process name
await Util.loadPlugin("dialer.exe", 'guitext');

// Method 3: Load plugin via process PID (assuming PID is 42532)
await Util.loadPlugin(42532, 'guitext');
# Launch a Windows application (e.g., Dialer)
proc = Util.launchProcess("C:/Windows/System32/dialer.exe")

# Method 1: Load plugin via ChildProcess object
Util.loadPlugin(proc, 'guitext')

# Method 2: Load plugin via process name
Util.loadPlugin("dialer.exe", 'guitext')

# Method 3: Load plugin via process PID (assuming PID is 42532)
Util.loadPlugin(42532, 'guitext')

takeScreenshot(filePath, monitor)

Deprecated: It is recommended to use the capture() and captureToFile() methods of the Screen object instead.

Capture a screenshot, save it as a PNG file, and return a Base64-encoded string. Screenshots can be directly inserted into test reports as images. For usage, see Report Attachments.

Parameters:

  • filePath: (Optional) string type, the path to save the screenshot, should end with .png suffix.
  • monitor: (Optional) number type, specifies the screen number to capture, 0 for all monitors, 1 for the first monitor, default is 0.

Return Value:

  • Returns the Base64-encoded string of the screenshot.

loadCsvFile(filePath)

Load a CSV file and return an array of JSON objects. Each object's key is the column name and value is the data.

Parameters:

  • filePath: string type, the path to the CSV file to read.

Return Value:

  • Returns Array<object> type, the data from the CSV file.

Usage Example:

Suppose there is a data.csv file with the following content:

first_name,last_name,company_name,state,zip
James,Butt,"Benton, John B Jr",LA,70116
Josephine,Darakjy,"Chanay, Jeffrey A Esq",MI,48116
Art,Venere,"Chemel, James L Cpa",NJ,8014

Use the following code to read it:

JavaScript
let data = await Util.loadCsvFile('data.csv');
console.log(data);

It will return the following JSON:

[
  { "first_name": "James", "last_name": "Butt", "company_name": "Benton, John B Jr", "state": "LA", "zip": "70116" },
  { "first_name": "Josephine", "last_name": "Darakjy", "company_name": "Chanay, Jeffrey A Esq", "state": "MI", "zip": "48116" },
  { "first_name": "Art", "last_name": "Venere", "company_name": "Chemel, James L Cpa", "state": "NJ", "zip": "8014" }
]

saveToCsvFile(rows, filePath)

Save data in JSON format as a CSV file.

Parameters:

  • rows: Array<object> type, the array of data to save. Each object's key is the column name and value is the cell content.
  • filePath: string type, the path to save the CSV file.

Return Value:

  • Returns boolean indicating whether the save was successful.

Usage Example:

JavaScript
const rows = [{ name: 'Alice', age: 30 }];
await Util.saveToCsvFile(rows, 'data.csv');

copyDir(source, target)

Copy the source directory and its contents to the target directory. If the target folder does not exist, it will be automatically created.

Parameters:

  • source: string type, the path to the source directory to copy.
  • target: string type, the path to the target directory.

Return Value:

  • None

Usage Examples:

JavaScript
Python
await Util.copyDir('source_folder', 'target_folder');
Util.copyDir('source_folder', 'target_folder')

reportStep(message)

Display custom information in CukeTest's run output, including text and images. This method is very useful for inserting debugging information, key step descriptions, or instant screenshots during test execution.

Parameters:

  • message: string | Buffer type, the content to display.
    • When it's a string type, it will be displayed as plain text information in the run output.
    • When it's a Buffer type (e.g., image binary data), CukeTest will attempt to render it as an image and display it in the run output.

Return Value:

  • Returns no value.

Usage Examples:

Display a text message in the run output:

JavaScript
Python
Util.reportStep("Current test step: Login user");
Util.reportStep("Current test step: Login user")

Display an image (e.g., screenshot) in the run output:

JavaScript
Python
let imageBuffer = Buffer.from(screenshot, 'base64'); // screenshot is assumed to be a base64-encoded image string
Util.reportStep(imageBuffer);
# Assuming screenshot is a base64-encoded image string
import base64
imageBuffer = base64.b64decode(screenshot)
Util.reportStep(imageBuffer)

runJavaScript(source)

Run custom JavaScript code and return the execution result.

Parameters:

  • source: string type, JavaScript code string.

Return Value:

  • Returns Promise<any>, indicating the execution result of the code.

Usage Examples:

JavaScript
Python
const result = await Util.runJavaScript('2 + 2');
assert.equal(result, 2);
result = Util.runJavaScript('2 + 2')
assert result == 2

runPython(source, options)

Run custom Python code and return the execution result.

Parameters:

  • source: string type, Python code string.
  • options: (Optional) object, optional runtime parameters.

Return Value:

  • Returns Promise<any>, indicating the execution result of the code.

Usage Examples:

JavaScript
Python
const result = await Util.runPython('print(2 + 2)');
assert.equal(result.replace("\r\n", ""), "Hello World!");
result = Util.runPython('print(2 + 2)')
assert result.replace("\r\n", "") == "Hello World!"

Clipboard Operations

The following are two simple methods for reading and setting the contents of the clipboard.

getClipboard()

Get the contents of the clipboard.

Parameters:

  • None

Return Value:

  • Returns Promise<string> the text content in the clipboard.

Usage Examples:

JavaScript
Python
const clipboardText = await Util.getClipboard();
console.log('Clipboard content:', clipboardText);
clipboardText = Util.getClipboard()
print('Clipboard content:', clipboardText)

setClipboard(text)

Set text to the clipboard.

Parameters:

  • text: string type, the text content to set to the clipboard.

Return Value:

  • None

Usage Examples:

JavaScript
Python
await Util.setClipboard('Hello World');
console.log('Clipboard content set to: Hello World');
Util.setClipboard('Hello World')
print('Clipboard content set to: Hello World')