I am trying to assert in my RestAssured TestNG test that for every given ReportCodeNbr in my JSON file there is a correct UID value.
I was able to successfully do this by referencing each json section with a hard-coded index value like in this example, however, the order of the sections can change which changes the index value and breaks the test.
How can I best store all of the values for ReportCodeNbr for each section and then assert that the UID is correct without using a hard-coded index value like in my example?
A colleague suggested an array, but I am not sure how to go about this.
Partial JSON file with two objects of data:
[
{
"Url": null,
"DataSteward": null,
"ReportAuthor": null,
"ReportKey": "100PercentSponsorFundedFaculty",
"SystemType": null,
"ReportTitle": "Report",
"ReportCodeNbr": "FIN1065",
"PropertyList": null,
"Title": "100 Percent Sponsor-Funded Faculty",
"Uid": "97d17dbd-9c3b-46aa-ae0e-39603a32250f"
},
{
"Url": null,
"DataSteward": null,
"ReportAuthor": null,
"ReportKey": "2013BaseYearPaidFTEReport",
"SystemType": null,
"ReportTitle": "Report",
"ReportCodeNbr": "FIN1075",
"PropertyList": null,
"Title": "100 Percent Sponsor-Funded Faculty",
"Uid": "97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"
}
]
Successful test with hard-coded index values:
#Test
public static void firstTest() {
Response response = given().when().get(baseURI);
response.then()
.assertThat().body("ReportCodeNbr[1]", equalTo("FIN1075"))
.assertThat().body("Uid[1]", equalTo("97b3f1e0-b17d-448b-86ae-6ed6b432dcd2"));}
Something like this should work:
Response response = given().when().get(baseURI);
List<String> jsonResponse = response.jsonPath().getList("Uid");
Then you can Stream the list and assert it contains the value you are looking for if you are using >= java 1.8.
Otherwise just use a for-loop.
There are a host of ways to do this.
Refer here for more information:
Testing Excellence,
Rest Assured Docs (jsonPath)
I have just started to work on Solr. There is a phone field and it has been defined in schema like below
<field docValues="true" indexed="true" multiValued="true" name="phones" stored="true" type="StrField"/>
From my understanding the string field will try to do the exact match but the user can use any format to search the phone number with special characters like (111) 111-1111. So I used ClientUtils.escapeQueryChars to add a slash for the special characters but the search does not result any result. I have been trying to understand why and is there any criteria that special characters cannot be escaped for string field? I don't think tokenizer matters as it is string field and I use edismax parser. Any ideas?
Using Solr 7.3.1 I reproduced what you've asked and can confirm that as long as you escape (, ) and properly, you'll get the hits you're looking for.
Schema
id: string
phones: string (multivalued, docvalues, indexed, stored)
Documents
{
"id":"doc1",
"phones":["(111) 111-1111"],
"_version_":1602190176246824960
},
{
"id":"doc2",
"phones":["111 111-1111"],
"_version_":1602190397829808128
},
{
"id":"doc3",
"phones":["111 (111)-1111"],
"_version_":1602190400002457600
}
Query
/select?q=phones:\(111\)\ 111-1111
{
"id":"doc1",
"phones":["(111) 111-1111"],
"_version_":1602190176246824960}]
}
/select?debugQuery=on&q=phones:111\ 111-1111
{
"id":"doc2",
"phones":["111 111-1111"],
"_version_":1602190397829808128}]
}
/select?debugQuery=on&q=phones:1111111111
"response":{"numFound":0,"start":0,"docs":[]}
The behavior is exactly as described - exact matches only.
Getting the behavior you want with PatternReplaceCharFilterFactory
Let's create a custom field type that removes anything that's not a number or letter:
curl -X POST -H 'Content-type:application/json' --data-binary '{
"add-field-type" : {
"name":"phoneStripped",
"class":"solr.TextField",
"positionIncrementGap":"100",
"analyzer" : {
"charFilters":[{
"class":"solr.PatternReplaceCharFilterFactory",
"replacement":"",
"pattern":"[^a-zA-Z0-9]"
}],
"tokenizer":{
"class":"solr.KeywordTokenizerFactory"
},
}
}
}' http://localhost:8983/solr/foo/schema
Then we create a new field named phone_stripped using this new field type (you can do this in the UI), and reindex our documents - now using the new field name:
{
"id":"doc1",
"phone_stripped":"(111) 111-1111"
},
{
"id":"doc3",
"phone_stripped":"111 (111)-1111"
},
{
"id":"doc2",
"phone_stripped":"111 111-1111"
}
And then we search for just 1111111111:
"response":{"numFound":3,"start":0,"docs":[ .. all our docs ..]
Using the previous search, phone_stripped:\(111\)\ 111-1111:
"response":{"numFound":3,"start":0,"docs":[ .. all our docs ..]
And just to make sure we haven't broken things in unspeakable ways, let's search for phone_stripped:\(111\)\ 111-1112:
"response":{"numFound":0,"start":0,"docs":[]
I am using GSON to convert the List(Map(String,String)) to json string and passing it to the front end through session. GSON is properly escaping the double qoutes with /" but the problem is coming while parsing the json string.
The JSON string generated is
[{"queueList": [{"Name": "Queue\"1\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]
Error I am getting in chrome while parsing is: "UnExpected Number"
Code I am using to parse is as below
$(document).ready(function () {
var menuItemsStr = '[{"queueList": [{"Name": "Queue\"1\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]';
var menuItems = $.parseJSON(menuItemsStr);
$.each(menuItems[0].queueList, function (idx, obj) {
var listItemHTML = $("#listItem").clone().html();
listItemHTML = listItemHTML.replace(/\#QN/g, obj.Name);
$("#list").append(listItemHTML);
});
});
Below is the fiddle link where above code is present with the issue
http://jsfiddle.net/vinaybvk/qvwL9246/2/
When the JSON string has \\" then above fiddle is working fine as expected.
Working escaped JSON string is below:
var menuItemsStr = '[{"queueList": [{"Name": "Queue\\"1\\""}, {"Name": "Queue2"}, {"Name": "Queue3"}, {"Name": "Queue4"}]}]';
I am not able to find a way to add \\ before " to get the behavior working. I am trying both in java and javascript.
what i am trying to do in javascript is there in the above fiddle in comments
what I am trying to do in java is str.replaceAll("\"", "\\\\\")); which is generating the string with \\\"
Please let me know Is there any way to get this corrected or I am doing something wrong.
Thanks.
Instead of quoting the string then parsing it, in this case you can just do:
var menuItems = <s:property value="#session['jsonFormattedResult']" escapeHtml = "false" />;
which results in a valid object.
As a follow up on my previous question: Why doesn't my attempt to escape quotation marks in JSON work?, I would like to know if there is any way to make Gson and Javascript play along when escaping special characters and symbols.
Consider this as a database table string, that I want to display on a web page:
I am "literally" hurting inside because this do not work!
If I retrieve the string in Java from my database, and use Gson to parse it, it will look like this:
'{"text" : "I am \"literally\" hurting inside that this does not work!"}'
However, my Javascript function for parsing needs this to display it correctly:
'{"text" : "I am \\"literally\\" hurting inside that this does not work!"}'
Are there any way to fix this, other then to check for substrings in Java, and adding an extra \?
I would suggest you to use Unbescape [ http://www.unbescape.org ]
It allows you to escape JavaScript string literals (among other things like HTML, XML, JSON...), so you can pass you GSON string to it simply like:
final String escaped = JavaScriptEscape.escapeJavaScript(text);
And it will give you the JavaScript-escaped string you need.
Disclaimer, per StackOverflow rules: I'm Unbescape's author.
Try this one, it will work in all the cases:
{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}
Sample code:
Using JSONObject:
String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";
try {
System.out.println(new JSONObject(str).getString("text"));
} catch (JSONException e) {
e.printStackTrace();
}
Using Gson:
class Text implements Serializable{
private String text;
...
}
Gson gson = new Gson();
String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";
System.out.println(gson.fromJson(str, Text.class).text);
Firefox Firebug plugin snapshot:
String str = "{\"text\" : \"I am \\\"litteraly\\\" hurting inside that this does not work!\"}";
try {
System.out.println(new JSONObject(str).getString("text"));
} catch (JSONException e) {
e.printStackTrace();
}
I'm new in Ext and I have a problem: I'm trying to fill extjs-grid with data:
Ext.onReady(function() {
var store = new Ext.data.JsonStore({
root: 'topics',
totalProperty: 'totalCount',
idProperty: 'threadid',
remoteSort: true,
autoLoad: true, ///
fields: [
'title', 'forumtitle', 'forumid', 'author',
{name: 'replycount', type: 'int'},
{name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},
'lastposter', 'excerpt'
],
proxy: new Ext.data.ScriptTagProxy({
url:'http://10.10.10.101:8080/myproject/statusList/getJobs/2-10/search-jobname-/sort-asdf/filterjobname-123/filterusername-davs/filterstatus-completed/filtersubmdate-today',
method : 'GET'
})
});
//
var cm = new Ext.grid.ColumnModel([
{sortable:true, id : 'id', dataIndex:'id'},
{sortable:true, id : 'title', dataIndex:'title'},
{sortable:true, id : 'forumtitle', dataIndex:'forumtitle'},
{sortable:true, id : 'forumid', dataIndex:'forumid'},
{sortable:true, id : 'author', dataIndex:'author'}
]);
var grid = new Ext.grid.GridPanel({
id: 'mainGrid',
el:'mainPageGrid',
pageSize:10,
store:store,
// stripeRows: true,
cm:cm,
stateful: false, // skipSavingSortState
viewConfig:{
forceFit:true
},
// width:1000,
// height:700,
loadMask:true,
frame:false,
bbar: new Ext.PagingToolbar({
id : 'mainGridPaginator',
store:store,
hideRefresh : true,
plugins: new Ext.ux.Andrie.pPageSize({
beforeText: 'View: ',
afterText: '',
addAfter: '-',
variations: [10, 25, 50, 100, 1000]
//comboCfg: {
//id: '${ dispview_widgetId }_bbar_pageSize'
//}
}),
displayMsg: 'Displaying items {0} - {1} of {2}',
emptyMsg:'No data found',
displayInfo:true
})
});
grid.render();
});
and the Java part:
#GET
#Path("/getJobs/{startFrom}-{startTo}/search-{searchType}-{searchName:.*}/" +
"sort-{sortType}/filterjobname-{filterJobName:.*}/filterusername-{filterUsername:.*}/" +
"filterstatus-{filterStatus:.*}/filtersubmdate-{filterSubmittedDate:.*}")
#Produces({"application/json"})
#Encoded
public String getJobs(
#PathParam("startFrom") String startFrom,
#PathParam("startTo") String startTo,
#PathParam("searchType") String searchType,
#PathParam("searchName") String searchName,
#PathParam("sortType") String sortType,
#PathParam("filterJobName") String filterJobName,
#PathParam("filterUsername") String filterUsername,
#PathParam("filterStatus") String filterStatus,
#PathParam("filterSubmittedDate") String filterSubmittedDate) {
return "{totalCount:'3',topics:[{title:'XTemplate with in EditorGridPanel',threadid:'133690',username:'kpremco',userid:'272497',dateline:'1305604761',postid:'602876',forumtitle:'Ext 3x Help',forumid:'40',replycount:'2',lastpost:'1305857807',lastposter:'kpremco',excerpt:'Hi I have an EditiorGridPanel whose one column i am using XTemplate to render and another Column is Combo Box FieldWhen i render the EditorGri'}," +
"{title:'IFrame error _flyweights is undefined',threadid:'133571',username:'Daz',userid:'52119',dateline:'1305533577',postid:'602456',forumtitle:'Ext 3x Help',forumid:'40',replycount:'1',lastpost:'1305857313',lastposter:'Daz',excerpt:'For Ext 330 using Firefox 4 Firebug, the following error is often happening when our app loads e._flyweights is undefined Yetthis '}," +
"{title:'hellllllllllllllpwhy it doesnt fire cellclick event after I change the cell value',threadid:'133827',username:'aimer311',userid:'162000',dateline:'1305700219',postid:'603309',forumtitle:'Ext 3x Help',forumid:'40',replycount:'3',lastpost:'1305856996',lastposter:'aimer311',excerpt:'okI will discribe this problem as more detail as I canI look into this problem for a whole dayI set clicksToEdit1 to a EditorGridPanelso when I'}]}";
As a result I'm getting a JavaScript error:
Syntax error at line 1 while loading:
totalCount:'3',topics:[{title:'XTemplate
---------------------^
expected ';', got ':'
Although, when I'm using Proxy's URL:
URL: 'http://extjs.com/forum/topics-browse-remote.php',
which represents same information, I don't have any problems.
Where is my failure????
P.S. Comments for the first answer:
return "{\"totalCount\":\"3\",\"topics\":[{\"title\":\"XTemplate with in EditorGridPanel\",\"threadid\":\"133690\",\"username\":\"kpremco\",\"userid\":\"272497\",\"dateline\":\"1305604761\",\"postid\":\"602876\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"2\",\"lastpost\":\"1305857807\",\"lastposter\":\"kpremco\",\"excerpt\":\"Hi I have an EditiorGridPanel whose one column i am using XTemplate to render and another Column is Combo Box FieldWhen i render the EditorGri\"}," +
"{\"title\":\"IFrame error _flyweights is undefined\",\"threadid\":\"133571\",\"username\":\"Daz\",\"userid\":\"52119\",\"dateline\":\"1305533577\",\"postid\":\"602456\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"1\",\"lastpost\":\"1305857313\",\"lastposter\":\"Daz\",\"excerpt\":\"For Ext 330 using Firefox 4 Firebug, the following error is often happening when our app loads e._flyweights is undefined Yet, this \"}," +
"{\"title\":\"hellllllllllllllpwhy it doesn't fire cellclick event after I change the cell value\",\"threadid\":\"133827\",\"username\":\"aimer311\",\"userid\":\"162000\",\"dateline\":\"1305700219\",\"postid\":\"603309\",\"forumtitle\":\"Ext 3x Help\",\"forumid\":\"40\",\"replycount\":\"3\",\"lastpost\":\"1305856996\",\"lastposter\":\"aimer311\",\"excerpt\":\"okI will discribe this problem as more detail as I canI look into this problem for a whole dayI set clicksToEdit1 to a EditorGridPanelso when I\"}]}";
I've got the following error:
Syntax error at line 1 while loading:
{"totalCount":"3","topics":[{"title
-------------^
expected ';', got ':'
P.S. #2. When I've added '[' to the begining of the response string and ']' to the end , erros disappered, but grid hasn't been filled with data
You're not returning (valid) JSON. Refer to the JSON site for details, but for instance, all property keys must be in double quotes. (All strings must also be in double quotes; single quotes are not valid for JSON strings.)
So for instance, this is not valid JSON:
{totalCount:'3'}
...because the key is not in quotes, and the value is using single quotes. The correct JSON would be:
{"totalCount":"3"}
...if you really want the 3 to be a string, or:
{"totalCount":3}
...if the 3 should be a number.
People frequently confuse JSON and JavaScript's object literal notation, but they are different. Specifically, JSON is a subset of object literal notation. A lot of things that are valid in object literal notation are not valid in JSON. Any time you're in doubt, you can check at jsonlint.com, which provides a proper JSON validator.
I have found the root of issue.
As I've known Ext send to my web service function with parameter 'callback=[some_callback_name]' (e.g. callback1001). It means that Extjs wanna to get results not just in JSON format, but in format 'callback1001()'. When I've return my data in this format everything became good.
Proof links:
http://www.sencha.com/forum/showthread.php?22990-Json-Invalid-label (response #6)
http://indiandeve.wordpress.com/2009/12/02/extjs-error-invalid-label-error-while-using-scripttagproxy-for-json-data-in-paging-grid-example/