Check value extracted with JSONPath and compare with regex using Gatling - regex

Is there a way of doing something like this in Gatling:
scenario("Check UUID with regex")
.exec(http("Get UUID")
.get("http://myapp/api/v1/goal/a24e210c-0fc1-44a0-a5ca-9bd5d8d71916")
.check(jsonPath("$.id").is(regex("[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}")))
Basically I want to apply a regex comparison on something returned in a check JSONPath construct.
Peace out!
P.S. I know I can do:
.check(regex("\"id\": \"[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}\"").exists)

There's nothing quite like what you describe, but you can kind of fake it using a transform
.check(jsonPath("$.id")
.find
.transform(id => "[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}".r
.findFirstMatchIn(id) match {
case Some(value) => true
case None => false
}
).is(true)
but if the straight regex check works... I'd go with that

Related

One-liner to extract domain from email address

How to optionally extract domain from local-part#domain? My attempt is
Try(email.split("#")(1)).toOption
but seems there should be a way without depending on exception handling. Ideally, I am after one-liner.
Not one liner, and only works on 2.13. But this seems very clear to me.
def extractDomain(email: String): Option[String] = email match {
case s"${_}#${domain}" => Some(domain)
case _ => None
}
(Note, if there are more than one # sign, this will just split on the first one).
email.dropWhile(_ != '#').drop(1)
email.split("#").lastOption
These are equivalent ONLY if what's passed is an email address.
If the string passed doesn't include # then lastOption will still return a Some() of the entire string, whereas your solution will return a None.
So if you can trust your input then this answer provides a cleaner approach.
You can use Some(email.split("#")(1)), this will split the String and then wrap in Some, which is instance of Option.
Let me cheat a little: I will prepare separate file Email.scala with extractor:
object Email{
def unapply(mail: String): Option[(String, String)] = {
mail match {
case s"$user#$domain" => Some(user, domain)
case _ => None
}
}
}
and then it can be used with pattern matching:
val Email(_, domain) = "test#domain.com"
Not a one-liner, but I always match on array extractors when I do String.split (pre-2.13), I think it's short enough and reads much better than getting parts by index.
email.split("#", 2) match {
case Array(_, domainPart # _*) => domainPart.headOption
}
limit = 2 makes sure that domainPart has at most 1 element.
Note you don't need a catch-all in this case, since split will always return at least one value in the array (although makes sense to cover it with tests to protect against future changes).

How to match specific string in ROBOT FRAMEWORK using regex?

I am using REST-API for testing
I am stuck where I am checking the response with some specific string.
please refer below info
I got the response from a request is
{
"clusters":[
{
"id":10,
"name":"HP2",
"status":2,
"statusDisplay":"HParihar#4info.com",
"lastModifiedBy":"HParihar#4info.com",
"lastModifiedTime":"06/08/2017 23:42",
"sitesAppsCount":0
},
{
"id":799,
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"lastModifiedBy":"admin#4info.net",
"lastModifiedTime":"07/11/2017 08:19",
"sitesAppsCount":0
}
]}
and I wanted to match just
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"sitesAppsCount":0
right side values I'll be keeping as hard coded.
any guesses?
Since you are only checking those 4 parameters are in response or not.
Do no use regex for this.
Use jsonObject's find key/value feature.
Check whether the values to the keys are there.
If key/value is null, the parameter is not in response.
I got my answer
I used the following regex
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net","lastModifiedBy":"[a-z]+#[0-9a-z]+\.[a-z]+","lastModifiedTime":"[0-9]{2}\/[0-9]{2}\/[0-9]{4}\ [0-9]{2}:[0-9]{2}","sitesAppsCount":0
or I can simply use
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net",.+"sitesAppsCount":0
thank you all

Regex JSON response Gatling stress tool

Wanting to capture a variable called scanNumber in the http response loking like this:
{"resultCode":"SUCCESS","errorCode":null,"errorMessage":null,"profile":{"fullName":"TestFirstName TestMiddleName TestLastName","memberships":[{"name":"UA Gold Partner","number":"123-456-123-123","scanNumber":"123-456-123-123"}]}}
How can I do this with a regular experssion?
The tool I am using is Gatling stress tool (with the Scala DSL)
I have tried to do it like this:
.check(jsonPath("""${scanNumber}""").saveAs("scanNr")))
But I get the error:
---- Errors --------------------------------------------------------------------
> Check extractor resolution crashed: No attribute named 'scanNu 5 (100,0%)
mber' is defined
You were close first time.
What you actually want is:
.check(jsonPath("""$..scanNumber""").saveAs("scanNr")))
or possibly:
.check(jsonPath("""$.profile.memberships[0].scanNumber""").saveAs("scanNr")))
Note that this uses jsonPath, not regular expressions. JsonPath should more reliable than regex for this.
Check out the JsonPath spec for more advanced usage.
use this regex to match this in anywhere in json:
/"scanNumber":"[^"]+"/
and if you want to match just happens in structure you said use:
/\{[^{[]+\{[^{[]+\[\{[^{[]*("scanNumber":"[^"]+")/
Since json fields may change its order you should make your regex more tolerant for those changes:
val j = """{"resultCode":"SUCCESS","errorCode":null,"errorMessage":null,"profile":{"fullName":"TestFirstName TestMiddleName TestLastName","memberships":[{"name":"UA Gold Partner","number":"123-456-123-123","scanNumber":"123-456-123-123"}]}}"""
val scanNumberRegx = """\{.*"memberships":\[\{.*"scanNumber":"([^"]*)".*""".r
val scanNumberRegx(scanNumber) = j
scanNumber //String = 123-456-123-123
This will work even if the json fields will be in different order (but of course keep the structure)

MongoDB findOne with regex (security flaw?)

Before i insert the email into the database -> i validate the adress with
if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
{
....
}
.. but is this maybe a security flaw?
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
Schould i do this? or is it not necessary?
$emailAdress= preg_replace("/\#/", '\#', $emailAdress);
$emailAdress= preg_replace("/\-/", '\-', $emailAdress);
$emailAdress= preg_replace("/\./", '\.', $emailAdress);
if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
Is a good way to vlaidate an email address in PHP, however, it does use regexes but so far, those have proven to be the best.
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
The only real problem with that is the . which is a special character which will effect how the regex works, but do you really need to do a regex here? You have checked it is a full email address as such you just need to check for where that exact email address exists (or better yet make a unique index on the field).
As I such I think you can take out the regex and do an exact match.

How to write this Regular Expression

How do i write a regular expression which accepts only value "1" in the textbox
and it should not accept zero or greter than "1"
if (theTextBoxValue == "1") {
// accept
} else {
// reject
}
You don't need regex for this simple task. And, if you only accept "1" in a user input, why provide such an input to the user at all?
/^1$/
… but for a "Must be this value, exactly this value, and nothing but this value" test, you would be much better off with a simple string comparison.
/^1$/ but a simple == "1" will be enough in most languages (or .equals("1")).
I saw your previous question (using the jquery validationEngine), and I was intrigued by it so I started looking.
The problem with using a funcCall (as you were trying in the old post) is that the function is called without any context (has no arguments, and has this == window), so you can't tell which input field is being validated.(I solved this with a trick - see example & comments linked below).
Another solution I found was using regex(as you are trying now).
This is the entry you have to add to the languages file:
"isOne":{
"regex":"/^1$/",
"alertText":"* Only '1' is valid [regex]"
}
This is how you use it on the input field:
<input type="text" class="validate[custom[isOne]]">
And this is how you start the validation engine:
$('#form').validationEngine({
validationEventTriggers:"change"
});
You can view a working example using both function and regex here
Don't think you want to use regex for this.
Pattern: ^1$