Karate - String concatenation of JSON value with a variable [duplicate] - karate

The embedded expressions are not replaced when appended, prepended or surrounded by characters in the following simplified and very basic scenario:
* def jobId = '0001'
* def out =
"""
{
"jobId": "#(jobId)",
"outputMetadata": {
"fileName_OK": "#(jobId)",
"fileName_Fail_1": "some_text_#(jobId)",
"fileName_Fail_2": "#(jobId)-and-some-more-text",
"fileName_Fail_3": "prepend #(jobId) and append"
}
}
"""
* print out
Executing the scenario returns:
{
"jobId": "0001",
"outputMetadata": {
"fileName_OK": "0001",
"fileName_Fail_1": "some_text_#(jobId)",
"fileName_Fail_2": "#(jobId)-and-some-more-text",
"fileName_Fail_3": "prepend #(jobId) and append"
}
}
Is it a feature, a limitation, or a bug? Or, did I miss something?

This is as designed ! You can do this:
"fileName_Fail_2": "#(jobId + '-and-some-more-text')"
Any valid JS expression can be stuffed into an embedded expression, so this is not a limitation. And this works only within JSON string values or when the entire RHS is a string within quotes and keeps the parsing simple. Hope that helps !

Related

Do strings need to be escaped inside parametrized queries?

I'm discovering Express by creating a simple CRUD without ORM.
Issue is, I'm not able to find any record through the Model.findBy() function
model User {
static async findBy(payload) {
try {
let attr = Object.keys(payload)[0]
let value = Object.values(payload)[0]
let user = await pool.query(
`SELECT * from users WHERE $1::text = $2::text LIMIT 1;`,
[attr, value]
);
return user.rows; // empty :-(
} catch (err) {
throw err
}
}
}
User.findBy({ email: 'foo#bar.baz' }).then(console.log);
User.findBy({ name: 'Foo' }).then(console.log);
I've no issue using psql if I surround $2::text by single quote ' like:
SELECT * FROM users WHERE email = 'foo#bar.baz' LIMIT 1;
Though that's not possible inside parametrized queries. I've tried stuff like '($2::text)' (and escaped variations), but that looks far from what the documentation recommends.
I must be missing something. Is the emptiness of user.rows related to the way I fetch attr & value ? Or maybe, is some kind of escape required when passing string parameters ?
"Answer":
As stated in the comment section, issue isn't related to string escape, but to dynamic column names.
Column names are not identifiers, and therefore cannot be dynamically set using a query parameter.
See: https://stackoverflow.com/a/50813577/11509906

Replace Json key in Karate [duplicate]

This question already has an answer here:
Karate API function/keyword to substitute JSON placeholder key with argument passed
(1 answer)
Closed 1 year ago.
I need to send a Json to an endpoint but I need to replace a key with a variable.
I've this code
.....
* def idJson = response.id
Given path <mypath>
And headers {Authorization: '#(auth)'}
And request read('classpath:myjson.json')
.....
The myjson.json file is
{
"a":
{
...
"b":false,
"c":true
},
"d":
{
'#(idJson)':
{
"Key":[
.....
]
}
}
}
But the value is not replace in the json. When I perform the request I see that the json contains the string '#(idJson)' instead of the value of the variable. Any idea about how to solve this?
Thank you
Embedded expressions cannot be used to modify a JSON key. You have to use a JS operation like this:
* def idJson = 'foo'
* def body = {}
* body[idJson] = 'bar'
* url 'https://httpbin.org/anything'
* request body
* method post
* status 200
* match response.json == { foo: 'bar' }
Note that d could be replaced like this so you can still read the file and be dynamic:
{ "d": "#(temp)" }
And temp can be JSON that is defined in your feature before reading the file.
If this is too troublesome, please contribute code :)

How to get the value of JSON element having # in the name in Karate [duplicate]

This question already has an answer here:
Get json value with hyphen from response
(1 answer)
Closed 1 year ago.
This is my json response
{
"meta": {
"type": "event-search",
"#href": "https://<ip>:<port>/SentinelRESTServices/objects/event-search/10c21c52229bfe0545BD7802A74E10398534005056869AAA"
}
}
I want to get the value for #href.
When i print meta.type I am able to get the value 'event-search', but same doesn't work for #href.
I tried to escape it using \\ (meta.\\#href) but i got empty value.
Is there a way to escape # and fetch the value?
Please help!!
Please use the square-bracket JS approach to extract nested properties when there are special characters in the key-names.
Example:
* def response = { meta: { '#href': 'foo' } }
* match response.meta['#href'] == 'foo'

Embedded expressions not replaced if surrounded by dot and underscores in it

The embedded expressions are not replaced when appended, prepended or surrounded by characters in the following way
* def RADName = 'IntegrationFirstRAD'
* def tenantID = '1452119626'
* def out =
"""
{
"nsName": "fld_<tenantID>_stage00.rad.<RADName>_.resources:<RADName>_resource"
}
"""
* print out
Executing the scenario returns:
"nsName":"fld_1452119626_stage00.rad.<RADName>_.resources:<RADName>_resource
In the above scenario 'RADName' is not replaced with the value
Please use the replace keyword:
* def out = { nsName: 'fld_<tenantID>_stage00.rad.<RADName>_.resources:<RADName>_resource' }
* replace out.RADName = 'IntegrationFirstRAD'
* replace out.tenantID = '1452119626'
* match out == { "nsName": "fld_1452119626_stage00.rad.IntegrationFirstRAD_.resources:IntegrationFirstRAD_resource" }
You seem to be confused between embedded expressions and Scenario Outlines.
I guess it is worth saying this again, you really really really should read the documentation fully once.

Gradle Single vs Double Quotes

I'm new to gradle and am currently just trying to follow the tutorials and quite a few times I've seen single and double quotes intermixed. I just wanted to know if there was a difference of when one set should be used over the other. One example of this is section 6.12 of the tutorial - Default tasks:
defaultTasks 'clean', 'run'
task clean << {
println 'Default Cleaning!'
}
task run << {
println 'Default Running!'
}
task other << {
println "I'm not a default task!"
}
So, I would just like to know if I should be paying attention to these differences or if they are inter-changable and I can use either single or double quotes when printing strings in gradle.
Gradle build scripts are written in Groovy. Groovy has both double-quoted and single-quoted String literals. The main difference is that double-quoted String literals support String interpolation:
def x = 10
println "result is $x" // prints: result is 10
You can learn more about Groovy String interpolation in this or other Groovy articles on the web.
Yes, you can use one or the other. The only difference is that double-quoted strings can be GStrings, which can contain evaluated expressions like in the following example taken from the Groovy documentation:
foxtype = 'quick'
foxcolor = ['b', 'r', 'o', 'w', 'n']
println "The $foxtype ${foxcolor.join()} fox"
// => The quick brown fox
According to the gradle docs:
Favor single quotes for plain strings in build script listings
This is
mostly to ensure consistency across guides, but single quotes are also
a little less noisy than double quotes. Only use double quotes if you
want to include an embedded expression in the string.
Single-quoted strings are a series of characters surrounded by single quotes.
like :
def str='a single quoted string'
println str
Ouput :
a single quoted string
Whereas Double-quoted strings allow us the String interpolation
Here, we have a string with a placeholder referencing a local variable:
def name = 'Guillaume' // a plain string
def greeting = "Hello ${name}"
Output : Hello Guillaume
In your code,If you want to print the task name. So in that case, you need to use Double-quotes:
defaultTasks 'clean', 'run'
task clean << {
println 'Default Cleaning!'
}
task run << {
println "Default Running $run.name!"
// here Double Quotes are required to interpolate task-name
}
task other << {
println "I'm not a default task!"
}
Kotlin DSL files (like build.gradle.kts or settings.gradle.kts) are regular Kotlin code.
So, string literals are always wrapped in double quotes:
val myFirstString = "4 / 2 equals ${4 / 2}"
val mySecondString = """The property "hide" was not found"""