Im a beginner for automation testing.Here I want to get the data's from json to be used by selenium webdriver.I wrote one java class and hard coded something to get a result as a try.and getting an answer in console panel like
{
"name": "john",
"location": "jihu",
"job": [
{
"manager": [
{
"collegues": [
"ram",
"ranma",
],
}
}
}
(not exactly this).
Now i want to use this for one specific application using selenium webdriver. How can i move on with this.help me in detail.Thanks in advance.
From Selenium and Backend Comparison testing point of view i am answering the same .you need to parse json response using some Libraries like GSON , jackson etc into Java Pojo objects and then apply asserts on the fields you want to compare with json and UI. I guess you need to go through below topics first
1) Serialization -Deserialization API response
2) GSON or Jackson parsers
3) RestAssured ( Provides framework for API testing )
4) JAVA pojo classed and usage of them . you might need them to save your response in form of some Response class and compare objects .
You can use these online converters for converting a json object into Java Pojo Classes :
http://json2java.azurewebsites.net/ (I usually use this)
https://codebeautify.org/json-to-java-converter
and then place them in a package or in the same class as you wish :
You can better understand it by below example :
package com.demo.core;
import com.google.gson.Gson;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class Demo {
public static void main(String r[]) {
Response response1 = RestAssured.given().get("http://dummy.restapiexample.com/api/v1/employee/1"); // use your method to get the API response (I have used RestAssured here)
String json = response1.asString(); // you can use your json response here and convert it into a String
Gson gson = new Gson();
Employee emp = gson.fromJson(json, Employee.class); // The response is now captured in this Employee class
System.out.println(emp.getEmployeeAge());
System.out.println(emp.getEmployeeName());
System.out.println(emp.getEmployeeSalary());
}
}
class Employee {
private String id;
private String employee_name;
private String employee_salary;
private String employee_age;
private String profile_image;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return this.employee_name;
}
public void setEmployeeName(String employee_name) {
this.employee_name = employee_name;
}
public String getEmployeeSalary() {
return this.employee_salary;
}
public void setEmployeeSalary(String employee_salary) {
this.employee_salary = employee_salary;
}
public String getEmployeeAge() {
return this.employee_age;
}
public void setEmployeeAge(String employee_age) {
this.employee_age = employee_age;
}
public String getProfileImage() {
return this.profile_image;
}
public void setProfileImage(String profile_image) {
this.profile_image = profile_image;
}
}
You can easily assert the values after the response is captured in Java classes using their getter methods like I have used in the code to get field values present in Employee class.
Please do let me know if you still got an issue.
If your result contains many fields than better to shift all converted java classes into a separate package for a clear code.
Related
Create a web script to get the parameters of the document in java Example url:
localhost:8080/alfresco/s/get-document-data?nodeRef=workspace://SpacesStore/3b3597e5-b5ec-41d5-b63b-54b050dccd1b&property=cm:name
As a result the script should return Json object of a kind:
{
"nodeRef": "workspace: // SpacesStore / 3b3597e5-b5ec-41d5-b63b-54b050dccd1b",
"value": "value property - the one we got from nodRef"
}
Create a web script to retrieve all subfolder settings along the way. Please help!
DocumentScript.java
import org.activiti.engine.impl.util.json.JSONException;
import org.apache.chemistry.opencmis.commons.impl.json.JSONObject;
import org.springframework.extensions.webscripts.*;
import java.io.IOException;
public class DocumentScript extends AbstractWebScript {
public static JSONObject obj = new JSONObject();
#Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
try {
String noderef = req.getParameter("nodeRef");
String valueRef = res.getEncodeResourceUrlFunction("value");
obj.put("nodeRef", noderef);
obj.put("value", valueRef);
String jsonString = obj.toString();
res.getWriter().write(jsonString);
} catch (JSONException e) {
throw new WebScriptException("Unable to serialize JSON");
}
}
}
document-script-context.xml
<bean class="alfresco.extension.templates.webscripts.repository.DocumentScript"
parent="templates.webscripts.repository">
</bean>
document-script.get.desc.xml
<webscript>
<shortname>Documents</shortname>
<description>JSON data
</description>
<url>/script-document?q={keyword}</url>
<authentication>user</authentication>
<format default="html"/>
<family>Alfresco Script</family>
</webscript>
document-script.get.html.ftl
{
"obj" : [
<#list obj as Obj>
{
"nodeRef" : "${Obj.nodeRef}",
"value" : "${Obj.value}"
}
<#if Obj_has_next>,</#if>
</#list>
]
}
Here I want to get the parameters of the document here is the code but it doesn't work, what's wrong with it?
06220015 Wrapped Exception (with status template): 06220002 Error during processing of the template 'The following has evaluated to null or missing: ==> obj [in template "repository/document-script.get.html.ftl" at line 3, column 8] Tip: If the failing expression is known to be legally null/missing, either specify a default value with myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthessis: (myOptionVar.foo)!myDefault, (myOptionVar.foo)?? The failing instruction: ==> #list obj as Obj [in template "repository/document-script.get.html.ftl" at line 3, column 1]'.
You could start by creating a class for the JSON object then just do something like this:
String url = localhost:8080/alfresco/s/get-document-data?nodeRef=workspace://SpacesStore/3b3597e5-b5ec-41d5-b63b-54b050dccd1b&property=cm:name;
String[] values = url.split('?');
String[] value = values[0].split('=');
jsonObject.setNodeRef(value[1]);
.....
This will work if you know that your url has the exact same parameters you mentioned. Just use regexp. I haven't tested the code myself, give it a try.
I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);
I have a website served from a proprietary C++ server.
There is a standard javascript ajax function in the code but I don't want to start editing it.
The actual sending bit is as follows:
this.send=function(myawesomemodel)
{
/*Code redacted for brevity*/
obj.req.open('POST',myawesomeurl,true);
obj.req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
obj.req.send(JSON.stringify(myawesomemodel));
}
It used to send key value pairs as a query string but now it needs to send json.
I can send this function a controller/action address (myawesomeurl) for the appropriate end point and I can send it an awesome object which will be accepted by the action as a basic C# Model (myawesomemodel):
public ActionResult myawesomeaction(MyAwesomeClass myawesomeclass)
{
}
For the .Net model:
public class MyAwesomeClass
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
}
How do I build a javascript object the controller will recognise please?
Here's my latest failure:
function MyAwesomeModel()
{
this.A=1;
this.B=2;
this.C='Three';
}
Then:
var anawesomemodel=new MyAwesomeModel();
myawesomeajaxmodel.send(anawesomemodel);
I cannot construct the correct object in plain javascript so the mvc action registers it, what's the correct method please?
var myawesomemodel = {
A : 1,
B : 2,
C : 'Three'
}
For anyone else with the same problem who finds this page, Stephen Muecke nailed it
Change the ajax object to:
this.send=function(myawesomemodel)
{
/*Code redacted for brevity*/
obj.req.open('POST',myawesomeurl,true);
obj.req.setRequestHeader('Content-type','application/json;charset=utf-8');
obj.req.send(JSON.stringify(myawesomemodel));
}
What is the best way to return a value of a method of rest service ? A java object, json string or with Response?
For example, these examples are implemented with api jersey (maven):
1) Return java object (mapped to json):
#GET
#Path("/getUser")
#Produces({MediaType.APPLICATION_JSON})
public UserVO getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
return user;
}
2) Return a json string:
#GET
#Path("/getUser")
public String getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return jsonResp;
}
3) Return with response json:
#GET
#Path("/getUser")
public Response getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return Response.ok(jsonResp, MediaType.APPLICATION_JSON).build();
}
What is the difference between these 3? Which is better to use ?
(Considering it will be consumed from javascript)
All three options seem valid, but the first one is in my opinion more consistent because you're using an API (jersey) and this #produces annotation is the common way to use that API.
Moreover it won't make you dependant of another lib, GSON, which you could ultimately remove from your classpath if it isn't used elsewhere.
I have an object as follows which is then stored in an array of them.
I would like to send the array of them to Web API, usually you would use JSON.stringify on an object, but would this work also being in an array?
I then need to work out what type of object they would be received as the other end as I need to iterate through them. I was hoping to use a typeof class.
var fieldarray = [];
$("div[class*=container_]").each(function (index) {
var firstElement = $(this).first();
var object = $(this).find('.object');
fielddata = {
id: firstElement.attr('class').match(/\d+/)[0],
attributes: [{
'label_text': firstElement.text(),
'label_width': firstElement.width(),
'label_height': firstElement.height(),
'label_color': firstElement.css('color'),
'Field_Width': object.width(),
'Field_Height': object.height,
'Field_Type': object.attr('Field_Type'),
'PositionX': firstElement.offset().left,
'PositionY': firstElement.offset().top,
'Field': firstElement.attr('class').match(/\d+/)[0],
'Label_Font': firstElement.css('font-family')
}]
}
array.push(fielddata);
});
Can I send this using JSON.stringify, and if so, what type would I receive this as in the Web API server side?
I usually use a public class type but the above code has an object inside an object - that is my problem.
I have sorted this now, basically I used:
[HttpPut]
public int Put(int id, [FromBody] FormData HTMLFORM)
{
....
}
and stored it in my type class as a string:
public class FormData
{
public int id { get; set; }
public string HTML { get; set; }
public string fieldData { get; set; }
}
I then used
IList<AttributeData> findingList = JsonConvert.DeserializeObject<IList<AttributeData>>(HTMLFORM.fieldData);
And it was stored in the list which I can iterate through using my type class of AttributeData!
Thanks