API Automation : Assertion is not working for google place api - rest

//Below mentioned code not working for assertion in google api
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class Base {
public static void main(String[] args) {
//URL --> End Point --> BaseURL/Resources/Format?Parameters
// BaseURL or Host
RestAssured.baseURI = "https://maps.googleapis.com";
given().
param("location","33.8670522,151.1957362").
param("radius","500").
param("key","AIzaSyDahQkqdxmUihrC0_3Gi7hRBZQWDrV1xI0").
when().
get("/maps/api/place/nearbysearch/json").
then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
body("results[0].geometry.location.lat", equalTo("-33.8710748"));
}
}
Below error I am getting :
java.lang.AssertionError: 1 expectation failed.
JSON path results[0].geometry.location.lat doesn't match.
Expected: -33.8710748
Actual: null
Also find the original response:
https://jsoneditoronline.org/?id=7f9b24fa65f044fa9c4f48500a6c9bbe

It looks, Given Piece of Code is correct only (I hope all the applicable headers are mentioned)and valid response might not be retrieved from the API with Status Code as 200. Please extract the response and store in one variable for the debugging purpose.
Please check the below for the debugging.
public static void main(String[] args) {
//URL --> End Point --> BaseURL/Resources/Format?Parameters
// BaseURL or Host
RestAssured.baseURI = "https://maps.googleapis.com";
String result=given().
param("location","33.8670522,151.1957362").
param("radius","500").
param("key","AIzaSyDahQkqdxmUihrC0_3Gi7hRBZQWDrV1xI0").
when().
get("/maps/api/place/nearbysearch/json").
then().assertThat().statusCode(200).extract().asString();;
System.out.println(" API Response :"+ result);
}

Related

C#.Net RestSharp client - passing auth token

I am writing a REST client in C#.Net using RestSharp. There are two API calls - one is "Auth" call and second is "getKey" call. The "Auth" call throws back a "Auth token"in the response, and I'd like to parse that token from the response, and pass it as an header to the second "getkey" call. Please advise with examples
I have given some sample to achieve your scenario. Please use the below example and do the modification as per your requirement.
RestUtils Class:
Add the Request Header, If your application is expected some additional headers.
class RestUtils
{
private static readonly RestClient _restClient = new RestClient();
public static void SetBaseURL(String host)
{
_restClient.BaseUrl = new Uri(host);
}
public static string GetResponse(String endpoint, String token)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", token);
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
public static string GetToken(String endpoint)
{
var request = new RestRequest(endpoint, Method.GET);
request.AddHeader("Accept", "application/json");
IRestResponse response = _restClient.Execute(request);
return response.Content;
}
}
TestClass:
In your test class you can add the below steps and you can get the result as expected. First two lines will be executed and give the authentication token as output. So, you can use the retrieved token in the subsequent lines for other API. In another way, you can create one property class and set the retrieved token value .So, that you can access the token from various class.
//Specify the Base URI of your Token Specific API
RestUtils.SetBaseURL("https://login.microsoftonline.com/");
//Specify the End Point of your Token Specific API
String token = RestUtils.GetToken("/oauth2/token");
//Specify the Base URI of your actual Test API
RestUtils.SetBaseURL("XXXXXXX");
String response = RestUtils.GetResponse(token);

java.lang.AssertionError: expected [201] but found [201]

I am pretty new to testing with RestAssured and using the methods.
This is my code
package com.123.tests;
import com.jayway.restassured.response.Response;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.specification.RequestSpecification;
public class PersonPostTest {
#Test
public void RegistrationSuccessful()
{
RestAssured.baseURI ="https://reqres.in/api";
RequestSpecification request = RestAssured.given();
JSONObject obj = new JSONObject();
obj.put("name", "morpheus");
obj.put("job", "leader");
request.body(obj.toString());
Response response = request.post("/users");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "201");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Got the correct code", successCode, "Success");
}
}
and everything seems to be good but I get this below error.
[RemoteTestNG] detected TestNG version 6.14.2
FAILED: RegistrationSuccessful
java.lang.AssertionError: expected [201] but found [201]
I don't seem to understand what the problem is. Any help would be appreciated. Thank you
The return type of getStatusCode() is Integer.
You are checking equality of statusCode which is Integer(201) with Object type. That is the issue here.
Try with below snippet. It works.
Response response = request.post("/users");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, 201);
Check for Object Types here:
Assert.assertEquals(statusCode, "201");
One is Integer and the other is String. That's the reason for failure. Make sure to convert them to the same type.
Replace the assertion with the below:
Assert.assertEquals(statusCode, new Integer(201));

HttpResponseException: Internal Server Error

Weirdest thing I have seen in a while. I run my API call through Postman and have no problems at all making a GET request. However, the groovy code below pulls groovyx.net.http.HttpResponseException: Internal Server Error. I am not able to pull even debug to understand if I am actually getting a 5xx error or my code is legitimately broken.
Additionally I have had code like this work in the past, I re-pulled that working code and have the same error. Curious if my Maven config settings would be causing the issue as well (Not sure where I would have to debug). I have also tried messing with the URIbuilder line to see if changing the endpoints would help.
Thanks for helping
abstract class HTTTPClient {
protected runGetRequest(String endpointPassedIn, RESTClient Client){
URIBuilder myEndpoint = new URIBuilder(new URI(Client.uri.toString() + endpointPassedIn))
//Error happens at the next Line
Client.get(uri: myEndpoint, contentType: ContentType.JSON)
LazyMap Response = unprocessedResponse.getData() as LazyMap
return Response
}
}
#Singleton(lazy = true)
class RequestService extends HTTTPClient {
private String auth = "myAuth"
private String baseURL = 'https://api.endpoint.net/'
private RESTClient client = setClient(baseURL, auth)
public buildResponseList(int pagesToPull) {
String endpoint = 'site/address.json?page='
ArrayList responseList = []
for (int i = 1; i <= pagesToPull; i++) {
LazyMap Response = runGetRequest(endpoint + i, client)
for (row in Response) {
responseList.add(row)
//TODO Add in items call here
}
}
return conversationList
}
The error was due to encoding in the Authorization, was on the server side, not the code side

Getting NullPointerException while fetching property from repository in ATG

I'm trying to fetch properties like first name and last name from profile repository, displaying it in jsp using droplet. Below is my sample code:
SampleDroplet.java
public class SampleDroplet extends DynamoServlet {
private Repository mProfileRepository;
#Override
public void service(DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes)
throws ServletException, IOException {
String lFirstName = null;
String lLastName = null;
String lProfileId = pReq.getParameter("profileId");
try {
RepositoryItem lItem = getProfileRepository().getItem(lProfileId, "user");
lFirstName = (String) lItem.getPropertyValue("firstName");
lLastName = (String) lItem.getPropertyValue("lastName");
} catch (RepositoryException e) {
e.printStackTrace();
}
pReq.setParameter("firstName", lFirstName);
pReq.setParameter("lastName", lLastName);
pReq.serviceParameter("output", pReq, pRes);
}
SampleDroplet.properties
$class=com.tap.droplet.SampleDroplet
scope=global
profileRepository=/atg/userProfiling/ProfileAdaptarRepository
SampleDroplet.jsp
<dsp:page>
<dsp:importbean bean="/atg/userprofiling/Profile" var="profile" />
<dsp:importbean bean="/com/tap/droplet/SampleDroplet" />
<dsp:getvalueof var="profileId" bean="Profile.id"/>
<dsp:droplet name="SampleDroplet">
<dsp:param name="profileId" value="${profileId}" />
<dsp:oparam name="output">
Profile's First Name : <dsp:valueof param="firstName"/>
Last Name : <dsp:valueof param="lastName"/>
</dsp:oparam>
</dsp:droplet>
</dsp:page>
I've tried displaying profileId in jsp it is working. But when i passed it to droplet it is showing NullPointerException
java.lang.NullPointerException
at com.tap.droplet.SampleDroplet.service(SampleDroplet.java:26)
at atg.servlet.DynamoServlet.service(DynamoServlet.java:152)
at atg.taglib.dspjsp.DropletTag.invokeServlet(DropletTag.java:420)
at atg.taglib.dspjsp.DropletTag.doAfterBody(DropletTag.java:705)
at jsp_servlet._test._droplet.__sampledroplet._jsp__tag18(__sampledroplet.java:874)
Truncated. see log file for complete stacktrace
If anyone knows what is the issue please help me.
Thanks in advance
it looks like problem is here:
profileRepository=/atg/userProfiling/ProfileAdaptarRepository
Nucleus can't find this component:
"userprofiling" should be in lower case.
ProfileAdaptarRepository -> ProfileAdapterRepository

Twitter 4j with Netbeans

First time poster, but I'm really stuck.
I'm working on a little project and I'm trying to send out a tweet using a netbeans project. I'm using twitter4j and it seems like things have recently changed to where you have to use their OAuth function. I've created an application on twitter and tried some code but I keep getting this error:Exception in thread "main" connect timed outRelevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=1b442895
TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
at login.Login.start(Login.java:36)
at login.Login.main(Login.java:63)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
... 6 more
Java Result: 1
I'm not entirely sure what I'm doing wrong. Below is the code I've tried.
package login;
import java.io.IOException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class Login {
private final static String CONSUMER_KEY = "******";
private final static String CONSUMER_KEY_SECRET =
"******";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
// here's the difference
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,
accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
// end of difference
twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");
System.out.println("\nMy Timeline:");
// I'm reading your timeline
ResponseList list = twitter.getHomeTimeline();
/* for (Status each : list) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}*/
}
private String getSavedAccessTokenSecret() {
// consider this is method to get your previously saved Access Token
// Secret
return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
}
private String getSavedAccessToken() {
// consider this is method to get your previously saved Access Token
return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
}
public static void main(String[] args) throws Exception {
new Login().start();
}
}
Could I suggest an alternative route..
I have recently been messing around with twitter4j and I approached this slightly differently - I found a nice and easy way to authenticate the client using a ConfigurationBuilder object and passing this to the factory that is getting the instance of the Twitter object you need.
package main;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Base {
protected Twitter twitter;
//protected TwitterStream twitterStream;
private ConfigurationBuilder configBuilder;
public Base(){
configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true);
configBuilder.setOAuthConsumerKey("[consumer key here]");
configBuilder.setOAuthConsumerSecret("[consumer secret key here]");
configBuilder.setOAuthAccessToken("[OAuthAccessToken here]");
configBuilder.setOAuthAccessTokenSecret("[secret OAuthAccessToken here]");
//use the ConfigBuilder.build() method and pass the result to the TwitterFactory
TwitterFactory tf = new TwitterFactory(configBuilder.build());
//you can now get authenticated instance of Twitter object.
twitter = tf.getInstance();
}
}
You could then extend this class with sub classes that implement the functionality you require or just create the ConfigurationBuilder/TwitterFactory/Twitter objects elsewhere in your code.
Below I have implemented a class that creates status' and can return the Status object that holds additional information such as createdAt() and the ID etc etc.
package main;
import twitter4j.Status;
import twitter4j.TwitterException;
public class StatusUpdater extends Base{
public StatusUpdater(){}
public Status updateStatus(String statusToUpdate) throws TwitterException{
Status status = twitter.updateStatus(statusToUpdate);
System.out.println("statusToUpdate: " + status + ".");
return status;
}
}
Then you can use the following statement to create the status. This can be done from mbean/ejb/servlet etc.
try {
StatusUpdater statusUpdater = new StatusUpdater();
String statusTextToSet = "test status";
Status updatedStatus = statusUpdater.updateStatus(statusTextToSet);
System.out.println("Created at: " + updatedStatus.getCreatedAt());
} catch (TwitterException tex) {
System.out.println(tex.getErrorMessage());
}
More info on the configuration process here
Your code looks ok. Have you confirmed your definitely using the correct consumer key and secret for your app? Try twitter.verifyCredentials() to see if you get the same error, or a more specific error.
If you're correcting to the net via a proxy, you will need to include your proxy settings to allow the connection to succeed, details can be found here http://twitter4j.org/en/configuration.html#HTTP%20proxy%20server
As an aside, you may want to remove you access token and secret from your post, if they're still valid then someone could login to your account with them.