Java Code Examples for io.restassured.response.Response#getStatusCode()

The following examples show how to use io.restassured.response.Response#getStatusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServiceHaMode.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private void routeAndVerifyRetry(List<String> gatewayUrls, int timeoutSec) {
    final long time0 = System.currentTimeMillis();

    for (String gatewayUrl : gatewayUrls) {
        while (true) {
            String url = gatewayUrl + "/application/instance";

            try {
                Response response = given().when()
                    .get(url)
                    .andReturn();
                if (response.getStatusCode() != HttpStatus.SC_OK) {
                    fail();
                }
                StringTokenizer retryList = new StringTokenizer(response.getHeader("RibbonRetryDebug"), "|");
                assertThat(retryList.countTokens(), is(greaterThan(1)));
                break;
            }
            catch (RuntimeException | AssertionError e) {
                if (System.currentTimeMillis() - time0 > timeoutSec * 1000) throw e;
                await().timeout(1, TimeUnit.SECONDS);
            }
        }
    }
}
 
Example 2
Source File: NotificationUtils.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * get Get Service Response
 *
 * @param contentType String
 * @param url String
 * @param responseLog boolean
 * @return JsonObject
 */
public static JsonObject getGetServiceResponse(String contentType, String url, boolean responseLog) {
    try {

        LOGGER.info("Request url: " + url);
        Response response = RestUtil.sendHttpGet(contentType, url.toString(), responseLog);

        if (response.getStatusCode() == 200) {
            LOGGER.debug("Call passed with status code '"
                    + response.getStatusCode()
                    + "'. ");

            JsonParser parser = new JsonParser();

            return parser.parse(response.asString()).getAsJsonObject();
        } else {
            LOGGER.error("Call failed with status code '"
                    + response.getStatusCode()
                    + "'. ");
        }

    } catch (Exception e) {
        LOGGER.error("getGetServiceResponse failure", e);
    }
    return null;
}
 
Example 3
Source File: NotificationUtils.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * get Push Service Response
 *
 * @param contentType String
 * @param request String
 * @param url String
 * @param responseLog boolean
 * @return JsonObject
 */
public static JsonObject getPushServiceResponse(String contentType, String request, String url, boolean responseLog) {
    try {

        LOGGER.info("Request url: " + url);
        Response response = RestUtil.sendHttpPost(contentType, request, url.toString(), responseLog);

        if (response.getStatusCode() == 200) {
            LOGGER.debug("Call passed with status code '"
                    + response.getStatusCode()
                    + "'. ");

            JsonParser parser = new JsonParser();

            return parser.parse(response.asString()).getAsJsonObject();
        } else {
            LOGGER.error("Call failed with status code '"
                    + response.getStatusCode()
                    + "'. ");
        }

    } catch (Exception e) {
        LOGGER.error("getPushServiceResponse failure", e);
    }
    return null;
}
 
Example 4
Source File: TracksAppAsApi.java    From tracksrestcasestudy with MIT License 6 votes vote down vote up
public void login() {

        Response response = httpMessageSender.getResponseFrom("/login");

        String authenticity_token =
                        getAuthenticityTokenFromResponse(response);

        // post the login form and get the cookies
        response = loginUserPost(username, password, authenticity_token);

        if(response.getStatusCode()==302) {
            //get the cookies
            loggedInCookieJar = response.getCookies();
        }else{
            System.out.println(response.asString());
            new RuntimeException("Could not login");
        }
    }
 
Example 5
Source File: SetupTracksTestDataUtilityTest.java    From tracksrestcasestudy with MIT License 6 votes vote down vote up
private void createContextsForUser(TestEnv env, String[] contexts,
                                   String aUserName, String aPassword) {
    // create the contexts for the user
    for(String aContext : contexts){

        // each user needs to create their own context
        TracksApi normalTracksUser = new TracksApi( env.getURL(),
                                                    aUserName, aPassword);

        Response response = normalTracksUser.createContext(aContext);

        if(response.getStatusCode()==201 || response.getStatusCode()==409){
            // 201 - Created
            // 409 - Already exists
        }else{
            System.out.println( "Warning: Creating Context " + aContext +
                                " Status Code " + response.getStatusCode());
        }
    }
}
 
Example 6
Source File: UrlFetcher.java    From frameworkium-core with Apache License 2.0 6 votes vote down vote up
/**
 * @param url the url to GET
 * @param maxTries max number of tries to GET url
 * @return the bytes from the downloaded URL
 * @throws TimeoutException if download fails and max tries have been exceeded
 */
public byte[] fetchWithRetry(URL url, int maxTries) throws TimeoutException {
    logger.debug("Downloading: " + url);
    for (int i = 0; i < maxTries; i++) {
        Response response = RestAssured.get(url);
        if (response.getStatusCode() == HttpStatus.SC_OK) {
            return response.asByteArray();
        }
        logger.debug("Retrying download: " + url);

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
    throw new TimeoutException();
}
 
Example 7
Source File: BaseMethods.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Сравнение кода http ответа с ожидаемым
 *
 * @param response           ответ от сервиса
 * @param expectedStatusCode ожидаемый http статус код
 * @return возвращает true или false в зависимости от ожидаемого и полученного http кодов
 */
public boolean checkStatusCode(Response response, int expectedStatusCode) {
    int statusCode = response.getStatusCode();
    if (statusCode != expectedStatusCode) {
        akitaScenario.write("Получен неверный статус код ответа " + statusCode + ". Ожидаемый статус код " + expectedStatusCode);
    }
    return statusCode == expectedStatusCode;
}
 
Example 8
Source File: NotificationUtils.java    From carina with Apache License 2.0 5 votes vote down vote up
/**
 * call Push Service
 *
 * @param contentType String
 * @param parameters Map String, ?
 * @param url String
 * @param responseLog boolean
 * @return JsonObject
 */
public static JsonObject callPushService(String contentType, Map<String, ?> parameters, String url, boolean responseLog) {
    try {

        LOGGER.info("Request url: " + url);

        Response response = RestUtil.sendHttpPost(contentType, parameters, url.toString(), responseLog);

        if (response.getStatusCode() == 200) {
            LOGGER.debug("Call passed with status code '"
                    + response.getStatusCode()
                    + "'. ");

            JsonParser parser = new JsonParser();

            return parser.parse(response.asString()).getAsJsonObject();
        } else {
            LOGGER.error("Call failed with status code '"
                    + response.getStatusCode()
                    + "'. ");
        }

    } catch (Exception e) {
        LOGGER.error("callPushService failure", e);
    }
    return null;
}
 
Example 9
Source File: GatewayDeployFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private void waitForAccess( String url, String username, String password, long sleep ) throws InterruptedException {
  while( true ) {
    Response response = given()
        .auth().preemptive().basic( username, password )
        .when().get( url ).andReturn();
    if( response.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
      Thread.sleep( sleep );
      continue;
    }
    assertThat( response.getContentType(), containsString( "text/plain" ) );
    assertThat( response.getBody().asString(), is( "test-service-response" ) );
    break;
  }
}
 
Example 10
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private int createFileDN( String user, String password, String path, String location, String contentType, String resource, int status ) throws IOException {
  if( status == HttpStatus.SC_CREATED ) {
    driver.getMock( "DATANODE" )
        .expect()
        .method( "PUT" )
        .pathInfo( path )
        .queryParam( "user.name", user )
        .queryParam( "op", "CREATE" )
        .contentType( contentType )
        .content( driver.getResourceBytes( resource ) )
        .respond()
        .status( status )
        .header( "Location", "webhdfs://" + driver.getRealAddr( "DATANODE" ) + "/v1" + path );
  } else {
    driver.getMock( "DATANODE" )
        .expect()
        .method( "PUT" )
        .pathInfo( path )
        .queryParam( "user.name", user )
        .queryParam( "op", "CREATE" )
        .contentType( contentType )
        .content( driver.getResourceStream( resource ) )
        .respond()
        .status( status );
  }
  Response response = given()
      //.log().all()
      .auth().preemptive().basic( user, password )
      .header( "X-XSRF-Header", "jksdhfkhdsf" )
      .contentType( contentType )
      .body( driver.getResourceBytes( resource ) )
      .then()
      //.log().all()
      .statusCode( status )
      .when().put( location );
  return response.getStatusCode();
}
 
Example 11
Source File: AbstractDebeziumTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
@Order(1)
public void testInsert() throws SQLException {
    if (getConnection() == null) {
        LOG.warn("Test 'testInsert' is skipped, because container is not running.");
        return;
    }

    int i = 0;

    while (i++ < REPEAT_COUNT) {
        executeUpdate(String.format("INSERT INTO %s (name, city) VALUES ('%s', '%s')", getCompanyTableName(),
                COMPANY_1 + "_" + i, CITY_1));

        Response response = receiveResponse();

        //if status code is 204 (no response), try again
        if (response.getStatusCode() == 204) {
            LOG.debug("Response code 204. Debezium is not running yet, repeating (" + i + "/" + REPEAT_COUNT + ")");
            continue;
        }

        response
                .then()
                .statusCode(200)
                .body(containsString((COMPANY_1 + "_" + i)));
        //if response is valid, no need for another inserts
        break;
    }

    Assert.assertTrue("Debezium does not respond (consider changing timeout in AbstractDebeziumResource).",
            i < REPEAT_COUNT);
}
 
Example 12
Source File: TracksResponse.java    From tracksrestcasestudy with MIT License 5 votes vote down vote up
public TracksResponse(Response response) {
    this.statusCode = response.getStatusCode();

    this.responseHeaders = new HashMap<>();
    Headers headers = response.getHeaders();
    for(Header header: headers){
        responseHeaders.put(header.getName(), header.getValue());
    }

    this.body = response.body().asString();
}
 
Example 13
Source File: TracksAppAsApi.java    From tracksrestcasestudy with MIT License 5 votes vote down vote up
public Response createUser(String username, String password){

        Response response= httpMessageSender.getResponseFrom(
                                                    "/signup",
                                                    loggedInCookieJar);

        String authenticity_token =
                            getAuthenticityTokenFromResponse(response);

        // cookies seem to change after signup
        // - if I don't use these then the request fails
        loggedInCookieJar = response.getCookies();

        response =  createUserPost(username, password,
                                    authenticity_token,
                                    loggedInCookieJar);

        if(response.getStatusCode()!=302) {
            //get the cookies
            loggedInCookieJar = response.getCookies();
        }else{
            System.out.println(response.asString());
            new RuntimeException(
                    String.format("Could not create user %s %s",
                                        username, password));
        }

        return response;
    }
 
Example 14
Source File: MpMetricTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
@InSequence(16)
public void testApplicationMetadataOkJson() {
    Header wantJson = new Header("Accept", APPLICATION_JSON);

    Response response = given().header(wantJson).options("/metrics/application");
    int code = response.getStatusCode();

    assertTrue(code == 200 || code == 204);

}
 
Example 15
Source File: HibernateTenancyFunctionalityTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Fruit findByName(String tenantPath, String name) {
    Response response = given().config(config).when().get(tenantPath + "/fruitsFindBy?type=name&value={name}", name);
    if (response.getStatusCode() == Status.OK.getStatusCode()) {
        return response.as(Fruit.class);
    }
    return null;
}
 
Example 16
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private void readFile( String user, String password, String file, String contentType, String resource, int status ) throws IOException {
  driver.getMock( "WEBHDFS" )
      .expect()
      .method( "GET" )
      .pathInfo( "/v1" + file )
      .queryParam( "user.name", user )
      .queryParam( "op", "OPEN" )
      .respond()
      .status( HttpStatus.SC_TEMPORARY_REDIRECT )
      .header( "Location", driver.getRealUrl( "DATANODE" ) + file + "?op=OPEN&user.name="+user );
  if( status == HttpStatus.SC_OK ) {
    driver.getMock( "DATANODE" )
        .expect()
        .method( "GET" )
        .pathInfo( file )
        .queryParam( "user.name", user )
        .queryParam( "op", "OPEN" )
        .respond()
        .status( status )
        .contentType( contentType )
        .content( driver.getResourceBytes( resource ) );
  } else {
    driver.getMock( "DATANODE" )
        .expect()
        .method( "GET" )
        .pathInfo( file )
        .queryParam( "user.name", user )
        .queryParam( "op", "OPEN" )
        .respond()
        .status( status );
  }
  Response response = given()
      //.log().all()
      .auth().preemptive().basic( user, password )
      .header( "X-XSRF-Header", "jksdhfkhdsf" )
      .queryParam( "op", "OPEN" )
      .then()
      //.log().all()
      .statusCode( status )
      .when().get( driver.getUrl("WEBHDFS") + "/v1" + file + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
  if( response.getStatusCode() == HttpStatus.SC_OK ) {
    String actualContent = response.asString();
    String thenedContent = driver.getResourceString( resource );
    assertThat( actualContent, Matchers.is(thenedContent) );
  }
  driver.assertComplete();
}
 
Example 17
Source File: RestUtil.java    From carina with Apache License 2.0 4 votes vote down vote up
public static int statusCode(Response response) {
    return response.getStatusCode();
}