Skip to content

Latest commit

 

History

History
1068 lines (782 loc) · 24.8 KB

expressions.adoc

File metadata and controls

1068 lines (782 loc) · 24.8 KB

Expressions

VIVIDUS provides a set of pre-defined expressions. Also plugins may define own expressions (they are documented in the corresponding plugins articles).

Note
The expression parameters marked with bold are mandatory.

Data generation

generate

Generates random data from various domain areas.

#{generate(<expression>)}
  • $expression - one of the data providers, its dot-separated method and space separated parameters wrapped into single quptes (for majority of cases parameters are not needed, their number and possible values depend on the chosen data provider method).

Below you can find a complete list of the supported expressions with results exmaples. Descriptions of the data providers and their parameters can be found in DataFaker documentation: click on the data provider name to find details.

Click here to view the complete list of the supported expressions

Let’s see the structure of the expression for the following example:

#{generate(Internet.password '5', '10', 'true')}
#{generate                                       (1)
          (Internet                              (2)
                   .password                     (3)
                             '5',                (4)
                                  '10',          (4)
                                        'true')} (4)
  1. Generate expression itself.

  2. Data provider from the list. In this case - Internet. Click on its name to see the methods it contains.

  3. One of the available methods within Internet data provider - password. There are multiple choices, we picked the fourth one.

  4. Available parameters for the chosen method.

    There are three of them:

    • int minimumLength - minimum number of symbols;

    • int maximumLength - maximum number of symbols;

    • boolean includeUppercase - true or false for Uppercase usage;

In this way we created an expression that generates a password from 5 to 10 characters length including uppercase letters.
Possible output is 51gVj5aLZY

letterify

Replaces ? symbols with latin letters.

#{generate(letterify '$input', '$isUpperCase')}
  • $input - any string containing ? symbols to be replaced with letters

  • $isUpperCase - boolean, set it to true for uppercase option

Table 1. letterify examples
Expression Result
#{generate(letterify 'test????test')}

testnjmytest

#{generate(letterify 'test????test', 'true')}

testXQBMtest

numerify

Replaces # symbols with numbers.

#{generate(numerify '$input')}
  • $input - any string containing # symbols to be replaced with numbers

Table 2. numerify example
Expression Result
#{generate(numerify 'test####test')}

test5862test

bothify

Combination of letterify and numerify.

#{generate(bothify '$input')}
  • $input - any string containing # and ? symbols to be replaced with numbers and letters accordingly

Table 3. bothify example
Expression Result
#{generate(bothify 'test#?#?#?#test')}

test2o7v0g9test

templatify

Replaces symbol mentioned in the second argument with one of the symbols mentioned after it.

#{generate(templatify '$input', '$whatToReplace', '$replacement1', '$replacement2', '$replacement3')}
  • $input - any string to process

  • $whatToReplace - part of the string to be replaced

  • $replacement - replacement to use. Possible to use multiple options

Table 4. templatify example
Expression Result
#{generate(templatify 'VIVIDUS', 'I', 'X', 'P')}`

VPVPDUS

VXVPDUS

VPVXDUS

VXVXDUS

examplify

Replaces symbols by example: uppercase with uppercase, digit with digit, lowercase with lowercase.

#{generate(examplify '$input')}
  • $input - any string to process

Table 5. examplify example
Expression Result
#{generate(examplify 'V1V1DUs')}

R9Q7VTq

regexify

Allows generating output based on regular expression.

#{generate(regexify '$regularExpression')}
  • $regularExpression - regular expression that describes desired output

Table 6. regexify example
Expression Result
#{generate(regexify '\d{3}\w{1}')}

409Y

#{generate(regexify '[A-Z]{3}[a-z]{4}[2-8]{5}')}

PQUlxdq66436

options

Returns any of provided items.

#{generate(options.option '$item1', '$item2', '$item3')}
  • $item - option to choose from

Table 7. options example
Expression Result
#{generate(options.option 'V','I','V','I','D','U','S')}

S

generate JSON

Generates JSON based on key-value pairs input.

#{generate(json '$key1', '$value1', '$key2', '$value2')}
Table 8. generate JSON example
Expression Result
#{generate(json 'first_name','Bob','last_name','Dylan','profession','singer')}
{"first_name": "Bob", "last_name": "Dylan", "profession": "singer"}

generate CSV

Generates comma-separated values based on input.

#{generate(csv, '$rowsNumber' '$columnName1', '$value1', '$columnName2', '$value2')}
  • $rowsNumber - number of rows to fill in

  • $columnName1 - name of the first column

  • $value1 - data to enter the first column

  • $columnName2 - name of the second column

  • $value2 - data to enter the second column

Table 9. generate CSV example
Expression Result
#{generate(csv '3', 'first_name','Bob','last_name','Dylan')}
"first_name","last_name"
"Bob","Dylan"
"Bob","Dylan"
"Bob","Dylan"

randomInt

Generates a random integer value between the specified origin (minInclusive) and the specified bound (maxInclusive).

#{randomInt($minInclusive, $maxInclusive)}
  • $minInclusive - the least value

  • $maxInclusive - the upper bound

Table 10. Examples of the expressions generating random integer value
Expression Result

#{randomInt(1, 10)}

An integer between 1 and 10

#{randomInt(100, 999)}

An integer between 100 and 999

#{randomInt(-5, 5)}

An integer between -5 and 5

#{randomInt(-5, -2)}

An integer between -5 and -2

#{randomInt(1, 1)}

1

Math calculations

round

Rounds a number with an approximate value based on specific rounding definitions.

#{round($value, $maxFractionDigits, $roundingMode)}
  • $value - any number to be processed

  • $maxFractionDigits - maximum number of digits after the decimal separator

  • $roundingMode - specifies a rounding behavior for numerical operations (more information here):

    Rouding Mode Readable Description

    UP

    up

    Rounds away from zero.

    DOWN

    down

    Rounds towards zero.

    CEILING

    ceiling

    Rounds towards positive infinity.

    FLOOR

    floor

    Rounds towards negative infinity.

    HALF_UP

    half up

    Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

    HALF_DOWN

    half down

    Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.

    HALF_EVEN

    half even

    Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

    UNNECESSARY

    unnecessary

    Asserts that the requested operation has an exact result, hence no rounding is necessary.

Table 11. Examples of rounding operations with different parameters
Expression Result

#{round(5.0)}

5

#{round(-5.9, 0)}

-6

#{round(5.551, 2)}

5.55

#{round(1.4, 0, ceiling)}

2

#{round(-1.4, 0, floor)}

-2

#{round(-5.5555, 3, half up)}

-5.556

#{round(-5.555, 2, half down)}

-5.55

#{round(-5.5, 0, half even)}

-6

#{round(-1.1, 2, unnecessary)}

-1.1

String manipulations

replaceFirstByRegExp / replaceAllByRegExp

Replaces the first / every substring of the input that matches the regular expression with the given replacement string.

Tip

Online tools like RegexPlanet or Regex101 can be used to test and debug regular expressions

#{replaceFirstByRegExp($regularExpression, $replacement, $input)}
#{replaceAllByRegExp($regularExpression, $replacement, $input)}
  • $regularExpression - the regular expression to match substring(s)

  • $replacement - the replacement string, it may contain references to captured substrings, e.g. $1 is a reference to the first group

  • $input - any string to be processed

Note
The expression parameters containing commas or empty values must be surrounded with triple quotes: """
Description Expression Result

Extract ID from the string

#{replaceFirstByRegExp(product-(\d+), $1, product-86)}

86

Extract ID and build new string with it

#{replaceFirstByRegExp(/user/(\d+), author/$1, /user/21)}

author/21

Extract password from the string with comma

#{replaceFirstByRegExp(.*new password is (.*), $1, """Updated, new password is qwe123""")}

qwe123

Replace whitespaces with dashes

#{replaceAllByRegExp(\s, -, convert spaces to dashes)}

convert-spaces-to-dashes

Remove all numbers from the string

#{replaceAllByRegExp(\d, """""", a1b2c3d)}

abcd

Replace all whitespaces with commas

#{replaceAllByRegExp(\s, """,""", string with spaces)}

string,with,spaces

Replace all whitespaces with commas

#{replaceAllByRegExp(\s, \,, string with spaces)}

string,with,spaces

Replace all commas with underscores

#{replaceAllByRegExp(\,, _, string,with,commas)}

string_with_commas

Replace all commas with underscores

#{replaceAllByRegExp(""",""", _, string,with,commas)}

string_with_commas

Replace all commas with underscores

#{replaceAllByRegExp(\,, _, """string,with,commas""")}

string_with_commas

Replace all commas with underscores

#{replaceAllByRegExp(\,, _, string\,with\,commas)}

string_with_commas

Replace the first whitespace with comma

#{replaceFirstByRegExp(\s, """,""", string with spaces)}

string,with spaces

Replace the first whitespace with comma

#{replaceFirstByRegExp(\s, \,, string with spaces)}

string,with spaces

Replace the first comma with underscore

#{replaceFirstByRegExp(\,, _, string,with,commas)}

string_with,commas

Replace the first comma with underscore

#{replaceFirstByRegExp(""",""", _, string,with,commas)}

string_with,commas

Replace the first comma with underscore

#{replaceFirstByRegExp(\,, _, """string,with,commas""")}

string_with,commas

Replace the first comma with underscore

#{replaceFirstByRegExp(\,, _, string\,with\,commas)}

string_with,commas

toLowerCase

Converts an input string to lower case.

#{toLowerCase($input)}
  • $input - any string to be converted lower case

Table 12. Examples of the expressions converting strings to lower case
Expression Result

#{toLowerCase(aBc)}

abc

toUpperCase

Converts an input string to upper case.

#{toUpperCase($input)}
  • $input - any string to be converted upper case

Table 13. Examples of the expressions converting strings to upper case
Expression Result

#{toUpperCase(aBc)}

ABC

capitalizeFirstWord

Capitalizes an input string, changing the first character to title case. No other characters are changed.

#{capitalizeFirstWord($input)}
  • $input - any string to be capitalized

Table 14. Examples of the expressions capitalizing strings
Expression Result

#{capitalizeFirstWord(aBc)}

ABc

capitalizeWords

Capitalizes all the whitespace separated words in the input string. Only the first character of each word is changed.

#{capitalizeWords($input)}
  • $input - any string to be capitalized

Table 15. Examples of the expressions capitalizing words in the string
Expression Result

#{capitalizeWords(aBc dEf)}

ABc DEf

capitalizeWordsFully

Converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.

#{capitalizeWordsFully($input)}
  • $input - any string to be capitalized

Table 16. Examples of the expressions capitalizing strings
Expression Result

#{capitalizeWordsFully(aBc dEf)}

Abc Def

uncapitalizeFirstWord

Uncapitalizes an input string, changing the first character to title case. No other characters are changed.

#{uncapitalizeFirstWord($input)}
  • $input - any string to be capitalized

Table 17. Examples of the expressions capitalizing strings
Expression Result

#{uncapitalizeFirstWord(ABc)}

aBc

uncapitalizeWords

Uncapitalizes all the whitespace separated words in the input string. Only the first character of each word is changed.

#{uncapitalizeWords($input)}
  • $input - any string to be capitalized

Table 18. Examples of the expressions capitalizing words in the string
Expression Result

#{uncapitalizeWords(ABc DEf)}

aBc eEf

trim

Trims an input string (removes control characters (chars with code less than or equal to 32) from both ends).

#{trim($input)}
  • $input - any string to be trimmed

Table 19. Examples of the expressions trimming strings
Expression Result

#{trim( a b c )}

a b c

substringBefore

Gets the substring before the first occurrence of a separator. The separator is not included in the result.

#{substringBefore($input, $separator)}
  • $input - any string to get a substring from

  • $separator - the string to search for

Tip
Since the arguments of the expression are comma-separated, meaningful commas (in $input or/and $separator) must be escaped with \
Table 20. Examples of the expressions getting the substring
Expression Result

#{substringBefore(, a)}

#{substringBefore(abc, a)}

#{substringBefore(abcba, b)}

a

#{substringBefore(abcba,b)}

a

#{substringBefore(abc, c)}

ab

#{substringBefore(abc, d)}

abc

#{substringBefore(abc, )}

#{substringBefore(a\,b\,c\,b\,a, c)}

a,b,

substringAfter

Gets the substring after the first occurrence of a separator. The separator is not included in the result.

#{substringAfter($input, $separator)}
  • $input - any string to get a substring from

  • $separator - the string to search for

Tip
Since the arguments of the expression are comma-separated, meaningful commas (in $input or/and $separator) must be escaped with \
Table 21. Examples of the expressions getting the substring
Expression Result

#{substringAfter(, a)}

#{substringAfter(abc, a)}

bc

#{substringAfter(abcba, b)}

cba

#{substringAfter(abcba,b)}

cba

#{substringAfter(abc, c)}

#{substringAfter(abc, d)}

#{substringAfter(abc, )}

abc

#{substringAfter(a\,b\,c\,b\,a, c)}

,b,a

encodeToBase64

Encode the input string to Base64 format

#{encodeToBase64($input)}
  • $input - any string to be encoded to Base64 format

Table 22. Examples of the expressions encoding to Base64
Expression Result

#{encodeToBase64(vividus)}

dml2aWR1cw==

decodeFromBase64

Decodes the input string from Base64 format to the regular string

#{decodeFromBase64($input)}
  • $input - Base64 string to decode

Table 23. Examples of the expressions decoding Base64
Expression Result

#{decodeFromBase64(dml2aWR1cw==)}

vividus

toBase64Gzip

Compress the input string to GZip and encode compressed bytes to Base64 format

#{toBase64Gzip($input)}
  • $input - any string to be compressed and encoded

Table 24. Examples of the expressions compressing and encoding to Base64 GZip
Expression Result

#{toBase64Gzip(vividus)}

H4sIAAAAAAAAACvLLMtMKS0GANIHCdkHAAAA

escapeHTML

Escapes reserved characters in HTML string

#{escapeHTML($input)}
  • $input - any string to be escaped

Table 25. Escape HTML string
Expression Result

#{escapeHTML(M&Ms)}

M&Ms

escapeJSON

Escapes reserved JSON characters: converts any string into one that’s properly escaped for inclusion in JSON as a value.

#{escapeJSON($input)}
  • $input - any string to be escaped

Table 26. Escape JSON string
Expression Result

#{escapeJSON("abc"+"xyz")}

\"abc\"+\"xyz\"

quoteRegExp

Quotes the input literal so that metacharacters or escape sequences in the input sequence will be given no special meaning in regular expression.

#{quoteRegExp($input)}
  • $input - any string to be quoted

Table 27. Quote regular expression
Expression Result

#{quoteRegExp(Some(Value))}

\QSome(Value)\E

Verify the data
Then `${frontEndData}` matches `#{quorePattern(${backEndData})}.*`

Hash calculations

calculateHash

Calculates the hash using the specified hashing algorithm

#{calculateHash($algorithm, $input)}
Table 28. Example of hash calculating for string using MD5
Expression Result

#{calculateHash(MD5, vividus)}

0a05ba6064ae7e5d6ee9818f85b666ad

#{calculateHash(SHA256, with,comma)}

f93dcfd6fc4c91c058177af3b5de34090073f2cc4a658010609ed8778d6d89f3

#{calculateHash(SHA256, with\,comma)}

f93dcfd6fc4c91c058177af3b5de34090073f2cc4a658010609ed8778d6d89f3

calculateFileHash

Calculates the resource or file hash using the specified hashing algorithm

#{calculateFileHash($algorithm, $resourceNameOrFilePath)}
Table 29. Example of hash calculating for file using SHA-1
Expression Result

#{calculateFileHash(SHA-1, data/file.txt)}

0a05ba6064ae7e5d6ee9818f85b666ad

Resources

loadResource

Loads the resource by its name and replaces the expression with the content of the resource.

#{loadResource($resourceName)}
  • $resourceName - the name of the resource to load

Load data from the project resource
Given I initialize scenario variable `my-data` with value `#{loadResource(/data/body.txt)}`

loadBinaryResource

Loads the resource by its name as bytes. It could be useful for the steps that accepting raw binary data.

#{loadBinaryResource($resourceName)}
  • $resourceName - the name of the resource to load

Load data from the project resource as bytes
When I mock HTTP responses with request URL which CONTAINS `frames.html` using response code `200`, content `#{loadBinaryResource(page.html)}` and headers:
|name        |value    |
|Content-Type|text/html|

resourceToBase64

Finds the resource by its name and replaces the expression with the content of the resource in Base64 format.

#{resourceToBase64($resourceName)}
  • $resourceName - the name of the resource to load

Load data as Base64 from the project resource
Given I initialize scenario variable `my-data` with value `#{resourceToBase64(/data/body.txt)}`

Script evaluation

eval

Evaluates JEXL script and converts result to a string.

#{eval($script)}
  • $script - valid JEXL script to be evaluated

  • Any Vividus variable is accessible in the JEXL script by its name

Evaluate JEXL script
Scenario: Verify eval expression
Then `#{<expression>}` is = `<expected>`
Examples:
|expected          |expression                                                        |
|null              |eval(null)                                                        |
|28                |eval(16 + 2 * 6)                                                  |
|10                |eval(math:abs(-10))                                               |
|here              |eval(stringUtils:substringAfterLast('namescpaces are %here', '%'))|
|108               |eval((16 + 2) * 6)                                                |
|-6                |eval(100 / 5 - 16 * 2 + 6)                                        |
|true              |eval(`string\n1` == `string\n1`)                                  |
|false             |eval(`string\n1` == `string1`)                                    |
|I Am FINE         |eval(wordUtils:capitalize('i am FINE'))                           |
|i am fINE         |eval(wordUtils:uncapitalize('I Am FINE'))                         |
|tHE DOG HAS A bone|eval(wordUtils:swapCase('The dog has a BONE'))                    |
|FRD               |eval(wordUtils:initials('Fus Ro Dah'))                            |

evalGroovy

Evaluates groovy script and converts result to a string.

#{evalGroovy($script)}
  • $script - valid Groovy script to be evaluated

Tip
  • Any Vividus variable is accessible in the groovy script by its name

  • One could use any of online groovy evaluators to verify the script. For example see: Evaluator

Evaluate Groovy script
When I initialize Scenario variable `listOfMaps` with values:
|key|
|2  |
|1  |
|3  |
Then `1-2-3` is = `#{evalGroovy(return listOfMaps.collect{it['key']}.sort().join('-'))}`

Null value

null

Represents null (a.k.a. NULL). In most case null means no value (see NULL in SQL and null in JSON).

#{null}
Note
Null expression can only be evaluated separately. Strings or other expressions with the nested null expression will be completely ignored and not executed.
Validation of JSON element with null value
Given I initialize scenario variable `json` with value `
{
    "persons": {
        "nemo": null
    }
}
`
Then JSON element value from `${json}` by JSON path `$.persons.nemo` is equal to `#{null}`