net.codestory.rest.RestAssert Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluent-rest-test Show documentation
Show all versions of fluent-rest-test Show documentation
Library to write REST tests
/**
* Copyright (C) 2013-2014 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package net.codestory.rest;
import com.squareup.okhttp.*;
import java.io.IOException;
import java.net.Proxy;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static java.util.function.Function.identity;
public class RestAssert {
private final String url;
private final Function configureClient;
private final Function configureRequest;
RestAssert(String url) {
this(url, identity(), identity());
}
private RestAssert(String url, Function configureClient, Function configureRequest) {
this.url = url;
this.configureRequest = configureRequest;
this.configureClient = configureClient;
}
// Configuration
public RestAssert withHeader(String name, String value) {
return withRequest(request -> request.addHeader(name, value));
}
public RestAssert withPreemptiveAuthentication(String login, String password) {
return withRequest(request -> request.addHeader("Authorization", Credentials.basic(login, password)));
}
public RestAssert withAuthentication(String login, String password) {
return withClient(client -> client.setAuthenticator(new Authenticator() {
AtomicInteger tries = new AtomicInteger(0);
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
if (tries.getAndIncrement() > 0) {
return null;
}
String credential = Credentials.basic(login, password);
return response.request().newBuilder().header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) {
return null;
}
}));
}
RestAssert withRequest(Function configure) {
return new RestAssert(url, configureClient, configureRequest.andThen(configure));
}
RestAssert withClient(Function configure) {
return new RestAssert(url, configureClient.andThen(configure), configureRequest);
}
// Assertions
public Should should() {
try {
return new Should(RestResponse.call(url, configureClient, configureRequest));
} catch (IOException e) {
throw new RuntimeException("Unable to query: " + url, e);
}
}
}