Restassured "OR" condition - rest-assured

I have REST for finding users by name, which for some search term returns users that has that term in first name or last name.
GET /search/joe
returns json array:
[
{"id": 1, "firstName": "Joe", "lastName": "Doe"},
{"id": 2, "firstName": "Alex", "lastName": "Joelson"}
]
How to test this REST with restassured and verify that given search term is contained in either first or last name of every row, case insensitive?
given()
.when()
.get("/user/search")
.then()
.statusCode(200)
.body(?)

Without a User object:
Response response = given().when().get("/user/search");
response.then().statusCode(200);
JSONArray users = new JSONArray(response.asString());
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String firstName = user.getString("firstName").toLowercase();
String lastName = user.getString("lastName").toLowercase();
Assert.assertTrue(firstName.contains("joe") || lastName.contains("joe"));
}
If you have a User object, look into using Jackson or JsonPath to make the validation simpler. You can also look into using Hamcrest to do the validations.

Related

How to correctly send array with objects in JSON Swift iOS

Hello I am beginner and trying to understand how to send an array with objects. Does the server understand what an array is like Int, Strings or Booleans? Do you have to send the array in a string for JSON? What I do not understand?
var productsResult = ""
let encoder = JSONEncoder()
let productObject = ProductUsed(name: "Custom name", reason: "This Reason", apply_way: "Intravenous infusion", dosing: "2x", date_start: "22-02-1999", date_end: "22-03-2003")
do {
let result = try encoder.encode([productObject])
if let resultString = String(data: result, encoding: .utf8) {
print(resultString)
productsResult = resultString
}
} catch {
print(error)
}
json["products_used"] = productsResult
And I sent to server with parameters like this:
parameters: ["pregnancy_week": 0, "body_height": 198, "initials": "John Appleseed", "heavy_effect": false, "sex": "Male", "pregnancy": false, "month_of_birth": 3, "reaction": "No option checked", "additional_info": "Eeee", "products_used": "[{\"date_end\":\"22-03-2003\",\"dosing\":\"2x\",\"date_start\":\"22-02-1999\",\"apply_way\":\"Intravenous infusion\",\"name\":\"Custom name\",\"reason\":\"This Reason\"}]", "description": "Eeee", "result": "Recovery without lasting consequences", "year_of_birth": 1983, "day_of_birth": 11, "issue_date": "15-11-2020", "body_weight": 78]
but printed "resultString" in log and looks good...
[{"date_end":"22-03-2003","dosing":"2x","date_start":"22-02-1999","apply_way":"Intravenous infusion","name":"Custom name","reason":"This Reason"}]
What's wrong in my code and why I have " \ " between words in "products_used" key?
JSON, unlike XML, does not specify the structure and type explicitly. This means that the server must know what JSON data to expect.
In JSON there are a few value types (https://www.w3schools.com/js/js_json_syntax.asp):
a string
a number
an array
a boolean
null
a JSON object (a dictionary with tags like { "first" : "John", "last" : "Doe" }). This allows nesting.
A JSON object is a set of tag-value pairs. The tag and value are separated by : and pairs are separated by ,.
An array is a list of JSON values. So for example [ "hello", world" ] is a JSON array with 2 strings and [ 12, 54 ] is a JSON array with two numbers.
Your parameter list ["pregnancy_week": 0, "body_height": 198, ... is not an array but a dictionary instead. A Swift dictionary is translated to an JSON object, not a JSON array.
The \ you see printed acts as escape character. This escape character is used to allow you to have a " inside the string.
That's just a few things that I hope will help understand things a bit better. Your questions are pretty basic, which is fine and it's great you want to understand things. But instead of us explaining everything here, I think it would be best if you'd read about the structure of JSON and how JSON works in Swift on your own.

How to Limit what fields are searchable in Algolia index in Swift?

My data is structured like this
firstName: String
lastName: String
username: String
userID: String
school: String
****EDIT: This is my front end code if that helps, maybe the problem lies here.
let index = client.index(withName: "Users")
index.setSettings([
"searchableAttributes": [
"firstName",
"lastName",
"username"
]
])
let query = Query(query: searchBar.text)
// query.facets = ["firstName", "username", "lastName"]
index.search(query, completionHandler: { (content, error) -> Void in
// completion handler//print results
})
When I index this, I only want to get results with the firstName, lastName, and username fields. I DO NOT want algolia to look through the userID and school fields for this particular search
I've tried changing the facets and the searchable attributes but nothing seems to change.
My results have been searching through every single field, not just the ones I specified. Maybe I just don't have a great understanding of how algolia queries work.
While indexing you should set which attributes are searchable.
index.setSettings([
"searchableAttributes": [
"firstName",
"lastName",
"username"
]
])
See this link for more details.
Although setting the searchableAttributes should work, you can also restrict your attributes
query.restrictSearchableAttributes = [
"firstName",
"lastName",
"username"
]
See this link for restricting your attributes for a query

comparing data in list of objects

I have a JSON which returning a duplicate object if it has a different value for one of the attributes, for example:
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img1.JPG",
},
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img2.JPG",
},
both of them are the same node with ID 41 and the other data are duplicated other than the unique which is news_image
The class of the object is:
String nid;
String newsTitle;
String body;
String newsImage;
List<String> newsImgs;
And am parsing it like this:
List<News> newsdata = (jsonResponse as List).map((i) => new News.fromJson(i));
Everything is fine till now .. but i have another list:
List<News> newsList = <News>[];
Where i want to add the images of the same news with the same nid to the list newsImgs and then add it to the newsList.. so i wont have duplicated news with the same nid and all of the images of the same news will be in one list
How to do this?
Try to make this list..
Set store only unique value..
Set<News> newsList= new Set();
newsList.addAll(newsdata);

DDMathParser: Parsing dynamic formula which contain $ to refer objects value within dictionary

I am struggling a little bit to use DDMathParser framework for expression requirement I have. I have JSON of fields & based on expressions certain fields can be set required, hidden or set the value of it.
Expressions in required tag in sample JSON are not fixed & so not getting how to achieve dynamic approach for expression.
[
{
"name": "firstName",
"value": "Ameer",
**"required": true**
},
{
"name": "lastName",
"value": "Shaikh",
**"required": "$firstName != ‘’"**
},
{
"name": "designation",
"value": "",
**"required": "$firstName == ‘Ameer’ && $lastName == ‘Shaikh’"**
},
{
"name": "location",
"value": "",
**"hidden": false**
}
]
Actually, expression in JSON contains $ to represent one of the
dictionary objects value from JSON. Wherein framework internally
treats it as a local variable.
These expressions may have different combinations as well. There may be several expression apart from "required" parameters. I need to run all relevant expressions for any change in value in UI.
EDIT
let expression = "$firstName == ‘Ameer’ && $lastName == ‘Shaikh’"
let dict = ["firstName": "Amir", "lastName": ""]
let e = try! Expression(string: expression)
let result = try! Evaluator.default.evaluate(e, substitutions: dict)
Though it should parse a correct value from JSON, I have hard coded substitutions string to at least get a breakthrough. Here, substitutions expect String & Double & give error as "Cannot convert a value of type [String: String] to expected arg type substitutions (Dcitionary).
Is there any way to pass String: String substitutions?
DDMathParser is not built to do string evaluations. It's technically possible to make it work, but it's a bit beyond the scope of the framework.
For this situation, I think you'd be better off using NSPredicate, which does allow string comparisons and variable substitutions.

restassured - parsing response and searching by value

I have following REST API response:
"items":
[
{
"empid": "1234",
"name": "Santosh",
"hiredby": "Mark",
"date": "2017-01-31,00:19:41 PST",
},
{
"empid": "5678",
"name": "Kumar",
"hiredby": "Bob",
"date": "2017-01-31,08:30:31 PST"
}
]
My query is : - How do i get empid based on querying name as Kumar.
For example: I need to find "Kumar" name and get his empid. (that is, search by name and get his empid as response) I'm able to get the response and store it in Response object. but, from response object how can i traverse and query to get the required value.
Also,
I tried by retrieving as:
String name = get(REST_ENDPOINT).then().body("items.name",hasItems("Kumar")).extract().path("items.empid").toString();
when i print the response i get collection of the empid like [1234,5678], where as my expectation is to get only 5678.
Do I need to parse via JSONArray and JSONObject and iterate the response?
Please suggest.
You can use something like this
response1.jsonPath().getList("collect { it.credentials.findAll { it.credentialType == 'Ban User Name'}.credentialId }.flatten()")

Resources