Postman test case insetitive - postman

I have a test case in the Postman which looks like:
pm.test("Last Name contains Bob", () => {
const responseJson = pm.response.json();
pm.response.to.have.status(200);
pm.response.json().result.length >= 1;
pm.expect(responseJson.result[0].last_name).to.include.a("Bob");
});
but that fail for a result which has BOBBY as last_name
I thought that by adding a to the assertion it will became case insensitive.
So what I'm doing wrong?

Solution for my case wast to use match with Regex
pm.test("Last Name contains Bob", () => {
const responseJson = pm.response.json();
pm.response.to.have.status(200);
pm.response.json().result.length >= 1;
pm.expect(responseJson.result[0].last_name).to.match(\Bob\gmi);
});

This works for me:
pm.expect(someprop.toLowerCase()).to.include("<some_lower_case_string>");

Related

Postman test is always passing even though it fails

While running postman Tests, Test case seems to be always passing
The response body is provided below. I am trying to fetch id when the name is "Erin" and validate that id is 800. Small piece of code that i wrote is below the response body written below.FOr some reason the test always returns true. If for some reason if Erin and 800 are not present still it passes the test.
[
{
"id":991,
"name":"Tomy"
},
{
"id":800,
"name":"Erin"
}
]
Code:
pm.test("Validate id to be 800", function() {
var jsonData = pm.response.json();
for(int i=0; i<responseJson.length;i++){
if(jsonData[i].name=='Erin'){
pm.expect(jsonData[i].id).to.eql(800);
}
}
});
Updated the response a bit a below , i wanted my test to fail as "Jack" is
not found and to pass only if Jack is found
pm.test("Validate id to be 800", function () {
let jsonData = pm.response.json();
for(i=0; i < jsonData.length; i++) {
if(jsonData[i].name == 'Jack') {
pm.expect(jsonData[i].id).to.eql(800);
}
}
});
That response body doesn't look quite right to me, I would expect to see quotes around the property keys in the objects.
Also, your references were not named correctly and that would pass the test as it wouldn't have caused any reference errors in the scripts.
This should help you out:
pm.test("Validate id to be 800", function () {
let jsonData = pm.response.json();
for(i=0; i < jsonData.length; i++) {
if(jsonData[i].name === 'Erin') {
pm.expect(jsonData[i].id).to.eql(800);
}
}
});
You could rewrite the test code to something like this:
pm.test("Validate id to be 800", () => {
let jsonData = pm.response.json();
jsonData.forEach(item => {
if(item.name === 'Erin') {
pm.expect(item.id).to.eql(800);
}
});
});
And the Test Results when it fails:

loopback4 Regular Expressions- Match Anything

I use loopback4. How do I make an expression to match datetime with time zone.I am interested by the hour parameter only: "finalhour"
example: 2019-12-20T10:22:50.143Z ==> 2019-12-20Tfinalhour:22:50.143Z
I tried with this: const pattern=await '^'+"T"+finalhour+'^'
but loopback usually read it as ^T10^
I'm resort to you after a long search in the forums.I will be thankful if you help me
From what i understand, you want to build a regex that match 2019-12-20TsomeNumber:22:50.143Z.
You could use this default ISO datetime regex
(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\.\d{3,4}Z
And modify it to take your finalhour variable in it.
let finalHour = 10;
// when building regex from constructor, we need to espace the backslash ( \ )
// i did not know that.
let regex = new RegExp('(\\d{4})-(\\d{2})-(\\d{2})T' + finalHour + '\\:(\\d{2})\\:(\\d{2})\\.\\d{3,4}\\Z');
let test = '2019-12-20T10:22:50.143Z';
console.log(regex.test(test));
Also, you don't need an await keyword here because your are building a string, not waiting for a promise.
I need to return the number of order per hour. so i try this solution but it return false comparison, for example if i have one order at hour:10 it return 6
#get('/orders/count-perHour/{date}', {
responses: {
'200': {
description: 'Order model count',
content: { 'application/json': { schema: CountSchema } },
},
},
})
async countPerHour(
#param.path.string('date') date: string): Promise<any> {
let dateStart = new Date(date);
dateStart.setSeconds(0);
dateStart.setMinutes(0);
let dateEnd = new Date(date);
dateEnd.setSeconds(59);
dateEnd.setMinutes(59);
return await this.orderRepository.count(
{
createdAt: {
lte: dateEnd
,
gte: dateStart
}
}
);
}

Postman API testing: Unable to assert a value is true

I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.

Scala Regex pattern matching issue when using |

This is my example code.
object Patterns {
val workingPattern = """^thisworks[\w]+""".r
val problemPattern = """^(fail|error|bs|meh)[\w]+""".r
}
object TestMaker {
var works = scala.collection.mutable.Set[String]()
var needsWork = scala.collection.mutable.Set[String]()
var junk = scala.collection.mutable.Set[String]()
def add(someInput: String) = someInput match {
case Patterns.workingPattern() => works.update(someInput, true)
case Patterns.problemPattern() => needsWork.update(someInput, true)
case _ => junk.update(someInput, true)
}
}
When I call TestMaker.add("thisworks1234"), the string "thisworks1234" gets inserted into TestMaker's works set. It works as expected.
When I call TestMaker.add("this_is_just_junk"), the string "this_is_just_junk" gets inserted into the junk set - also as expected.
Here's the problem. When I call TestMaker.add("fail1234"), that string will also be inserted into the junk set. It should however be inserted into the needsWork set.
Where's my mistake?
You should use a non-capturing group with the second regex:
val problemPattern = """^(?:fail|error|bs|meh)[\w]+""".r
^^^
This is required because you are not referencing the captured value in your case.
Note that you can still use capturing groups within your patterns to ignore them later while matching with _*:
case Patterns.workingPattern(_*) => works.update(someInput, true)
case Patterns.problemPattern(_*) => needsWork.update(someInput, true)
case _ => junk.update(someInput, true)
See the IDEONE demo:
object Main extends App {
TestMaker.add("this_is_just_junk")
TestMaker.add("fail1234")
println(TestMaker.needsWork) // => Set(fail1234)
println(TestMaker.junk) // => Set(this_is_just_junk)
}
object Patterns {
val workingPattern = """^thisworks[\w]+""".r
val problemPattern = """^(fail|error|bs|meh)[\w]+""".r
}
object TestMaker {
var works = scala.collection.mutable.Set[String]()
var needsWork = scala.collection.mutable.Set[String]()
var junk = scala.collection.mutable.Set[String]()
def add(someInput: String) = someInput match {
case Patterns.workingPattern(_*) => works.update(someInput, true)
case Patterns.problemPattern(_*) => needsWork.update(someInput, true)
case _ => junk.update(someInput, true)
}
}

Pass parameters through angularjs 2 to restful services

I am trying to call a webservice which is as follows,
#RequestMapping(value = { "/persons" },method = RequestMethod.GET,headers="Accept=application/json")
public List<Person> getDummyData(#RequestParam(value="search", defaultValue="a") String search,HttpServletRequest req){
List<Person> listOfMatchedPersons=listOfPersons.stream().filter(person->person.getName().contains(search)).collect(Collectors.toList());
req.getParameterMap().forEach((k,v)->System.out.println(k+" : "+v));
return listOfMatchedPersons;
}
I want to call this service with some parameter from my UI, but it always executes this method with default value of search i.e. a.
Following is my angularjs 2's service that is consuming this service,
search(term: string) {
var params = new URLSearchParams();
params.set('search', term);
let aopsServices = 'http://localhost:8080/dummy/persons';//?search='+term;
this.ot = this.http
.get(aopsServices,params)
.map(response => response.json())
;
return this.ot;
}
however if i change the url to http://localhost:8080/dummy/persons'?search='+term; it works.
And also what should be the ideal approach to access the restful services if they are secured ?
I see two ways to do that:
Leveraging the URLSearchParams class:
search(term: string) {
var params = new URLSearchParams();
params.set('search', term);
let aopsServices = 'http://localhost:8080/dummy/persons';
this.ot = this.http
.get(aopsServices, { search: params })
.map(response => response.json());
return this.ot;
}
Use of ` (backticks) instead of single quotes '
search(term: string) {
let aopsServices = `http://localhost:8080/dummy/persons?search=${term}`;
this.ot = this.http
.get(aopsServices, { search: params })
.map(response => response.json());
return this.ot;
}
The second approach is more concise but doesn't urlencode the parameter.
I changed my code to
var params = new URLSearchParams();
params.set('search', term);
let aopsServices = 'http://localhost:8080/dummy/persons';
this.ot = this.http
.get(aopsServices,new RequestOptions({search:params}))
.map(response => response.json());
and it worked.
I misread the documentation of get.