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));
Related
I'm currently using Grails 2.4.5 and used AmazonWebService plugin for grails 2.4.5
I'm trying to create a new recordset on route53 using this plugin.
On my BuildConfig.groovy I used this plugin fro aws web services.
compile ":aws-sdk:1.10.44"
I need your help guys regarding route53 change resource record sets.
I got an error below when I tried to change route53 resource record sets.
Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6). Stacktrace follows:
Message: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6)
This is my code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
AliasTarget target = new AliasTarget('hostedZoneIDHere', 'app.sample.com.')
target.setEvaluateTargetHealth(true)
List<ResourceRecord> resourceRecords = new ArrayList<>()
resourceRecords.add(new ResourceRecord('dNSNameHere'))
ResourceRecordSet recordSet = new ResourceRecordSet('app.sample.com.', RRType.A)
recordSet.setAliasTarget(target)
recordSet.setResourceRecords(resourceRecords)
recordSet.setTrafficPolicyInstanceId('simple')
List<Change> changes = new ArrayList<>()
changes.add(new Change(ChangeAction.CREATE, recordSet))
ChangeBatch changeBatch = new ChangeBatch(changes)
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest('hostedZoneIDHere', changeBatch)
return route53Client.changeResourceRecordSets(request)
}
}
Can you tell me what is the problem with the setup?
I would be glad if you can help me with my problem right now.
Thank you guys.
I already solve this problem. below is the working code.
import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional
#Transactional
class AwsRoute53Service {
private static final String DOMAIN_NAME_SERVER = "${System.env.DOMAIN_NAME_SERVER}"
private static final String HOSTED_ZONE_ID = "${System.env.HOSTED_ZONE_ID}"
AmazonWebService amazonWebService
ChangeResourceRecordSetsResult changeRecordSet() {
AmazonRoute53Client route53Client = amazonWebService.route53
GetHostedZoneResult hostedZoneResult = route53Client.getHostedZone(new GetHostedZoneRequest(HOSTED_ZONE_ID))
HostedZone hostedZone = hostedZoneResult.getHostedZone()
ResourceRecordSet resourceRecordSet = new ResourceRecordSet()
.withName('dNSName')
.withType(RRType.CNAME)
.withTTL(60)
.withResourceRecords([
new ResourceRecord().withValue(DOMAIN_NAME_SERVER)
])
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
.withHostedZoneId(hostedZone.id)
.withChangeBatch(
new ChangeBatch()
.withChanges([
new Change()
.withAction(ChangeAction.CREATE)
.withResourceRecordSet(resourceRecordSet)
])
)
return route53Client.changeResourceRecordSets(request)
}
}
I want to convert Response to string
Response response = ClientBuilder.newBuilder().sslContext(sslContext).build().target(url)
.request(MediaType.APPLICATION_JSON).get();
// I have tried as below.. It didn't work
String result = (String)response.getEntity();
Error is java.lang.ClassCastException: org.glassfish.jersey.client.HttpUrlConnector$1 cannot be cast to java.lang.String
Please not i am using Java 1.6 version and i cannot find methods like readEntity(String.class) and getEntity(String.class) from Response class.
Alternate way works as below by giving String.class in get.
But i need Response object First to check the status code then i want to convert it to String.
String response = ClientBuilder.newBuilder().sslContext(sslContext).build().target(url)
.request(MediaType.APPLICATION_JSON).get(String.class);
Please assist in solving this
The readEntity() method is the way to go:
Response response = ...
String value = response.readEntity(String.class);
I don't understand why you are saying that such method is not available for you: the ClientBuilder class (just like the readEntity() method) was also introduced in JAX-RS 2.0 (Java EE 7) as part of the Client API.
Don't you have any JAX-RS 1.x dependencies in the classpath?
If we don't use Jersey client jar, then we don't get readEntity(class) and getEntity(class). These methods are not part of javax.ws.rs.core.Response they are part of Jersey clientjar. So if we are using javax.ws.rs.core.Response, then we have to manually convert as below
javax.ws.rs.core.Response response;
String result = readInputStreamAsString((InputStream) response.getEntity());
public static String readInputStreamAsString(InputStream in) {
try {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte) result;
buf.write(b);
result = bis.read();
}
return buf.toString();
} catch (IOException ex) {
return null;
}
}
//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);
}
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
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.