How to set and save a variable using the script

Hi there!

I’m running a test which generates me an ID. This ID increments by 1 every time the test is run. I need to verify this ID each time the test is run, but as it is a dynamic value I am struggling to do so.

I have thought of ways to do this but cannot set AND save a variable value.

For example, I need to be able to do this and save it each time so it will continuously work.

def init_value = 2900
def value = init_value + 1
init_value = value

So I need to be able to SAVE the variable value at the end of every test execution. Essentially, how do I set the value of a variable using groovy and then save that variable value for further use.

I apologise for repeating myself, but just wanted to make the question as clear as possible.

Any help is greatly appreciated.

I want to save the variable value here

What do you mean by saying “here”? Where do you want to save the value into? Please state it clearly.

I added a screenshot right below the “here.” I want it saved in the variables tab

Do you mean you want to increment the “Default value” of “variable” from 0 to 1 by script?

I have an idea how to implement it, but it is not a good approach.

However I would tell you the straight forward scenario how to. The content of Variable tab of a “New Test Case” is serialised into an XML file at the path of “projectDir/Test Cases/New Test Case.tc”, which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<TestCaseEntity>
   <description></description>
   <name>New Test Case</name>
   <tag></tag>
   <comment></comment>
   <testCaseGuid>c46d1117-79df-4d02-a44f-d6a0c03f43e0</testCaseGuid>
   <variable>
      <defaultValue>'bar'</defaultValue>
      <description></description>
      <id>d70ab867-638b-4043-a88c-2e4bc5168e19</id>
      <masked>false</masked>
      <name>foo</name>
   </variable>
</TestCaseEntity>

Here you can find an XML element

<defaultValue>'bar'</defaultValue>

This is the serialized format of a Default value of a variable foo of the Test Case.

You might be able to write a Test Case script to edit this XML file. I guess, Katalon Studio does not prohibit you from doing so.

Let me suppose you have developed that Test Case script. Every time you executed it and edited the XML file, you have to close the project and reopen it. This is to let Katalon Studio reload the edited XML file.

I do not think that this approach is good.


If you are capable of Groovy programming, you should be able to write a script that makes a text file in the project directory, and update it. The script will create a file, for example projectDir/history.json, with the initial state

{"times":0}

Once your test has run, the file should be updated to:

{"times":1}

Next time it should be updated to:

{"times":2}

and so on.

Your test case script needs to be capable of entirely managing (create/read/write/delete) the file. Skill of Groovy programming is required here.

I have no other idea easier to implement.

Yes, on every run.

Thanks for the reply … seems like a lot of work for such a small issue. Maybe this thread should be moved to feature requests.

I agree with you.

Katalon Studio does not provide user with any built-in means of storing current test results and retrieving the previous record.

@Russ_Thomas

Could you move this topic to the “Feature Request” category?

I have a not-so-complex workaround for this. In my similar test case I read lines from a text file, save them into variables, modify some as needed and write back into the file.

The below example refers to a local txt which contains only a number in the first line.

You should think about the test case outcomes whether you want to save the incremented ID or not, if it fails at some point.

The downside of this FileWriter solution that it overwrites the whole text file, so if you have more than one line, you need to read all and write back all of them. including break lines.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.io.FileWriter;
import java.io.IOException;

String filename = 'C:\\tmp\\var.txt'
ArrayList<String> lines = new ArrayList<>(Files.readAllLines(Paths.get(filename)));

String var1str = lines.get(0)
int var1int = var1str as int

var1int++

try {
    	FileWriter writer = new FileWriter(filename, false);
        writer.write(Integer.toString(var1int));
        writer.close();
} catch (IOException e) {
   	e.printStackTrace();
}

My sample Test Case:

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

final String fileName_ = "history.json"
final DateTimeFormatter formatter_ = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

Path projectDir = Paths.get(RunConfiguration.getProjectDir())
Path f = projectDir.resolve(fileName_)

def history = readHistory(f)

history["times"] += 1
history["lastRunAt"] = LocalDateTime.now().format(formatter_)

writeHistory(history, f)

WebUI.comment("history.times = ${history['times']}")

/**
 * 
 * @param f
 * @return
 */
def readHistory(Path f) {
	if (!Files.exists(f)) {
		Map m = [ "times":0 ]
		f.text = JsonOutput.toJson(m)
	}
	return new JsonSlurper().parse(f.toFile())	
}

/**
 * 
 * @param history
 * @param f
 * @return
 */
def writeHistory(Object history, Path f) {
	f.text = JsonOutput.toJson(history)
}

This creates history.json file with the following content like this:

{"times":8,"lastRunAt":"2021-10-22 18:06:48"}

This will show the following at the 8th times of execution.

2021-10-22 18:06:48.731 INFO  c.k.k.c.keyword.builtin.CommentKeyword   - history.times = 8

You can extend the script and add more data items in the history.json file.

Hi Josh,

Could you clarify “need to verify this ID each time the test is run”, what the purpose of this verification? Or do you have other use cases?
So I can suggest a better solution for the problem.

Hi Chris,

I need to verify the ID is being sent in the correct order. So for example on the first run, I know the ID will be 2554. If I run the test again, I need to make sure the ID is now 2555.

Hope this helps.

1 Like

Could you explain what “the ID” is? What does it mean, what does it stand for? Who (which software component) decides the ID value? When is the ID value incremented? When is the ID value is initialised to 0? Is “the ID” value visible and accessible as a HTML element? If not, how your test script will get access to the value of “the ID” (by which Katalon Keyword)?

1 Like

@josh.thompson

I guess you don’t need to save the variable value into the history.json at all if the ID is incremented by a simple event, e.g, log-in/log-out the App.

Your test case script should be able to make 2 or more times of firing the events (login/logout) in a single test case execution. Then your test case script would be able to check how the value of ID moves at each event firing. In this scenario, your test case will create a variable and update/read it, but it doesn’t have to save the value into an external file to pass to the following Test Case runs.

I am just guessing … You haven’t explained enough about the ID nature, so it is difficult for others to have clearer idea about your problem.