Variables and their type conversion using KarateDSL

Priyanka Brahmane
6 min readJul 14, 2021

--

Hola TestCommunity!!!

I’ve covered a few fundamental topics in Karate DSL so far. If you haven’t read any of the previous blogs, here’s a link to get you started.

You’re reading the 6th chapter of my karate DSL series, which is designed to help you grasp different variables and their type conversions.

What is a variable and why is type conversion significant?

A Variables are used to hold data in a computer programme that may be referenced and changed. In short, Variables can be thought of as information-holding boxes. They exist just to categorize and store data in memory.

Type conversions is the process of converting a variable from one data type to another. We may convert string/text/yaml/xml to json.

Let’s take a closer look at each variable and understand in detail-

def - This keyword is typically for defining a new variable. It is a powerful keyword that can be used for storing any type of variable such as number, string, to read JS function, JSON, Array, JSONPath, XML and even JS-Java.

We can you custom names for variables.It is the most preferred karate keyword.

Let us have a look at few examples stated below-

To define a number:

Feature: Type definition DemoScenario: Define a numberAnd def test_variable = 1And print test_variable

To define a string:

Feature: Type definition DemoScenario: Define a stringAnd def test_string = "abc"And print test_string

To define a JS Function and JSONPath:

Scenario: Define a JS function and JSONPathGiven url 'http://openlibrary.org/api/volumes/brief/isbn/9780525440987.json'When method GetThen status 200And def pagecount = $..latest_revisionAnd def square_function = function(m) { return m * m; }And def square = square_function(pagecount)And print square

We can declare a JSON in a single line or in a multi-line JSON wrapped between three double inverted commas (“””).

Scenario: Define a JSON in 2 techniques - single line and multi-lineAnd def single_line_json = {key1: 'value1' , key2: 'value2' }And print single_line_jsonAnd def multi_line_json ="""{key1: 'value1' ,key2: 'value2',key3: [key4: 'value4' ,key5: 'value5',key6: {key7: 'value7' , key8: 'value8'}]}"""And print multi_line_json

To define an Array:

# Array is defined from above jsonAnd def test_array = multi_line_json.key3And print test_array

string- It is used convert JSON or any other data-type (except XML) to a string.

API : https://jsonplaceholder.typicode.com/comments?postId=1

Feature: Type definition DemoScenario: Define a stringGiven url 'https://jsonplaceholder.typicode.com/comments?postId=1'When method GetThen status 200And print responseAnd string string_type = response[0]And print string_typeAnd string convert_num_to_string = response[0].idAnd print convert_num_to_stringAnd match convert_num_to_string == '1'And def name = 'String demo'And string dynamic_string = '{\r"name":"'+name+'",\n"postId":1,\n"id":1,\n"body":"laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium",\n"email":"Eliseo@gardner.biz"} 'And print dynamic_string

For more examples, refer this link.

text- This is used to treat payload as raw text. I can be used to disable karate’s default behaviour of parsing everything that looks like JSON or XML.

In the karate documentation, it is stated that — this is especially relevant when manipulating GraphQL queries because although they look suspiciously like JSON, they are not, and tend to confuse Karate’s internals.

It can be used with “Scenario Outline” and “Examples” keyword.

Feature: Type definition DemoScenario Outline: Define a textAnd text textQuery ="""{name: <name>,email: <e-mail>}"""And print textQueryExamples:|name       | e-mail                               ||'ameesh'   |'ameesh@email.com'                    ||'abhilasha'|'ab@email.com'                        ||'arav'     |['arav123@email.com','abc@gmail.com'] |

json - Using this keyword, JSON can be created from XML, a map-like or list-like object, a text or even a Java object.

Scenario: Define a JSONAnd json mapObject = { 'a': 1 , 'b': 2 , 'c': 3 }And print mapObjectAnd json my_list = [1, "Hello", 3.4]And print my_listAnd json xmlType = <?xml version="1.0" encoding="ISO-8859-1"?>  <note>   <to>Tove</to>  <from>Jani</from>  <heading>Reminder</heading>  <body>Don't forget me this weekend!</body>  </note>And print xmlType

table- It’s used to turn all of the columns into JSON. It can be used to solve nested complex scenarios that are dependent on dynamic data.

Feature: Type definition DemoScenario: Define a tableAnd table tableObj|S.no |name      | e-mail             ||1    |'meesh'   |'ameesh@email.com'  ||2    |'abhilasha'|'ab@email.com'     ||3   |'arav'      |['arav123@email.com','abc@gmail.com'] |And print tableObj

yaml- YAML is a human interaction oriented data serialization language. JSON, another data serialization language, is a tight superset of it.
To know more about yaml, refer this blog.

In exceptional cases, the yaml type cast keyword can be used to convert a YAML string to JSON.

The text in the example below is actually a yaml payload. Assigning a defined reference variable with the “yaml” variable type is used to type cast this payload.

Feature: Type definition DemoScenario: Define a YamlAnd text yaml_example ="""doe: "a deer, a female deer"ray: "a drop of golden sun"pi: 3.14159xmas: truefrench-hens: 3calling-birds:- huey- dewey- louie- fredxmas-fifth-day:calling-birds: fourfrench-hens: 3golden-rings: 5partridges:count: 1location: "a pear tree"turtle-doves: two"""And yaml yaml_example = yaml_exampleAnd print yaml_example

csv- It is used to convert a string that is in CSV(Comma Separated Values) format into JSON.

Feature: Type definition DemoScenario: Define a csvAnd text csvExample ="""S.no,name,e-mail1,'meesha','meesh@email.com'2,'abhilasha','ab@email.com'3,'arav','arav123@email.com'"""And csv csvObject = csvExampleAnd print csvObject

copy- As the name implies, this keyword is used to duplicate a payload to a variable reference.

Copy can be used in situations where a change to the payload is requested while preserving a copy of the original payload for matching/assertion/reference purposes.

A JSON, XML, Map or List can be copied to a reference variable.

Feature: Type definition DemoScenario: Define a copyGiven url "https://reqres.in"And path "api/users/2"When method GetThen status 200# Create a copy of original responseAnd copy response_copy = response# Remove support section from original responseAnd remove response.supportAnd print response_copyAnd print response

For more example, refer this feature file.

It’s time for me to wrap up this blog, anticipating that the examples presented have helped you understand the various types of variables and their type conversions. Stay tuned for more karate DSL concepts in upcoming blogs.

Please share your thoughts in the comments section below and be sure to click the Follow button to stay updated with the latest blogs. You may find me on LinkedIn as well.

Keep yourself safe and happy learning!!!

Until then, Sayonara!! 😃

--

--

Priyanka Brahmane

AM SDET Automation @M&G | QA Lead @ MyGlamm | QA Automation engineer @ Ex-Paytm Insider| Ex-Automation Tester @ Reliance Jio Infocomm Ltd. | Ex-Software Develop