diff --git a/pom.xml b/pom.xml index c07246e6..98cf401d 100755 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,11 @@ com.openshift openshift-java-client - 2.3.0-SNAPSHOT +<<<<<<< Updated upstream + 2.3.1-SNAPSHOT +======= + 2.3.0.Final +>>>>>>> Stashed changes jar OpenShift Java Client http://openshift.redhat.com diff --git a/src/main/java/com/openshift/client/IDomain.java b/src/main/java/com/openshift/client/IDomain.java index 9b5ce377..40b458d8 100755 --- a/src/main/java/com/openshift/client/IDomain.java +++ b/src/main/java/com/openshift/client/IDomain.java @@ -16,6 +16,7 @@ /** * @author André Dietisheim + * @author Nicolas Spano */ public interface IDomain extends IOpenShiftResource { @@ -78,13 +79,16 @@ public IApplication createApplication(final String name, final IStandaloneCartri throws OpenShiftException; public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, - final ApplicationScale scale) throws OpenShiftException; + final ApplicationScale scale) + throws OpenShiftException; public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, - final IGearProfile gearProfile) throws OpenShiftException; + final IGearProfile gearProfile) + throws OpenShiftException; public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, - final ApplicationScale scale, final IGearProfile gearProfile) throws OpenShiftException; + final ApplicationScale scale, final IGearProfile gearProfile) + throws OpenShiftException; /** * Creates a new application with the given name and the given @@ -110,6 +114,33 @@ public IApplication createApplication(final String name, final IStandaloneCartri final ApplicationScale scale, final IGearProfile gearProfile, String initialGitUrl) throws OpenShiftException; + /** + * Creates a new application with the given name and the given + * cartridge/framework. Optionally, adds scalability, a specific gear + * profile, a git url to use for the initial template and the timeout value. + * + * @param name + * the name of the application + * @param cartridge + * the cartridge (the application type, ex. jbossas-7, + * jbossews-2, php.5.2, etc. + * @param scale + * or null (will use default on openshift, ie, false) + * @param gearProfile + * ("small", "micro", "medium", "large", "exlarge", "jumbo") or + * null (will use default on openshift, ie, 'small') + * @param initialGitUrl + * the git url for the initial template app to be used + * @param timeout + * the timeout value in milliseconds + * @return IApplication created + * @throws OpenShiftException + */ + public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, + final ApplicationScale scale, final IGearProfile gearProfile, String initialGitUrl, + final int timeout) + throws OpenShiftException; + public List getApplications() throws OpenShiftException; /** diff --git a/src/main/java/com/openshift/client/IHttpClient.java b/src/main/java/com/openshift/client/IHttpClient.java index da336c06..9c4f1873 100755 --- a/src/main/java/com/openshift/client/IHttpClient.java +++ b/src/main/java/com/openshift/client/IHttpClient.java @@ -19,6 +19,7 @@ /** * @author André Dietisheim + * @author Nicolas Spano */ public interface IHttpClient { @@ -37,7 +38,7 @@ public interface IHttpClient { public static final String AUTHORIZATION_BASIC = "Basic"; public static final int STATUS_OK = 200; - public static final int STATUS_INTERNAL_SERVER_ERROR = 200; + public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_NOT_FOUND = 404; @@ -48,8 +49,12 @@ public interface IHttpClient { public static final char AMPERSAND = '&'; public static final char EQUALS = '='; - public static final String VERSION = "version"; - + public static final String VERSION = "version"; + + public static final int DEFAULT_CONNECT_TIMEOUT = 10 * 1000; + public static final int DEFAULT_READ_TIMEOUT = 2 * 60 * 1000; + public static final int NO_TIMEOUT = -1; + public void setUserAgent(String userAgent); public String getUserAgent(); @@ -60,12 +65,20 @@ public interface IHttpClient { public String get(URL url) throws HttpClientException, SocketTimeoutException; + public String get(URL url, int timeout) throws HttpClientException, SocketTimeoutException; + public String post(Map parameters, URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String post(Map parameters, URL url, int timeout) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String put(Map parameters, URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String put(Map parameters, URL url, int timeout) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String delete(Map parameters, URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String delete(Map parameters, URL url, int timeout) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; + public String delete(URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException; public void setAcceptedMediaType(String acceptedMediaType); diff --git a/src/main/java/com/openshift/client/OpenShiftConnectionFactory.java b/src/main/java/com/openshift/client/OpenShiftConnectionFactory.java index 831635d4..73db113d 100755 --- a/src/main/java/com/openshift/client/OpenShiftConnectionFactory.java +++ b/src/main/java/com/openshift/client/OpenShiftConnectionFactory.java @@ -61,7 +61,7 @@ public IOpenShiftConnection getConnection(final String clientId, final String pa * * @param clientId * http client id - * @param login + * @param username * user's login * @param password * user's password @@ -70,7 +70,7 @@ public IOpenShiftConnection getConnection(final String clientId, final String pa * @throws IOException * @throws OpenShiftException */ - public IOpenShiftConnection getConnection(final String clientId, final String login, final String password) + public IOpenShiftConnection getConnection(final String clientId, final String username, final String password) throws OpenShiftException { IOpenShiftConfiguration configuration; try { @@ -78,7 +78,7 @@ public IOpenShiftConnection getConnection(final String clientId, final String lo } catch (IOException e) { throw new OpenShiftException(e, "Failed to load OpenShift configuration file."); } - return getConnection(clientId, login, password, configuration.getLibraServer()); + return getConnection(clientId, username, password, configuration.getLibraServer()); } /** @@ -87,7 +87,7 @@ public IOpenShiftConnection getConnection(final String clientId, final String lo * * @param clientId * http client id - * @param login + * @param username * user's login. * @param password * user's password. @@ -98,9 +98,9 @@ public IOpenShiftConnection getConnection(final String clientId, final String lo * @throws IOException * @throws OpenShiftException */ - public IOpenShiftConnection getConnection(final String clientId, final String login, final String password, + public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String serverUrl) throws OpenShiftException { - return getConnection(clientId, login, password, null, null, serverUrl); + return getConnection(clientId, username, password, null, null, serverUrl); } /** @@ -109,7 +109,7 @@ public IOpenShiftConnection getConnection(final String clientId, final String lo * * @param clientId * http client id - * @param login + * @param username * user's login. * @param password * user's password. @@ -120,20 +120,28 @@ public IOpenShiftConnection getConnection(final String clientId, final String lo * @throws IOException * @throws OpenShiftException */ - public IOpenShiftConnection getConnection(final String clientId, final String login, final String password, + public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String authKey, final String authIV, final String serverUrl) throws OpenShiftException { Assert.notNull(clientId); - Assert.notNull(login); + Assert.notNull(username); Assert.notNull(password); Assert.notNull(serverUrl); try { - final IHttpClient httpClient = - new UrlConnectionHttpClientBuilder().setCredentials(login, password, authKey, authIV).client(); - final IRestService service = new RestService(serverUrl, clientId, httpClient); - return getConnection(service, login, password); + IHttpClient httpClient = + new UrlConnectionHttpClientBuilder().setCredentials(username, password, authKey, authIV).client(); + return getConnection(clientId, username, password, serverUrl, httpClient); } catch (IOException e) { - throw new OpenShiftException(e, "Failed to establish connection for user ''{0}}''", login); + throw new OpenShiftException(e, "Failed to establish connection for user ''{0}}''", username); } } + + protected IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String serverUrl, IHttpClient httpClient) throws OpenShiftException, IOException { + Assert.notNull(clientId); + Assert.notNull(serverUrl); + Assert.notNull(httpClient); + + IRestService service = new RestService(serverUrl, clientId, httpClient); + return getConnection(service, username, password); + } } diff --git a/src/main/java/com/openshift/internal/client/AbstractOpenShiftConnectionFactory.java b/src/main/java/com/openshift/internal/client/AbstractOpenShiftConnectionFactory.java index 0e286ae8..bf9eeb7a 100755 --- a/src/main/java/com/openshift/internal/client/AbstractOpenShiftConnectionFactory.java +++ b/src/main/java/com/openshift/internal/client/AbstractOpenShiftConnectionFactory.java @@ -10,7 +10,6 @@ ******************************************************************************/ package com.openshift.internal.client; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; @@ -30,7 +29,7 @@ public abstract class AbstractOpenShiftConnectionFactory { @SuppressWarnings("unchecked") - protected IOpenShiftConnection getConnection(IRestService service, final String login, final String password) throws FileNotFoundException, IOException, OpenShiftException { + protected IOpenShiftConnection getConnection(IRestService service, final String login, final String password) throws IOException, OpenShiftException { RestResponse response = (RestResponse) service.request(new Link("Get API", "/api", HttpMethod.GET)); return new APIResource(login, password, service, (Map) response.getData()); diff --git a/src/main/java/com/openshift/internal/client/AbstractOpenShiftResource.java b/src/main/java/com/openshift/internal/client/AbstractOpenShiftResource.java index 8f53cda9..1376b5e0 100755 --- a/src/main/java/com/openshift/internal/client/AbstractOpenShiftResource.java +++ b/src/main/java/com/openshift/internal/client/AbstractOpenShiftResource.java @@ -12,6 +12,7 @@ import java.util.Map; +import com.openshift.client.IHttpClient; import com.openshift.client.IOpenShiftResource; import com.openshift.client.Message; import com.openshift.client.Messages; @@ -119,8 +120,12 @@ protected ServiceRequest(String linkName) { } protected DTO execute(ServiceParameter... parameters) throws OpenShiftException { + return execute(IHttpClient.NO_TIMEOUT, parameters); + } + + protected DTO execute(int timeout, ServiceParameter... parameters) throws OpenShiftException { Link link = getLink(linkName); - RestResponse response = getService().request(link, parameters); + RestResponse response = getService().request(link, timeout, parameters); // in some cases, there is not response body, just a return code to // indicate that the operation was successful (e.g.: delete domain) diff --git a/src/main/java/com/openshift/internal/client/ApplicationResource.java b/src/main/java/com/openshift/internal/client/ApplicationResource.java index 42e5e28e..3623d231 100755 --- a/src/main/java/com/openshift/internal/client/ApplicationResource.java +++ b/src/main/java/com/openshift/internal/client/ApplicationResource.java @@ -39,11 +39,9 @@ import com.openshift.client.IApplication; import com.openshift.client.IApplicationPortForwarding; import com.openshift.client.IDomain; -import com.openshift.client.IField; import com.openshift.client.IGearGroup; import com.openshift.client.IGearProfile; import com.openshift.client.IOpenShiftConnection; -import com.openshift.client.Message; import com.openshift.client.Messages; import com.openshift.client.OpenShiftException; import com.openshift.client.OpenShiftSSHOperationException; diff --git a/src/main/java/com/openshift/internal/client/DomainResource.java b/src/main/java/com/openshift/internal/client/DomainResource.java index df565afa..a8e768b7 100755 --- a/src/main/java/com/openshift/internal/client/DomainResource.java +++ b/src/main/java/com/openshift/internal/client/DomainResource.java @@ -19,6 +19,7 @@ import com.openshift.client.IApplication; import com.openshift.client.IDomain; import com.openshift.client.IGearProfile; +import com.openshift.client.IHttpClient; import com.openshift.client.IUser; import com.openshift.client.Messages; import com.openshift.client.OpenShiftException; @@ -33,6 +34,7 @@ /** * @author André Dietisheim + * @author Nicolas Spano */ public class DomainResource extends AbstractOpenShiftResource implements IDomain { @@ -126,6 +128,12 @@ public IApplication createApplication(final String name, final IStandaloneCartri public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, final ApplicationScale scale, final IGearProfile gearProfile, String initialGitUrl) throws OpenShiftException { + return createApplication(name, cartridge, scale, gearProfile, initialGitUrl, IHttpClient.NO_TIMEOUT); + } + + public IApplication createApplication(final String name, final IStandaloneCartridge cartridge, + final ApplicationScale scale, final IGearProfile gearProfile, String initialGitUrl, int timeout) + throws OpenShiftException { if (name == null) { throw new OpenShiftException("Application name is mandatory but none was given."); } @@ -137,14 +145,14 @@ public IApplication createApplication(final String name, final IStandaloneCartri } ApplicationResourceDTO applicationDTO = - new CreateApplicationRequest().execute(name, cartridge, scale, gearProfile, initialGitUrl); + new CreateApplicationRequest().execute(name, cartridge, scale, gearProfile, initialGitUrl, timeout); IApplication application = new ApplicationResource(applicationDTO, cartridge, this); getOrLoadApplications().add(application); return application; } - public boolean hasApplicationByName(String name) throws OpenShiftException { + public boolean hasApplicationByName(String name) throws OpenShiftException { return getApplicationByName(name) != null; } @@ -291,7 +299,7 @@ public CreateApplicationRequest() throws OpenShiftException { } public ApplicationResourceDTO execute(final String name, final IStandaloneCartridge cartridge, - final ApplicationScale scale, final IGearProfile gearProfile, final String initialGitUrl) throws OpenShiftException { + final ApplicationScale scale, final IGearProfile gearProfile, final String initialGitUrl, final int timeout) throws OpenShiftException { if (cartridge == null) { throw new OpenShiftException("Application cartridge is mandatory but was not given."); } @@ -303,7 +311,7 @@ public ApplicationResourceDTO execute(final String name, final IStandaloneCartri addGearProfileParameter(gearProfile, parameters); addStringParameter(IOpenShiftJsonConstants.PROPERTY_INITIAL_GIT_URL, initialGitUrl, parameters); - return super.execute((ServiceParameter[]) parameters.toArray(new ServiceParameter[parameters.size()])); + return super.execute(timeout, (ServiceParameter[]) parameters.toArray(new ServiceParameter[parameters.size()])); } private List addCartridgeParameter(IStandaloneCartridge cartridge, List parameters) { diff --git a/src/main/java/com/openshift/internal/client/IRestService.java b/src/main/java/com/openshift/internal/client/IRestService.java index 6bf9220d..00fd70e6 100755 --- a/src/main/java/com/openshift/internal/client/IRestService.java +++ b/src/main/java/com/openshift/internal/client/IRestService.java @@ -31,12 +31,21 @@ public abstract RestResponse request(Link link) public RestResponse request(Link link, ServiceParameter... serviceParameters) throws OpenShiftException; + public RestResponse request(Link link, int timeout, ServiceParameter... serviceParameters) + throws OpenShiftException; + public abstract RestResponse request(Link link, Map parameters) throws OpenShiftException; + public abstract RestResponse request(Link link, int timeout, Map parameters) + throws OpenShiftException; + public abstract String request(String url, HttpMethod httpMethod, Map parameters) throws OpenShiftException; + public abstract String request(String url, HttpMethod httpMethod, int timeout, Map parameters) + throws OpenShiftException; + public abstract String getServiceUrl(); public abstract String getPlatformUrl(); diff --git a/src/main/java/com/openshift/internal/client/RestService.java b/src/main/java/com/openshift/internal/client/RestService.java index ccd7ab8a..2bb282d7 100755 --- a/src/main/java/com/openshift/internal/client/RestService.java +++ b/src/main/java/com/openshift/internal/client/RestService.java @@ -81,8 +81,16 @@ public RestResponse request(Link link) throws OpenShiftException { return request(link, (Map) null); } + public RestResponse request(Link link, int timeout) throws OpenShiftException { + return request(link, (Map) null); + } + public RestResponse request(Link link, ServiceParameter... serviceParameters) throws OpenShiftException { - return request(link, toMap(serviceParameters)); + return request(link, IHttpClient.NO_TIMEOUT, serviceParameters); + } + + public RestResponse request(Link link, int timeout, ServiceParameter... serviceParameters) throws OpenShiftException { + return request(link, timeout, toMap(serviceParameters)); } private Map toMap(ServiceParameter... serviceParameters) { @@ -93,18 +101,25 @@ private Map toMap(ServiceParameter... serviceParameters) { return parameterMap; } - public RestResponse request(Link link, Map parameters) - throws OpenShiftException { + public RestResponse request(Link link, Map parameters) throws OpenShiftException { + return request(link, IHttpClient.NO_TIMEOUT, parameters); + } + + public RestResponse request(Link link, int timeout, Map parameters) throws OpenShiftException { validateParameters(parameters, link); HttpMethod httpMethod = link.getHttpMethod(); - String response = request(link.getHref(), httpMethod, parameters); + String response = request(link.getHref(), httpMethod, timeout, parameters); return ResourceDTOFactory.get(response); } public String request(String href, HttpMethod httpMethod, Map parameters) throws OpenShiftException { + return request(href, httpMethod, IHttpClient.NO_TIMEOUT, parameters); + } + + public String request(String href, HttpMethod httpMethod, int timeout, Map parameters) throws OpenShiftException { URL url = getUrl(href); try { - return request(url, httpMethod, parameters); + return request(url, httpMethod, timeout, parameters); } catch (UnsupportedEncodingException e) { throw new OpenShiftException(e, e.getMessage()); } catch (UnauthorizedException e) { @@ -116,7 +131,8 @@ public String request(String href, HttpMethod httpMethod, Map pa url.toString(), e, e.getMessage(), "Could not request {0}: {1}", url.toString(), getResponseMessage(e)); } catch (SocketTimeoutException e) { - throw new OpenShiftTimeoutException(url.toString(), e, e.getMessage(), "Could not request url {0}, connection timed out", url.toString()); + throw new OpenShiftTimeoutException(url.toString(), e, e.getMessage(), + "Could not request url {0}, connection timed out", url.toString()); } } @@ -141,20 +157,20 @@ private String getResponseMessage(HttpClientException clientException) { } } - private String request(URL url, HttpMethod httpMethod, Map parameters) + private String request(URL url, HttpMethod httpMethod, int timeout, Map parameters) throws HttpClientException, SocketTimeoutException, OpenShiftException, UnsupportedEncodingException { LOGGER.info("Requesting {} with protocol {} on {}", new Object[] { httpMethod.name(), client.getAcceptVersion(), url }); switch (httpMethod) { case GET: - return client.get(url); + return client.get(url, timeout); case POST: - return client.post(parameters, url); + return client.post(parameters, url, timeout); case PUT: - return client.put(parameters, url); + return client.put(parameters, url, timeout); case DELETE: - return client.delete(parameters, url); + return client.delete(parameters, url, timeout); default: throw new OpenShiftException("Unexpected HTTP method {0}", httpMethod.toString()); } diff --git a/src/main/java/com/openshift/internal/client/httpclient/UrlConnectionHttpClient.java b/src/main/java/com/openshift/internal/client/httpclient/UrlConnectionHttpClient.java index fd160dbe..ec607a81 100755 --- a/src/main/java/com/openshift/internal/client/httpclient/UrlConnectionHttpClient.java +++ b/src/main/java/com/openshift/internal/client/httpclient/UrlConnectionHttpClient.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 Red Hat, Inc. + * Copyright (c) 2013 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -43,20 +43,19 @@ /** * @author Andre Dietisheim + * @author Nicolas Spano */ public class UrlConnectionHttpClient implements IHttpClient { private static final Logger LOGGER = LoggerFactory.getLogger(UrlConnectionHttpClient.class); - private static final int DEFAULT_CONNECT_TIMEOUT = 10 * 1000; - private static final int DEFAULT_READ_TIMEOUT = 2 * 60 * 1000; private static final String SYSPROP_OPENSHIFT_CONNECT_TIMEOUT = "com.openshift.httpclient.timeout"; private static final String SYSPROP_DEFAULT_CONNECT_TIMEOUT = "sun.net.client.defaultConnectTimeout"; private static final String SYSPROP_DEFAULT_READ_TIMEOUT = "sun.net.client.defaultReadTimeout"; - private static final String SYSPROP_ENABLE_SNI_EXTENSION = "jsse.enableSNIExtension"; private static final String USERAGENT_FOR_KEYAUTH = "OpenShift"; + private String userAgent; private boolean sslChecks; private String username; @@ -71,7 +70,7 @@ public UrlConnectionHttpClient(String username, String password, String userAgen IMediaType requestMediaType, String acceptedMediaType, String version) { this(username, password, userAgent, sslChecks, requestMediaType, acceptedMediaType, version, null, null); } - + public UrlConnectionHttpClient(String username, String password, String userAgent, boolean sslChecks, IMediaType requestMediaType, String acceptedMediaType, String version, String authKey, String authIV) { this.username = username; @@ -84,7 +83,8 @@ public UrlConnectionHttpClient(String username, String password, String userAgen this.authIV = authIV; this.acceptVersion = version; } - + + /** TODO: unify with #setUserAgent **/ private String setupUserAgent(String authKey, String authIV, String userAgent) { if (!StringUtils.isEmpty(authKey)) { if (userAgent == null) { @@ -99,16 +99,24 @@ private String setupUserAgent(String authKey, String authIV, String userAgent) { public void setAcceptedMediaType(String acceptedMediaType) { this.acceptedMediaType = acceptedMediaType; } - + public String getAcceptedMediaType() { - return this.acceptedMediaType; + return acceptedMediaType; } - public String get(URL url) throws HttpClientException, SocketTimeoutException { + return get(url, NO_TIMEOUT); + } + + @Override + public String get(URL url, int timeout) throws HttpClientException, SocketTimeoutException { + HttpURLConnection connection = null; - try { - return write(null, HttpMethod.GET.toString(), url); + try { + return write(null, HttpMethod.GET.toString(), url, timeout); + } catch (SocketTimeoutException e) { + throw e; + /* TODO: cleanup exception handling */ } catch (IOException e) { throw createException(e, connection); } finally { @@ -123,7 +131,7 @@ public void setUserAgent(String userAgent) { public String getUserAgent() { return userAgent; } - + public void setAcceptVersion(String version) { this.acceptVersion = version; } @@ -131,14 +139,20 @@ public void setAcceptVersion(String version) { public String getAcceptVersion() { return acceptVersion; } - + public String put(Map parameters, URL url) throws SocketTimeoutException, UnsupportedEncodingException, HttpClientException { return put(requestMediaType.encodeParameters(parameters), url); } + @Override + public String put(Map parameters, URL url, int timeout) + throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException { + return write(requestMediaType.encodeParameters(parameters), HttpMethod.PUT.toString(), url, timeout); + } + protected String put(String data, URL url) throws HttpClientException, SocketTimeoutException { - return write(data, HttpMethod.PUT.toString(), url); + return write(data, HttpMethod.PUT.toString(), url, NO_TIMEOUT); } public String post(Map parameters, URL url) @@ -147,28 +161,40 @@ public String post(Map parameters, URL url) } protected String post(String data, URL url) throws HttpClientException, SocketTimeoutException { - return write(data, HttpMethod.POST.toString(), url); + return write(data, HttpMethod.POST.toString(), url, NO_TIMEOUT); } + public String post(Map data, URL url, int timeout) throws HttpClientException, SocketTimeoutException, + UnsupportedEncodingException { + return write(requestMediaType.encodeParameters(data), HttpMethod.POST.toString(), url, timeout); + } + public String delete(Map parameters, URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException { return delete(requestMediaType.encodeParameters(parameters), url); } + @Override + public String delete(Map parameters, URL url, int timeout) throws HttpClientException, + SocketTimeoutException, + UnsupportedEncodingException { + return write(requestMediaType.encodeParameters(parameters), HttpMethod.DELETE.toString(), url, timeout); + } + public String delete(URL url) throws HttpClientException, SocketTimeoutException, UnsupportedEncodingException { return delete((String) null, url); } protected String delete(String data, URL url) throws HttpClientException, SocketTimeoutException { - return write(data, HttpMethod.DELETE.toString(), url); + return write(data, HttpMethod.DELETE.toString(), url, NO_TIMEOUT); } - protected String write(String data, String requestMethod, URL url) + protected String write(String data, String requestMethod, URL url, int timeout) throws SocketTimeoutException, HttpClientException { HttpURLConnection connection = null; try { - connection = createConnection(username, password, authKey, authIV, userAgent, url); + connection = createConnection(username, password, authKey, authIV, userAgent, url, timeout); connection.setRequestMethod(requestMethod); connection.setDoOutput(true); if (data != null) { @@ -176,6 +202,8 @@ protected String write(String data, String requestMethod, URL url) StreamUtils.writeTo(data.getBytes(), connection.getOutputStream()); } return StreamUtils.readToString(connection.getInputStream()); + } catch (SocketTimeoutException e) { + throw e; } catch (IOException e) { throw createException(e, connection); } finally { @@ -220,7 +248,7 @@ protected String createErrorMessage(IOException ioe, HttpURLConnection connectio return errorMessage; } StringBuilder builder = new StringBuilder("Connection to ") - .append(connection.getURL()); + .append(connection.getURL()); String reason = connection.getResponseMessage(); if (!StringUtils.isEmpty(reason)) { builder.append(": ").append(reason); @@ -228,7 +256,6 @@ protected String createErrorMessage(IOException ioe, HttpURLConnection connectio return builder.toString(); } - private boolean isHttps(URL url) { return "https".equals(url.getProtocol()); } @@ -255,11 +282,11 @@ private void setPermissiveSSLSocketFactory(HttpsURLConnection connection) { protected HttpURLConnection createConnection(String username, String password, String userAgent, URL url) throws IOException { - return createConnection(username, password, null, null, userAgent, url); + return createConnection(username, password, null, null, userAgent, url, NO_TIMEOUT); } - - protected HttpURLConnection createConnection(String username, String password, String authKey, String authIV, String userAgent, URL url) - throws IOException { + + protected HttpURLConnection createConnection(String username, String password, String authKey, String authIV, + String userAgent, URL url, int timeout) throws IOException { LOGGER.trace( "creating connection to {} using username \"{}\" and password \"{}\"", new Object[] { url, username, password }); @@ -270,15 +297,15 @@ protected HttpURLConnection createConnection(String username, String password, S connection.setDoInput(true); connection.setAllowUserInteraction(false); setConnectTimeout(connection); - setReadTimeout(connection); + setReadTimeout(timeout, connection); // wont work when switching http->https // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4620571 connection.setInstanceFollowRedirects(true); setAcceptHeader(connection); setUserAgent(connection); - + connection.setRequestProperty(PROPERTY_CONTENT_TYPE, requestMediaType.getType()); - + return connection; } @@ -287,8 +314,8 @@ private void setUserAgent(HttpURLConnection connection) { if (!StringUtils.isEmpty(authKey)) { userAgent = USERAGENT_FOR_KEYAUTH; } - - if (userAgent != null){ + + if (userAgent != null) { connection.setRequestProperty(PROPERTY_USER_AGENT, userAgent); } } @@ -304,7 +331,8 @@ private void setAcceptHeader(HttpURLConnection connection) { connection.setRequestProperty(PROPERTY_ACCEPT, builder.toString()); } - private void setAuthorisation(String username, String password, String authKey, String authIV, HttpURLConnection connection) { + private void setAuthorisation(String username, String password, String authKey, String authIV, + HttpURLConnection connection) { if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) { if (authKey != null && authIV != null) { @@ -329,22 +357,26 @@ private void setSSLChecks(URL url, HttpURLConnection connection) { } private void setConnectTimeout(URLConnection connection) { - int timeout = getSystemPropertyInteger(SYSPROP_OPENSHIFT_CONNECT_TIMEOUT); - if (timeout > -1) { - connection.setConnectTimeout(timeout); - return; - } - timeout = getSystemPropertyInteger(SYSPROP_DEFAULT_CONNECT_TIMEOUT); - if (timeout == -1) { - connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); - } + int timeout = getTimeout( + getSystemPropertyInteger(SYSPROP_OPENSHIFT_CONNECT_TIMEOUT), + getSystemPropertyInteger(SYSPROP_DEFAULT_CONNECT_TIMEOUT), + DEFAULT_CONNECT_TIMEOUT); + connection.setConnectTimeout(timeout); } - private void setReadTimeout(URLConnection connection) { - int timeout = getSystemPropertyInteger(SYSPROP_DEFAULT_READ_TIMEOUT); - if (timeout == -1) { - connection.setReadTimeout(DEFAULT_READ_TIMEOUT); + private void setReadTimeout(int timeout, URLConnection connection) { + timeout = getTimeout(timeout, getSystemPropertyInteger(SYSPROP_DEFAULT_READ_TIMEOUT), DEFAULT_READ_TIMEOUT); + connection.setReadTimeout(timeout); + } + + private int getTimeout(int timeout, int systemPropertyTimeout, int defaultTimeout) { + if (timeout == NO_TIMEOUT) { + timeout = systemPropertyTimeout; + if (timeout == NO_TIMEOUT) { + timeout = defaultTimeout; + } } + return timeout; } private int getSystemPropertyInteger(String key) { @@ -376,5 +408,4 @@ public boolean verify(String hostname, SSLSession sslSession) { return true; } } - } diff --git a/src/test/java/com/openshift/client/fakes/HttpClientFake.java b/src/test/java/com/openshift/client/fakes/HttpClientFake.java index 08c58731..6e545674 100644 --- a/src/test/java/com/openshift/client/fakes/HttpClientFake.java +++ b/src/test/java/com/openshift/client/fakes/HttpClientFake.java @@ -12,8 +12,10 @@ import java.io.FileNotFoundException; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.net.URL; +import java.util.Map; import com.openshift.client.OpenShiftException; import com.openshift.client.utils.OpenShiftTestConfiguration; @@ -23,6 +25,7 @@ /** * @author Andre Dietisheim + * @author Nicolas Spano */ public class HttpClientFake extends UrlConnectionHttpClient { @@ -31,7 +34,7 @@ public HttpClientFake(String mediaType, String version) throws FileNotFoundExcep } @Override - protected String write(String data, String requestMethod, URL url) + protected String write(String data, String requestMethod, URL url, int timeout) throws SocketTimeoutException, HttpClientException { return data; } @@ -46,4 +49,5 @@ protected HttpClientFake(OpenShiftTestConfiguration configuration, String mediaT version); } + } diff --git a/src/test/java/com/openshift/client/fakes/HttpServerFake.java b/src/test/java/com/openshift/client/fakes/HttpServerFake.java index 9d8a1d46..1a0e2ef5 100644 --- a/src/test/java/com/openshift/client/fakes/HttpServerFake.java +++ b/src/test/java/com/openshift/client/fakes/HttpServerFake.java @@ -36,6 +36,7 @@ /** * @author André Dietisheim + * @author Nicolas Spano */ public class HttpServerFake { @@ -110,6 +111,9 @@ public void silentlyClose(ServerSocket serverSocket) { } } + protected void write(byte[] bytes, OutputStream outputStream) throws IOException{ + outputStream.write(bytes); + } private class ServerFakeSocket implements Runnable { @@ -121,7 +125,7 @@ public void run() { String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); - outputStream.write(response.getBytes()); + write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); diff --git a/src/test/java/com/openshift/client/fakes/WaitingHttpServerFake.java b/src/test/java/com/openshift/client/fakes/WaitingHttpServerFake.java new file mode 100644 index 00000000..7afdfe8b --- /dev/null +++ b/src/test/java/com/openshift/client/fakes/WaitingHttpServerFake.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2013 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ +package com.openshift.client.fakes; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author Nicolas Spano + * @author Andre Dietisheim + */ +public class WaitingHttpServerFake extends HttpServerFake { + + private long delay; + + @Override + protected void write(byte[] text, OutputStream outputStream) throws IOException { + + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + //Intentional ignore + return ; + } + } + + public WaitingHttpServerFake(long delay){ + this.delay = delay; + } +} diff --git a/src/test/java/com/openshift/client/utils/ApplicationAssert.java b/src/test/java/com/openshift/client/utils/ApplicationAssert.java index 56156ce6..c991826e 100644 --- a/src/test/java/com/openshift/client/utils/ApplicationAssert.java +++ b/src/test/java/com/openshift/client/utils/ApplicationAssert.java @@ -253,4 +253,23 @@ public ApplicationAssert hasMessage(IField field, ISeverity severity) throws IOE return this; } + public ApplicationAssert hasMessage(IField field) throws IOException { + Messages messages = application.getMessages(); + assertThat(messages).isNotNull(); + List matchingMessages = messages.getBy(field); + assertThat(matchingMessages).isNotEmpty(); + return this; + } + + public ApplicationAssert hasResultFieldOrResultSeverityMessage() throws IOException { + Messages messages = application.getMessages(); + assertThat(messages).isNotNull(); + List matchingMessages = messages.getBy(IField.RESULT); + if (matchingMessages == null + || matchingMessages.isEmpty()) { + matchingMessages = messages.getBy(IField.DEFAULT, ISeverity.RESULT); + assertThat(matchingMessages).isNotEmpty(); + } + return this; + } } diff --git a/src/test/java/com/openshift/client/utils/Samples.java b/src/test/java/com/openshift/client/utils/Samples.java index f6d8ea28..8575f702 100644 --- a/src/test/java/com/openshift/client/utils/Samples.java +++ b/src/test/java/com/openshift/client/utils/Samples.java @@ -33,7 +33,7 @@ public enum Samples { GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS("get-domains-foobarz-applications_noapps.json"), // 1.2 GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6("get-domains-foobarz-applications-springeap6.json"), // 1.2 GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_2ALIAS("get-domains-foobarz-applications-springeap6_2alias.json"), // 1.2 - GET_DOMAINS_FOOBARZ_APPLICATONS_SPRINGEAP6_0ALIAS("get-domains-foobarz-applications-springeap6_0alias.json"), // 1.2 + GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_0ALIAS("get-domains-foobarz-applications-springeap6_0alias.json"), // 1.2 POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT("post-stop-domains-foobarz-applications-springeap6-events.json"), // 1.2 POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS("post-scalable-domains-foobarz-applications.json"), // 1.2 POST_JEKYLL_DOMAINS_FOOBARZ_APPLICATIONS("post-jekyll-domains-foobarz-applications.json"), // 1.2 @@ -51,7 +51,7 @@ public enum Samples { // user GET_API("get-api.json"), // 1.2 - GET_USER_JSON("get-user.json"), // 1.2 + GET_USER("get-user.json"), // 1.2 GET_USER_KEYS_2KEYS("get-user-keys_2keys.json"), // 1.2 GET_USER_KEYS_NONE("get-user-keys_none.json"), // 1.2 GET_USER_KEYS_1KEY("get-user-keys_1key.json"), // 1.2 @@ -68,7 +68,7 @@ public enum Samples { this.filePath = SAMPLES_FOLDER + fileName; } - public String getContentAsString() throws Throwable { + public String getContentAsString() { String content = null; try { final InputStream contentStream = Samples.class.getResourceAsStream(filePath); diff --git a/src/test/java/com/openshift/client/utils/TestConnectionFactory.java b/src/test/java/com/openshift/client/utils/TestConnectionFactory.java index c6d2f553..43c04f68 100644 --- a/src/test/java/com/openshift/client/utils/TestConnectionFactory.java +++ b/src/test/java/com/openshift/client/utils/TestConnectionFactory.java @@ -13,6 +13,7 @@ import java.io.FileNotFoundException; import java.io.IOException; +import com.openshift.client.IHttpClient; import com.openshift.client.IOpenShiftConnection; import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.OpenShiftException; @@ -29,14 +30,27 @@ public IOpenShiftConnection getConnection() throws FileNotFoundException, IOExce OpenShiftTestConfiguration configuration = new OpenShiftTestConfiguration(); - IOpenShiftConnection connection = getConnection( + return getConnection( configuration.getClientId() , configuration.getRhlogin() , configuration.getPassword() , null , null , configuration.getLibraServer()); - - return connection; + } + + public IOpenShiftConnection getConnection(String password, String server, IHttpClient httpClient) throws FileNotFoundException, IOException, OpenShiftException { + OpenShiftTestConfiguration configuration = new OpenShiftTestConfiguration(); + return getConnection( + configuration.getClientId(), + configuration.getRhlogin(), + password, + server, + httpClient); + } + + public IOpenShiftConnection getConnection(IHttpClient httpClient) throws FileNotFoundException, IOException, OpenShiftException { + OpenShiftTestConfiguration configuration = new OpenShiftTestConfiguration(); + return getConnection(configuration.getPassword(), configuration.getLibraServer(), httpClient); } } diff --git a/src/test/java/com/openshift/internal/client/APIResourceTest.java b/src/test/java/com/openshift/internal/client/APIResourceTest.java index 3fe89f92..ccaf8e83 100644 --- a/src/test/java/com/openshift/internal/client/APIResourceTest.java +++ b/src/test/java/com/openshift/internal/client/APIResourceTest.java @@ -10,22 +10,18 @@ ******************************************************************************/ package com.openshift.internal.client; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.util.List; import org.junit.Before; import org.junit.Test; -import com.openshift.client.IHttpClient; import com.openshift.client.IOpenShiftConnection; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.cartridge.IEmbeddableCartridge; import com.openshift.client.cartridge.IStandaloneCartridge; import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; /** * @author Xavier Coulon @@ -33,19 +29,11 @@ */ public class APIResourceTest { - private IHttpClient mockClient; - private IOpenShiftConnection connection; @Before public void setup() throws Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/cartridges"))) - .thenReturn(Samples.GET_CARTRIDGES.getContentAsString()); - connection = new OpenShiftConnectionFactory() - .getConnection(new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); + connection = new TestConnectionFactory().getConnection(new HttpClientMockDirector().client()); } @Test diff --git a/src/test/java/com/openshift/internal/client/ApplicationResourceTest.java b/src/test/java/com/openshift/internal/client/ApplicationResourceTest.java index 5d80cd47..adac7f1b 100644 --- a/src/test/java/com/openshift/internal/client/ApplicationResourceTest.java +++ b/src/test/java/com/openshift/internal/client/ApplicationResourceTest.java @@ -13,22 +13,16 @@ import static com.openshift.client.utils.Samples.GET_DOMAINS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6; +import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_0ALIAS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_2ALIAS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_1EMBEDDED; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED; -import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATONS_SPRINGEAP6_0ALIAS; import static com.openshift.client.utils.Samples.POST_MYSQL_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES; import static com.openshift.client.utils.Samples.POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.net.SocketTimeoutException; import java.util.Arrays; @@ -44,49 +38,44 @@ import com.openshift.client.IDomain; import com.openshift.client.IField; import com.openshift.client.IHttpClient; -import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IUser; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.OpenShiftEndpointException; import com.openshift.client.OpenShiftTimeoutException; import com.openshift.client.cartridge.EmbeddableCartridge; import com.openshift.client.cartridge.IEmbeddedCartridge; import com.openshift.client.utils.EmbeddedCartridgeAssert; import com.openshift.client.utils.MessageAssert; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; import com.openshift.internal.client.httpclient.HttpClientException; import com.openshift.internal.client.httpclient.InternalServerErrorException; /** * @author Xavier Coulon * @author Andre Dietisheim + * @author Nicolas Spano */ public class ApplicationResourceTest { private IDomain domain; private IHttpClient mockClient; + private HttpClientMockDirector mockDirector; @Before public void setup() throws Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))).thenReturn( - Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))) - .thenReturn(GET_DOMAINS.getContentAsString()); - final IOpenShiftConnection connection = - new OpenShiftConnectionFactory().getConnection( - new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); - IUser user = connection.getUser(); + this.mockDirector = new HttpClientMockDirector(); + this.mockClient = mockDirector + .mockGetDomains(GET_DOMAINS) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS) + .mockGetApplication("foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6) + .mockGetEmbeddableCartridges("foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_1EMBEDDED) + .client(); + IUser user = new TestConnectionFactory().getConnection(mockClient).getUser(); this.domain = user.getDomain("foobarz"); } @Test public void shouldDestroyApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); assertThat(domain).isNotNull(); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app).isNotNull(); @@ -99,58 +88,52 @@ public void shouldDestroyApplication() throws Throwable { @Test public void shouldStopApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/honkabons2/applications/springeap6/events"))).thenReturn( - POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT.getContentAsString()); + mockDirector.mockPostApplicationEvent( + "foobarz", "springeap6", POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT); final IApplication app = domain.getApplicationByName("springeap6"); // operation app.stop(); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldForceStopApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); + mockDirector + .mockPostApplicationEvent( + "honkabonka2", "springeap6", POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT); final IApplication app = domain.getApplicationByName("springeap6"); // operation app.stop(true); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldStartApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); + mockDirector + .mockPostApplicationEvent( + "honkabonka2", "springeap6", POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT); final IApplication app = domain.getApplicationByName("springeap6"); // operation app.start(); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldRestartApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); + mockDirector + .mockPostApplicationEvent( + "honkabonka2", "springeap6", POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT); final IApplication app = domain.getApplicationByName("springeap6"); // operation app.restart(); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); - + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Ignore("Need higher quotas on stg") @@ -161,10 +144,7 @@ public void shouldScaleDownApplication() throws Throwable { @Test public void shouldNotScaleDownApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenThrow( + mockDirector.mockPostApplicationEvent("foobarz", "springeap6", new InternalServerErrorException( "Failed to add event scale-down to application springeap6 due to: Cannot scale a non-scalable application")); final IApplication app = domain.getApplicationByName("springeap6"); @@ -176,7 +156,7 @@ public void shouldNotScaleDownApplication() throws Throwable { assertThat(e.getCause()).isInstanceOf(InternalServerErrorException.class); } // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Ignore("Need higher quotas on stg") @@ -187,11 +167,10 @@ public void shouldScaleUpApplication() throws Throwable { @Test public void shouldNotScaleUpApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenThrow( - new InternalServerErrorException( + mockDirector.mockPostApplicationEvent( + "foobarz", "springeap6", POST_STOP_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_EVENT) + .mockPostApplicationEvent("foobarz","springeap6", + new InternalServerErrorException( "Failed to add event scale-up to application springeap6 due to: Cannot scale a non-scalable application")); final IApplication app = domain.getApplicationByName("springeap6"); // operation @@ -202,36 +181,27 @@ public void shouldNotScaleUpApplication() throws Throwable { assertThat(e.getCause()).isInstanceOf(InternalServerErrorException.class); } // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldAddAliasToApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_2ALIAS.getContentAsString()); + mockDirector.mockPostApplicationEvent( + "foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_2ALIAS); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app.getAliases()).hasSize(1).contains("jbosstools.org"); // operation app.addAlias("redhat.com"); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); assertThat(app.getAliases()).hasSize(2).contains("jbosstools.org", "redhat.com"); } @Test public void shouldNotAddExistingAliasToApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenThrow( + mockDirector.mockPostApplicationEvent("foobarz","springeap6", new InternalServerErrorException( "Failed to add event add-alias to application springeap6 due to: Alias 'jbosstools.org' already exists for 'springeap6'")); final IApplication app = domain.getApplicationByName("springeap6"); @@ -245,34 +215,29 @@ public void shouldNotAddExistingAliasToApplication() throws Throwable { } // verifications assertThat(app.getAliases()).hasSize(1).contains("jbosstools.org"); - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldRemoveAliasFromApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATONS_SPRINGEAP6_0ALIAS.getContentAsString()); + mockDirector + .mockPostApplicationEvent( + "foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_0ALIAS); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app.getAliases()).hasSize(1).contains("jbosstools.org"); // operation app.removeAlias("jbosstools.org"); // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); assertThat(app.getAliases()).hasSize(0); } @Test public void shouldNotRemoveAliasFromApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events"))) - .thenThrow( + mockDirector + .mockPostApplicationEvent("foobarz","springeap6", new InternalServerErrorException( "Failed to add event remove-alias to application springeap6 due to: Alias 'openshift-origin.org' does not exist for 'springeap6'")); final IApplication app = domain.getApplicationByName("springeap6"); @@ -287,18 +252,15 @@ public void shouldNotRemoveAliasFromApplication() throws Throwable { } // verifications assertThat(app.getAliases()).hasSize(1).contains("jbosstools.org"); - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/events")); + mockDirector.verifyPostApplicationEvent("foobarz", "springeap6"); } @Test public void shouldListExistingCartridges() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); + mockDirector + .mockGetEmbeddableCartridges("foobarz", "springeap6", + GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED); final IApplication app = domain.getApplicationByName("springeap6"); // operation final List embeddedCartridges = app.getEmbeddedCartridges(); @@ -309,44 +271,32 @@ public void shouldListExistingCartridges() throws Throwable { @Test public void shouldReloadExistingEmbeddedCartridges() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_1EMBEDDED.getContentAsString()); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app.getEmbeddedCartridges()).hasSize(1); // simulate new content on openshift, that should be grabbed while doing // a refresh() - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); + mockDirector.mockGetEmbeddableCartridges("foobarz", "springeap6", + GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED); // operation app.refresh(); assertThat(app.getEmbeddedCartridges()).hasSize(2); - verify(mockClient, times(2)).get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges")); + mockDirector.verifyReloadEmbeddableCartridges("foobarz", "springeap6"); } @Test public void shouldAddCartridgeToApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_1EMBEDDED.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(POST_MYSQL_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES.getContentAsString()); + mockDirector.mockAddEmbeddableCartridge("foobarz", "springeap6", + POST_MYSQL_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES); final IApplication app = domain.getApplicationByName("springeap6"); String mySql51Name = "mysql-5.1"; + assertThat(app.getEmbeddedCartridges()).hasSize(1); // operation app.addEmbeddableCartridge(new EmbeddableCartridge(mySql51Name)); // verifications - verify(mockClient, times(1)) - .post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/cartridges")); + mockDirector.verifyAddEmbeddableCartridge("foobarz", "springeap6"); assertThat(app.getEmbeddedCartridges()).hasSize(2); IEmbeddedCartridge mySqlCartridge = app.getEmbeddedCartridge(mySql51Name); new EmbeddedCartridgeAssert(mySqlCartridge) @@ -373,14 +323,9 @@ public void shouldAddCartridgeToApplication() throws Throwable { @Test public void shouldNotAddCartridgeToApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenThrow(new SocketTimeoutException("mock...")); + mockDirector + .mockGetEmbeddableCartridges("foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED) + .mockAddEmbeddableCartridge("foobarz", "springeap6", new SocketTimeoutException("mock...")); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app.getEmbeddedCartridges()).hasSize(2); // operation @@ -391,8 +336,7 @@ public void shouldNotAddCartridgeToApplication() throws Throwable { // ok } // verifications - verify(mockClient, times(1)).post(anyMapOf(String.class, Object.class), - urlEndsWith("/domains/foobarz/applications/springeap6/cartridges")); + mockDirector.verifyAddEmbeddableCartridge("foobarz", "springeap6"); assertThat(app.getEmbeddedCartridge("postgresql-8.4")).isNull(); assertThat(app.getEmbeddedCartridges()).hasSize(2); } @@ -400,19 +344,14 @@ public void shouldNotAddCartridgeToApplication() throws Throwable { @Test public void shouldRemoveCartridgeFromApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); + mockDirector.mockGetEmbeddableCartridges( + "foobarz", "springeap6",GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED); final IApplication application = domain.getApplicationByName("springeap6"); assertThat(application.getEmbeddedCartridges()).hasSize(2); // operation application.getEmbeddedCartridge("mysql-5.1").destroy(); // verifications - verify(mockClient, times(1)).delete(anyMapOf(String.class, Object.class), - urlEndsWith("/domains/foobarz/applications/springeap6/cartridges/mysql-5.1")); + mockDirector.verifyDeleteEmbeddableCartridge("foobarz", "springeap6", "mysql-5.1"); assertThat(application.getEmbeddedCartridge("mysql-5.1")).isNull(); assertThat(application.getEmbeddedCartridges()).hasSize(1); } @@ -420,14 +359,9 @@ public void shouldRemoveCartridgeFromApplication() throws Throwable { @Test public void shouldNotRemoveCartridgeFromApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); - when(mockClient.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications/springeap6/cartridges/mysql-5.1"))) - .thenThrow(new SocketTimeoutException("mock...")); + mockDirector.mockGetEmbeddableCartridges( + "foobarz", "springeap6",GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED) + .mockRemoveEmbeddableCartridge("foobarz", "springeap6", "mysql-5.1", new SocketTimeoutException("mock...")); final IApplication application = domain.getApplicationByName("springeap6"); assertThat(application.getEmbeddedCartridges()).hasSize(2); // operation @@ -439,16 +373,13 @@ public void shouldNotRemoveCartridgeFromApplication() throws Throwable { // ok } // verifications - verify(mockClient, times(1)).delete(anyMapOf(String.class, Object.class), - urlEndsWith("/domains/foobarz/applications/springeap6/cartridges/mysql-5.1")); + mockDirector.verifyDeleteEmbeddableCartridge("foobarz", "springeap6", "mysql-5.1"); assertThat(application.getEmbeddedCartridges()).hasSize(2).contains(mysql); } @Test public void shouldWaitUntilTimeout() throws HttpClientException, Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app).isNotNull().isInstanceOf(ApplicationResource.class); ApplicationResource spy = Mockito.spy(((ApplicationResource) app)); @@ -466,8 +397,6 @@ public void shouldWaitUntilTimeout() throws HttpClientException, Throwable { @Test public void shouldEndBeforeTimeout() throws HttpClientException, Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); long startTime = System.currentTimeMillis(); long timeout = 10 * 1000; final IApplication app = domain.getApplicationByName("springeap6"); @@ -485,8 +414,6 @@ public void shouldEndBeforeTimeout() throws HttpClientException, Throwable { @Test public void shouldGetForwardablePorts() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); final IApplication app = domain.getApplicationByName("springeap6"); assertThat(app).isNotNull().isInstanceOf(ApplicationResource.class); String[] rhcListPortsOutput = new String[] { @@ -514,5 +441,7 @@ public void shouldGetForwardablePorts() throws Throwable { .onProperty("remoteAddress").containsExactly("127.7.233.2", "127.7.233.3", "127.7.233.1", "127.7.233.1", "127.7.233.1", "127.7.233.1", "127.7.233.1", "127.7.233.1", "127.7.233.1", "5190d701500446506a0000e4-foobarz.rhcloud.com"); assertThat(forwardablePorts) .onProperty("remotePort").containsExactly(8080, 8080, 3528, 4447, 5445, 5455, 8080, 9990, 9999, 56756); - } + } + + } diff --git a/src/test/java/com/openshift/internal/client/DomainResourceIntegrationTest.java b/src/test/java/com/openshift/internal/client/DomainResourceIntegrationTest.java index 4e00ef08..42f92a0a 100755 --- a/src/test/java/com/openshift/internal/client/DomainResourceIntegrationTest.java +++ b/src/test/java/com/openshift/internal/client/DomainResourceIntegrationTest.java @@ -325,8 +325,8 @@ public void shouldHaveCredentialsInMessage() throws Exception { applicationName, jenkins ); // verification - assertThat(new ApplicationAssert(application)) - .hasMessage(IField.DEFAULT, ISeverity.RESULT); + new ApplicationAssert(application) + .hasResultFieldOrResultSeverityMessage(); } @Test(expected = OpenShiftException.class) diff --git a/src/test/java/com/openshift/internal/client/DomainResourceTest.java b/src/test/java/com/openshift/internal/client/DomainResourceTest.java index e5e4af3b..dba68930 100644 --- a/src/test/java/com/openshift/internal/client/DomainResourceTest.java +++ b/src/test/java/com/openshift/internal/client/DomainResourceTest.java @@ -22,21 +22,13 @@ import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; -import java.net.URL; import java.util.List; -import java.util.Map; import org.junit.Before; import org.junit.Ignore; @@ -44,7 +36,6 @@ import org.junit.Test; import org.junit.rules.ErrorCollector; import org.junit.rules.ExpectedException; -import org.mockito.ArgumentCaptor; import com.openshift.client.ApplicationScale; import com.openshift.client.IApplication; @@ -52,17 +43,16 @@ import com.openshift.client.IField; import com.openshift.client.IGearProfile; import com.openshift.client.IHttpClient; -import com.openshift.client.IOpenShiftConnection; import com.openshift.client.ISeverity; import com.openshift.client.IUser; import com.openshift.client.InvalidCredentialsOpenShiftException; import com.openshift.client.Message; import com.openshift.client.Messages; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.OpenShiftEndpointException; import com.openshift.client.OpenShiftException; import com.openshift.client.utils.MessageAssert; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; +import com.openshift.internal.client.HttpClientMockDirector.Pair; import com.openshift.internal.client.httpclient.BadRequestException; import com.openshift.internal.client.httpclient.HttpClientException; import com.openshift.internal.client.httpclient.UnauthorizedException; @@ -79,8 +69,9 @@ public class DomainResourceTest { private IUser user; private IDomain domain; - private IHttpClient mockClient; - + private IHttpClient clientMock; + private HttpClientMockDirector mockDirector; + @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -89,37 +80,26 @@ public class DomainResourceTest { @Before public void setup() throws Throwable { - this.mockClient = createMockClient(GET_DOMAINS); - this.user = createUser(mockClient); + this.mockDirector = new HttpClientMockDirector(); + this.clientMock = mockDirector.mockGetDomains(GET_DOMAINS).client(); + this.user = new TestConnectionFactory().getConnection(clientMock).getUser(); this.domain = user.getDomain("foobarz"); } - private IHttpClient createMockClient(Samples domainsResponse) throws SocketTimeoutException, Throwable { - IHttpClient mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))).thenReturn(Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))).thenReturn(domainsResponse.getContentAsString()); - return mockClient; - } - - private IUser createUser(IHttpClient client) throws FileNotFoundException, IOException { - final IOpenShiftConnection connection = new OpenShiftConnectionFactory().getConnection(new RestService( - "http://mock", "clientId", client), "foo@redhat.com", "bar"); - return connection.getUser(); - } - @Test public void shouldLoadEmptyListOfDomains() throws Throwable { // pre-conditions - IHttpClient client = createMockClient(GET_DOMAINS_EMPTY); - IUser user = createUser(client); + HttpClientMockDirector mockBuilder = new HttpClientMockDirector(); + IHttpClient clientMock = mockBuilder.mockGetDomains(GET_DOMAINS_EMPTY).client(); + IUser user = new TestConnectionFactory().getConnection(clientMock).getUser(); // operation final List domains = user.getDomains(); // verifications assertThat(domains).hasSize(0); // 3 calls: /API + /API/user + /API/domains - verify(client, times(3)).get(any(URL.class)); + mockBuilder + .verifyGetAny(3) + .verifyGetDomains(); } @Test @@ -130,14 +110,13 @@ public void shouldLoadSingleUserDomain() throws Throwable { // verifications assertThat(domains).hasSize(1); // 3 calls: /API + /API/user + /API/domains - verify(mockClient, times(3)).get(any(URL.class)); + mockDirector.verifyGetAny(3); } @Test public void shouldCreateNewDomain() throws Throwable { // pre-conditions - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains"))).thenReturn( - GET_DOMAINS_FOOBARS.getContentAsString()); + mockDirector.mockCreateDomain(GET_DOMAINS_FOOBARS); int numOfDomains = user.getDomains().size(); // operation final IDomain domain = user.createDomain("foobars"); @@ -159,8 +138,7 @@ public void shouldNotRecreateExistingDomain() throws Throwable { @Test public void shouldDestroyDomain() throws Throwable { // pre-conditions - when(mockClient.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobar"))) - .thenReturn(DELETE_DOMAINS_FOOBARZ.getContentAsString()); + mockDirector.mockDeleteDomain("foobarz", DELETE_DOMAINS_FOOBARZ); // operation final IDomain domain = user.getDomain("foobarz"); domain.destroy(); @@ -172,7 +150,7 @@ public void shouldDestroyDomain() throws Throwable { @Test public void shouldNotDestroyDomainWithApp() throws Throwable { // pre-conditions - when(mockClient.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz"))) + when(clientMock.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz"), anyInt())) .thenThrow(new BadRequestException( "Domain contains applications. Delete applications first or set force to true.", null)); // operation @@ -191,8 +169,7 @@ public void shouldNotDestroyDomainWithApp() throws Throwable { @Test public void shouldUpdateDomainId() throws Throwable { // pre-conditions - when(mockClient.put(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz"))) - .thenReturn(GET_DOMAINS_FOOBARS.getContentAsString()); + mockDirector.mockRenameDomain("foobarz", GET_DOMAINS_FOOBARS); final IDomain domain = user.getDomain("foobarz"); // operation domain.rename("foobars"); @@ -202,7 +179,7 @@ public void shouldUpdateDomainId() throws Throwable { assertThat(updatedDomain).isNotNull(); assertThat(updatedDomain.getId()).isEqualTo("foobars"); assertThat(LinkRetriever.retrieveLink(updatedDomain, "UPDATE").getHref()).contains("/foobars"); - verify(mockClient, times(1)).put(anyMapOf(String.class, Object.class), any(URL.class)); + mockDirector.verifyRenameDomain("foobarz"); } @Test @@ -219,102 +196,108 @@ public void shouldListAvailableGearSizes() throws Throwable { @Test public void shouldRefreshDomainAndReloadApplications() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz"))) - .thenReturn(GET_DOMAINS_FOOBARZ.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetDomain("foobarz", GET_DOMAINS_FOOBARZ) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); + final IDomain domain = user.getDomain("foobarz"); assertThat(domain).isNotNull(); domain.getApplications(); // operation domain.refresh(); // verifications - verify(mockClient, times(1)).get(urlEndsWith("/domains/foobarz")); // explicit refresh on this location - verify(mockClient, times(2)).get(urlEndsWith("/domains/foobarz/applications")); // two calls, before and while refresh + mockDirector + .verifyGetDomain("foobarz") // explicit refresh + .verifyGetApplications("foobarz", 2); // two calls, before and while refresh } @Test public void shouldRefreshDomainAndNotReloadApplications() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz"))) - .thenReturn(GET_DOMAINS_FOOBARZ.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetDomain("foobarz", GET_DOMAINS_FOOBARZ) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); final IDomain domain = user.getDomain("foobarz"); assertThat(domain).isNotNull(); // operation domain.refresh(); // verifications - verify(mockClient, times(1)).get(urlEndsWith("/domains")); // explicit refresh on this location - verify(mockClient, times(0)).get(urlEndsWith("/domains/foobarz/applications")); // no call, neither before and while refresh + mockDirector + .verifyGetDomains() // explicit refresh + .verifyGetApplications("foobarz", 0); // // no call, neither before and while refresh } @Test public void shouldLoadListOfApplicationsWithNoElement() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS); // operation final List apps = domain.getApplications(); // verifications assertThat(apps).isEmpty(); - // 4 calls: /API + /API/user + /API/domains + - // /API/domains/foobar/applications - verify(mockClient, times(4)).get(any(URL.class)); + mockDirector + .verifyGetAPI() + .verifyGetUser() + .verifyGetDomains() + .verifyGetApplications("foobarz", 1) + .verifyGetAny(4); } @Test public void shouldLoadListOfApplicationsWith2Elements() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); // operation final List apps = domain.getApplications(); // verifications assertThat(apps).hasSize(2); - // 4 calls: /API + /API/user + /API/domains + - // /API/domains/foobarz/applications - verify(mockClient, times(4)).get(any(URL.class)); + mockDirector + .verifyGetAPI() + .verifyGetUser() + .verifyGetDomains() + .verifyGetApplications("foobarz", 1) + .verifyGetAny(4); } @Test public void shouldNotLoadApplicationTwice() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); // operation List apps = domain.getApplications(); assertThat(apps).hasSize(2); // verifications - reset(mockClient); + reset(clientMock); apps = domain.getApplications(); // dont do new client request - verify(mockClient, times(0)).get(any(URL.class)); - + mockDirector.verifyGetAny(0); } @Test(expected = InvalidCredentialsOpenShiftException.class) public void shouldNotLoadListOfApplicationsWithInvalidCredentials() throws OpenShiftException, HttpClientException, SocketTimeoutException { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) + when(clientMock.get(urlEndsWith("/domains/foobarz/applications"), anyInt())) .thenThrow(new UnauthorizedException("invalid credentials (mock)", null)); // operation domain.getApplications(); // verifications - // expect an exception + mockDirector.verifyGetAPI() + .verifyGetUser() + .verifyGetAny(2); } @Test public void shouldCreateApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))).thenReturn( - POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); + + when(clientMock.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))) + .thenReturn(POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); // operation - final IApplication app = domain.createApplication("sample", CARTRIDGE_JBOSSAS_7, ApplicationScale.NO_SCALE, null); + final IApplication app = domain.createApplication("scalable", CARTRIDGE_JBOSSAS_7, ApplicationScale.NO_SCALE, null); // verifications assertThat(app.getName()).isEqualTo("scalable"); assertThat(app.getGearProfile().getName()).isEqualTo("small"); @@ -334,11 +317,9 @@ public void shouldCreateApplication() throws Throwable { @Test public void shouldHaveMessagesWhenCreating() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))).thenReturn( - POST_JEKYLL_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_JEKYLL_DOMAINS_FOOBARZ_APPLICATIONS); // operation final IApplication app = domain.createApplication("jekyll", CARTRIDGE_JENKINS_14); // verifications @@ -369,31 +350,29 @@ public void shouldHaveMessagesWhenCreating() throws Throwable { @Test public void shouldRequestCreateApplicationWithNameAndCartridgeOnly() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); // operation domain.createApplication("foo", CARTRIDGE_JBOSSAS_7); // verification - assertPostParameters(mockClient, + mockDirector.assertPostParameters( new Pair(IOpenShiftJsonConstants.PROPERTY_NAME, "foo"), - new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName())); + new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName())); } @Test public void shouldRequestCreateApplicationWithNameCartridgeAndScaleOnly() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); // operation domain.createApplication("foo", CARTRIDGE_JBOSSAS_7, ApplicationScale.SCALE); // verification - assertPostParameters(mockClient, + mockDirector.assertPostParameters( new Pair(IOpenShiftJsonConstants.PROPERTY_NAME, "foo"), new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName()), new Pair(IOpenShiftJsonConstants.PROPERTY_SCALE, ApplicationScale.SCALE.getValue())); @@ -402,15 +381,14 @@ public void shouldRequestCreateApplicationWithNameCartridgeAndScaleOnly() throws @Test public void shouldRequestCreateApplicationWithNameCartridgeScaleGearProfileOnly() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); // operation domain.createApplication("foo", CARTRIDGE_JBOSSAS_7, ApplicationScale.SCALE, GearProfile.JUMBO); // verification - assertPostParameters(mockClient, + mockDirector.assertPostParameters( new Pair(IOpenShiftJsonConstants.PROPERTY_NAME, "foo"), new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName()), new Pair(IOpenShiftJsonConstants.PROPERTY_SCALE, ApplicationScale.SCALE.getValue()), @@ -421,15 +399,14 @@ public void shouldRequestCreateApplicationWithNameCartridgeScaleGearProfileOnly( @Test public void shouldRequestCreateApplicationWithNameCartridgeScaleGearProfileAndGitUrl() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); // operation domain.createApplication("foo", CARTRIDGE_JBOSSAS_7, ApplicationScale.SCALE, GearProfile.JUMBO, "git://github.com/adietish/openshift-java-client.git"); // verification - assertPostParameters(mockClient, + mockDirector.assertPostParameters( new Pair(IOpenShiftJsonConstants.PROPERTY_NAME, "foo"), new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName()), new Pair(IOpenShiftJsonConstants.PROPERTY_SCALE, ApplicationScale.SCALE.getValue()), @@ -438,39 +415,10 @@ public void shouldRequestCreateApplicationWithNameCartridgeScaleGearProfileAndGi ); } - private static class Pair { - private String key; - private String value; - - private Pair(String key, String value) { - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private void assertPostParameters(IHttpClient client, Pair... pairs) throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { - ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); - verify(mockClient).post(captor.capture(), any(URL.class)); - Map postedParameters = captor.getValue(); - assertThat(postedParameters).hasSize(pairs.length); - for(Pair pair: pairs) { - assertThat(postedParameters.get(pair.getKey())).isEqualTo(pair.getValue()); - } - } - @Test(expected = OpenShiftException.class) public void shouldNotCreateApplicationWithMissingName() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) + when(clientMock.get(urlEndsWith("/domains/foobarz/applications"))) .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); // operation domain.createApplication(null, CARTRIDGE_JBOSSAS_7, null, null); @@ -481,8 +429,7 @@ public void shouldNotCreateApplicationWithMissingName() throws Throwable { @Test(expected = OpenShiftException.class) public void shouldNotCreateApplicationWithMissingCartridge() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS); // operation domain.createApplication("foo", null, null, null); // verifications @@ -492,8 +439,7 @@ public void shouldNotCreateApplicationWithMissingCartridge() throws Throwable { @Test public void shouldNotRecreateExistingApplication() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); // operation try { domain.createApplication("springeap6", CARTRIDGE_JBOSSAS_7, null, null); @@ -509,8 +455,7 @@ public void shouldNotRecreateExistingApplication() throws Throwable { @Test public void shouldGetApplicationByNameCaseInsensitive() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))).thenReturn( - GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); + mockDirector.mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS); // operation IApplication lowerCaseQueryResult = domain.getApplicationByName("springeap6"); IApplication upperCaseQueryResult = domain.getApplicationByName("SPRINGEAP6"); @@ -551,4 +496,23 @@ public void shouldNotifyAfterDomainUpdated() throws Throwable { public void shouldNotifyAfterDomainDestroyed() throws Throwable { fail("not implemented yet"); } + + @Test + public void shouldPassTimeoutToClient() throws Throwable { + // pre-conditions + int timeout = 42 * 1000; + mockDirector + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS) + .mockCreateApplication("foobarz", POST_SCALABLE_DOMAINS_FOOBARZ_APPLICATIONS); + + // operation + domain.createApplication("scalable", CARTRIDGE_JBOSSAS_7, ApplicationScale.NO_SCALE, GearProfile.SMALL, null, timeout); + + // verifications + mockDirector.verifyCreateApplication("foobarz", timeout, + new Pair(IOpenShiftJsonConstants.PROPERTY_SCALE, String.valueOf(Boolean.FALSE)), + new Pair(IOpenShiftJsonConstants.PROPERTY_GEAR_PROFILE, GearProfile.SMALL.getName()), + new Pair(IOpenShiftJsonConstants.PROPERTY_CARTRIDGE, CARTRIDGE_JBOSSAS_7.getName()), + new Pair(IOpenShiftJsonConstants.PROPERTY_NAME, "scalable")); + } } diff --git a/src/test/java/com/openshift/internal/client/EmbeddedCartridgeTest.java b/src/test/java/com/openshift/internal/client/EmbeddedCartridgeTest.java index e0d3d693..5affd00a 100644 --- a/src/test/java/com/openshift/internal/client/EmbeddedCartridgeTest.java +++ b/src/test/java/com/openshift/internal/client/EmbeddedCartridgeTest.java @@ -12,15 +12,11 @@ import static com.openshift.client.utils.Samples.GET_DOMAINS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS; -import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.net.SocketTimeoutException; import java.util.Collections; @@ -35,14 +31,12 @@ import com.openshift.client.IDomain; import com.openshift.client.IField; import com.openshift.client.IHttpClient; -import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IUser; import com.openshift.client.Message; import com.openshift.client.Messages; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.cartridge.EmbeddableCartridge; import com.openshift.client.cartridge.IEmbeddedCartridge; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; import com.openshift.internal.client.httpclient.HttpClientException; import com.openshift.internal.client.response.Link; @@ -58,29 +52,17 @@ public class EmbeddedCartridgeTest { @Before public void setUp() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions - IHttpClient mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))) - .thenReturn(Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))) - .thenReturn(GET_DOMAINS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/cartridges"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED.getContentAsString()); - final IOpenShiftConnection connection = - new OpenShiftConnectionFactory().getConnection( - new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); - this.user = connection.getUser(); + IHttpClient client = new HttpClientMockDirector() + .mockGetDomains(GET_DOMAINS) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS) + .mockGetEmbeddableCartridges("foobarz", "springeap6", + GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_CARTRIDGES_2EMBEDDED) + .client(); + this.user = new TestConnectionFactory().getConnection(client).getUser(); this.domain = user.getDomain("foobarz"); this.application = domain.getApplicationByName("springeap6"); } - + @Test public void shouldEqualsOtherCartridge() { // pre-coniditions @@ -97,7 +79,7 @@ public void shouldEqualsEmbeddableCartridge() { // operation // verification - assertEquals(new EmbeddableCartridge("redhat"), embeddedCartridgeMock); + assertEquals(new EmbeddableCartridge("redhat"), embeddedCartridgeMock); assertEquals(embeddedCartridgeMock, new EmbeddableCartridge("redhat")); assertFalse(new EmbeddableCartridge("redhat").equals(new EmbeddableCartridge("jboss"))); } @@ -147,17 +129,17 @@ public void shouldHaveDisplayName() throws Throwable { // verifications assertThat(mysql.getDisplayName()).isEqualTo("MySQL Database 5.1"); } - + private IEmbeddedCartridge createEmbeddedCartridgeMock(String name) { ApplicationResource applicationResourceMock = Mockito.mock(ApplicationResource.class); return new EmbeddedCartridgeResource( - name, - "displayName", - "description", - CartridgeType.EMBEDDED, - "embedded-info", - Collections. emptyMap(), - new Messages(Collections.> emptyMap()), - applicationResourceMock); + name, + "displayName", + "description", + CartridgeType.EMBEDDED, + "embedded-info", + Collections. emptyMap(), + new Messages(Collections.> emptyMap()), + applicationResourceMock); } } diff --git a/src/test/java/com/openshift/internal/client/GearGroupsResourceTest.java b/src/test/java/com/openshift/internal/client/GearGroupsResourceTest.java index c8fcd577..98095be9 100644 --- a/src/test/java/com/openshift/internal/client/GearGroupsResourceTest.java +++ b/src/test/java/com/openshift/internal/client/GearGroupsResourceTest.java @@ -14,10 +14,7 @@ import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6; import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_GEARGROUPS; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.util.Collection; @@ -29,11 +26,9 @@ import com.openshift.client.IDomain; import com.openshift.client.IGearGroup; import com.openshift.client.IHttpClient; -import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IUser; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.utils.GearGroupsAssert; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; /** * @author Xavier Coulon @@ -42,32 +37,22 @@ public class GearGroupsResourceTest { private IDomain domain; - private IHttpClient mockClient; @Before public void setup() throws Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))).thenReturn( - Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))).thenReturn(GET_DOMAINS.getContentAsString()); - final IOpenShiftConnection connection = - new OpenShiftConnectionFactory().getConnection( - new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); - IUser user = connection.getUser(); + IHttpClient client = new HttpClientMockDirector() + .mockGetDomains(GET_DOMAINS) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS) + .mockGetApplication("foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6) + .mockGetGearGroups("foobarz", "springeap6", GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_GEARGROUPS) + .client(); + IUser user = new TestConnectionFactory().getConnection(client).getUser(); this.domain = user.getDomain("foobarz"); } @Test public void shouldGetGearGroups() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains/foobarz/applications"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobarz/applications/springeap6/gear_groups"))) - .thenReturn(GET_DOMAINS_FOOBARZ_APPLICATIONS_SPRINGEAP6_GEARGROUPS.getContentAsString()); final IApplication app = domain.getApplicationByName("springeap6"); // operation final Collection gearGroups = app.getGearGroups(); diff --git a/src/test/java/com/openshift/internal/client/HttpClientMockDirector.java b/src/test/java/com/openshift/internal/client/HttpClientMockDirector.java new file mode 100644 index 00000000..0e71a61e --- /dev/null +++ b/src/test/java/com/openshift/internal/client/HttpClientMockDirector.java @@ -0,0 +1,490 @@ +/******************************************************************************* + * Copyright (c) 2013 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ +package com.openshift.internal.client; + +import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; +import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyMapOf; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.util.Map; + +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import com.openshift.client.IHttpClient; +import com.openshift.client.utils.Samples; +import com.openshift.internal.client.httpclient.HttpClientException; + +/** + * @author Andre Dietisheim + */ +public class HttpClientMockDirector { + + private IHttpClient client; + + public HttpClientMockDirector() throws SocketTimeoutException, HttpClientException { + this.client = Mockito.mock(IHttpClient.class); + mockGetAPI(Samples.GET_API) + .mockGetCartridges(Samples.GET_CARTRIDGES) + .mockGetUser(Samples.GET_USER); + } + + public HttpClientMockDirector mockUserAgent(String userAgent) throws SocketTimeoutException, HttpClientException { + when(client.getUserAgent()).thenReturn(userAgent); + return this; + } + + public HttpClientMockDirector mockGetAny(String response) throws SocketTimeoutException, HttpClientException { + when(client.get(any(URL.class), anyInt())).thenReturn(response); + return this; + } + + public HttpClientMockDirector mockGetAny(Exception exception) throws SocketTimeoutException, HttpClientException { + when(client.get(any(URL.class), anyInt())).thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockPostAny(Samples postRequestResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + return mockPostAny(postRequestResponse.getContentAsString()); + } + + public HttpClientMockDirector mockPostAny(String jsonResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post(anyMapOf(String.class, Object.class), any(URL.class), anyInt())) + .thenReturn(jsonResponse); + return this; + } + + public HttpClientMockDirector mockPostAny(Exception exception) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post(anyMapOf(String.class, Object.class), any(URL.class), anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockPutAny(String jsonResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.put(anyMapOf(String.class, Object.class), any(URL.class))) + .thenReturn(jsonResponse); + return this; + } + + public HttpClientMockDirector mockDeleteAny(String jsonResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.delete(anyMapOf(String.class, Object.class), any(URL.class), anyInt())) + .thenReturn(jsonResponse); + return this; + } + + public HttpClientMockDirector mockGetAPI(Samples getApiResourceResponse) + throws HttpClientException, SocketTimeoutException { + when(client.get(urlEndsWith("/api"), anyInt())) + .thenReturn(getApiResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetAPI(Exception exception) throws SocketTimeoutException { + when(client.get(urlEndsWith("/api"), anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockGetCartridges(Samples cartridgesResourceResponse) throws HttpClientException, + SocketTimeoutException { + when(client.get(urlEndsWith("/cartridges"), anyInt())) + .thenReturn(cartridgesResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetUser(Samples userResourceResponse) throws HttpClientException, + SocketTimeoutException { + when(client.get(urlEndsWith("/user"), anyInt())) + .thenReturn(userResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetKeys(Samples keysRequestResponse) throws SocketTimeoutException, HttpClientException { + when(client.get(urlEndsWith("/user/keys"), anyInt())) + .thenReturn(keysRequestResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockCreateKey(Samples createKeyRequestResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post( + anyMapOf(String.class, Object.class), + urlEndsWith("/user/keys"), + anyInt())) + .thenReturn(createKeyRequestResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockUpdateKey(String keyName, Samples updateKeyRequestResponse, Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.put( + anyMapOf(String.class, Object.class), + urlEndsWith("/user/keys/" + keyName), + anyInt())) + .thenReturn(updateKeyRequestResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetDomains(Samples domainsResourceResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get(urlEndsWith("/domains"), anyInt())) + .thenReturn(domainsResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockCreateDomain(Samples domainResourceResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post(anyMapOf(String.class, Object.class), urlEndsWith("/domains"), anyInt())) + .thenReturn(domainResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockDeleteDomain(String domainId, Samples deleteDomainResourceResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/" + domainId), anyInt())) + .thenReturn(deleteDomainResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockDeleteDomain(String domainId, Exception exception) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/" + domainId), anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockRenameDomain(String domainId, Samples getDomainsResourceResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.put(anyMapOf(String.class, Object.class), urlEndsWith("/domains/" + domainId), anyInt())) + .thenReturn(getDomainsResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetDomain(String domainId, Samples domainResourceResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get(urlEndsWith("/domains/" + domainId), anyInt())) + .thenReturn(domainResourceResponse.getContentAsString()); + return this; + + } + + public HttpClientMockDirector mockGetApplications(String domainId, Samples applicationsResourceResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get(urlEndsWith("/domains/" + domainId + "/applications"), anyInt())) + .thenReturn(applicationsResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockCreateApplication(String domainId, Samples postDomainsResourceResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post(anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications"), anyInt())) + .thenReturn(postDomainsResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockPostApplicationEvent(String domainId, String applicationName, + Samples postApplicationEvent) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/events"), + anyInt())) + .thenReturn(postApplicationEvent.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetApplication(String domainId, String applicationName, + Samples applicationResourceResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get(urlEndsWith("/domains/" + domainId + "/applications/" + applicationName))) + .thenReturn(applicationResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockGetGearGroups(String domainId, String applicationName, + Samples gearGroupsResourceResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get( + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/gear_groups"), + anyInt())) + .thenReturn(gearGroupsResourceResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockPostApplicationEvent(String domainId, String applicationName, Exception exception) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/events"), + anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockGetEmbeddableCartridges(String domainId, String applicationName, + Samples cartridgesResourcesResponse) + throws SocketTimeoutException, HttpClientException { + when(client.get( + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt())) + .thenReturn(cartridgesResourcesResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockAddEmbeddableCartridge(String domainId, String applicationName, + Samples addEmbeddedCartridgeResponse) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt())) + .thenReturn(addEmbeddedCartridgeResponse.getContentAsString()); + return this; + } + + public HttpClientMockDirector mockAddEmbeddableCartridge(String domainId, String applicationName, + Exception exception) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector mockRemoveEmbeddableCartridge(String domainId, String applicationName, + String cartridgeName, + Exception exception) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + when(client.delete( + anyMapOf(String.class, Object.class), + urlEndsWith( + "/domains/" + domainId + "/applications/" + applicationName + "/cartridges/" + cartridgeName), + anyInt())) + .thenThrow(exception); + return this; + } + + public HttpClientMockDirector verifyPostApplicationEvent(String domainId, String applicationName) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(1)).post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/events"), + anyInt()); + return this; + } + + public HttpClientMockDirector verifyReloadEmbeddableCartridges(String domainId, String applicationName) + throws SocketTimeoutException, HttpClientException { + verify(client, times(2)).get( + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt()); + return this; + + } + + public HttpClientMockDirector verifyGetEmbeddableCartridges(String domainId, String applicationName) + throws SocketTimeoutException, HttpClientException { + verify(client, times(1)).get( + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt()); + return this; + } + + public HttpClientMockDirector verifyAddEmbeddableCartridge(String domainId, String applicationName) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(1)).post( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges"), + anyInt()); + return this; + } + + public HttpClientMockDirector verifyDeleteEmbeddableCartridge(String domainId, String applicationName, + String cartridgeName) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(1)).delete( + anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications/" + applicationName + "/cartridges/" + + cartridgeName), + anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetAny(int times) throws SocketTimeoutException, HttpClientException { + verify(client, times(times)).get(any(URL.class), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGet(String url, int times) + throws SocketTimeoutException, HttpClientException, MalformedURLException { + verify(client, times(times)).get(eq(new URL(url)), anyInt()); + return this; + } + + public HttpClientMockDirector verifyPostAny(int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(times)).post(anyMapOf(String.class, Object.class), any(URL.class), anyInt()); + return this; + } + + public HttpClientMockDirector verifyPost(String url, int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException, MalformedURLException { + verify(client, times(times)).post(anyMapOf(String.class, Object.class), new URL(url), anyInt()); + return this; + } + + public HttpClientMockDirector verifyPutAny(int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(times)).put(anyMapOf(String.class, Object.class), any(URL.class), anyInt()); + return this; + } + + public HttpClientMockDirector verifyPut(String url, int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException, MalformedURLException { + verify(client, times(times)).put(anyMapOf(String.class, Object.class), new URL(url), anyInt()); + return this; + } + + public HttpClientMockDirector verifyDeleteAny(int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(times)).delete(anyMapOf(String.class, Object.class), any(URL.class), anyInt()); + return this; + } + + public HttpClientMockDirector verifyDelete(String url, int times) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException, MalformedURLException { + verify(client, times(times)).delete(anyMapOf(String.class, Object.class), new URL(url), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetDomains() throws SocketTimeoutException, HttpClientException { + verify(client, times(1)).get(urlEndsWith("/domains"), anyInt()); + return this; + } + + public HttpClientMockDirector verifyRenameDomain(String domainId) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client, times(1)).put(anyMapOf(String.class, Object.class), urlEndsWith(domainId), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetDomain(String domainId) throws SocketTimeoutException, HttpClientException { + verify(client, times(1)).get(urlEndsWith("/domains/" + domainId), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetApplications(String domainId, int times) + throws SocketTimeoutException, HttpClientException { + verify(client, times(times)).get(urlEndsWith("/domains/" + domainId + "/applications"), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetAPI() throws SocketTimeoutException, HttpClientException { + verify(client, times(1)).get(urlEndsWith("/broker/rest/api"), anyInt()); + return this; + } + + public HttpClientMockDirector verifyGetUser() throws SocketTimeoutException, HttpClientException { + verify(client, times(1)).get(urlEndsWith("/broker/rest/user"), anyInt()); + return this; + } + + public HttpClientMockDirector verifyCreateKey(Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client).post(anyMapOf(String.class, Object.class), + urlEndsWith("/user/keys"), eq(IHttpClient.NO_TIMEOUT)); + assertPostParameters(pairs); + return this; + } + + public HttpClientMockDirector verifyUpdateKey(String keyName, Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client).put(anyMapOf(String.class, Object.class), + urlEndsWith("/user/keys/" + keyName), eq(IHttpClient.NO_TIMEOUT)); + assertPutParameters(pairs); + return this; + } + + public HttpClientMockDirector verifyCreateApplication(String domainId, int timeout, Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + verify(client).post(anyMapOf(String.class, Object.class), + urlEndsWith("/domains/" + domainId + "/applications"), eq(timeout)); + assertPostParameters(pairs); + return this; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public HttpClientMockDirector assertPostParameters(Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + verify(client).post(captor.capture(), any(URL.class), anyInt()); + assertParameters(captor.getValue(), pairs); + return this; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public HttpClientMockDirector assertPutParameters(Pair... pairs) + throws SocketTimeoutException, HttpClientException, UnsupportedEncodingException { + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + verify(client).put(captor.capture(), any(URL.class), anyInt()); + assertParameters(captor.getValue(), pairs); + return this; + } + + private void assertParameters(@SuppressWarnings("rawtypes") Map postedParameters, Pair... pairs) { + assertThat(postedParameters).hasSize(pairs.length); + for (Pair pair : pairs) { + String value = (String) postedParameters.get(pair.getKey()); + assertThat(value).isNotNull().isEqualTo(pair.getValue()); + } + } + + public IHttpClient client() { + return client; + } + + public static class Pair { + + private String key; + private String value; + + public Pair(String key, String value) { + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + } +} diff --git a/src/test/java/com/openshift/internal/client/HttpClientTest.java b/src/test/java/com/openshift/internal/client/HttpClientTest.java index 9ddef055..e488e788 100755 --- a/src/test/java/com/openshift/internal/client/HttpClientTest.java +++ b/src/test/java/com/openshift/internal/client/HttpClientTest.java @@ -23,6 +23,7 @@ import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; +import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; @@ -37,6 +38,7 @@ import com.openshift.client.OpenShiftException; import com.openshift.client.fakes.HttpClientFake; import com.openshift.client.fakes.HttpServerFake; +import com.openshift.client.fakes.WaitingHttpServerFake; import com.openshift.client.utils.Base64Coder; import com.openshift.internal.client.httpclient.HttpClientException; import com.openshift.internal.client.httpclient.NotFoundException; @@ -44,6 +46,7 @@ /** * @author Andre Dietisheim + * @author Nicolas Spano */ public class HttpClientTest { @@ -114,7 +117,8 @@ public void canAddAuthorization() throws SocketTimeoutException, HttpClientExcep assertEquals(1, matcher.groupCount()); String credentials = matcher.group(1); String cleartextCredentials = Base64Coder.decode(credentials); - assertThat(credentials).describedAs("credentials were not encoded in httpClient").isNotEqualTo(cleartextCredentials); + assertThat(credentials).describedAs("credentials were not encoded in httpClient").isNotEqualTo( + cleartextCredentials); assertEquals(username + ":" + password, cleartextCredentials); } @@ -182,7 +186,7 @@ public void shouldAddServiceVersionToAcceptHeader() throws FileNotFoundException IHttpClient httpClient = new HttpClientFake(IHttpClient.MEDIATYPE_APPLICATION_JSON, version) { @Override - protected String write(String data, String requestMethod, URL url) + protected String write(String data, String requestMethod, URL url, int timeout) throws SocketTimeoutException, HttpClientException { try { HttpURLConnection connection = createConnection("dummyUser", "dummyPassword", "dummyUserAgent", url); @@ -200,7 +204,7 @@ protected String write(String data, String requestMethod, URL url) // operation httpClient.get(serverFake.getUrl()); - + // verification assertThat(verified.get()).as("The protocol version sent by the client was not verified").isTrue(); } @@ -257,13 +261,102 @@ public void shouldHaveURLInExceptionMessage() throws IOException { // operation httpClient.get(server.getUrl()); fail("Expected NotFoundException not thrown"); - } catch(NotFoundException e) { + } catch (NotFoundException e) { assertTrue(e.getMessage().contains(server.getUrl().toString())); } finally { server.stop(); } } + @Test + public void shouldRespectGivenTimeoutPOST() throws Throwable { + // pre-conditions + final int timeout = 1000; + final int serverDelay = timeout * 4; + assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + WaitingHttpServerFake serverFake = this.startWaitingHttpServerFake(serverDelay); + long startTime = System.currentTimeMillis(); + // operations + try { + httpClient.post(Collections.emptyMap(), serverFake.getUrl(), timeout); + fail("Timeout expected."); + } catch (SocketTimeoutException e) { + // assert + assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) + .isLessThan(serverDelay) + .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + } finally { + serverFake.stop(); + } + } + + @Test + public void shouldRespectGivenTimeoutDELETE() throws Throwable { + // pre-conditions + final int timeout = 1000; + final int serverDelay = timeout * 4; + assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + WaitingHttpServerFake serverFake = this.startWaitingHttpServerFake(serverDelay); + long startTime = System.currentTimeMillis(); + // operations + try { + httpClient.delete(Collections.emptyMap(), serverFake.getUrl(), timeout); + fail("Timeout expected."); + } catch (SocketTimeoutException e) { + // assert + assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) + .isLessThan(serverDelay) + .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + } finally { + serverFake.stop(); + } + } + + @Test + public void shouldRespectGivenTimeoutPUT() throws Throwable { + // pre-conditions + final int timeout = 1000; + final int serverDelay = timeout * 4; + assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + WaitingHttpServerFake serverFake = this.startWaitingHttpServerFake(serverDelay); + long startTime = System.currentTimeMillis(); + // operations + try { + httpClient.put(Collections.emptyMap(), serverFake.getUrl(), timeout); + fail("Timeout expected."); + } catch (SocketTimeoutException e) { + // assert + assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) + .isLessThan(serverDelay) + .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + } finally { + serverFake.stop(); + } + } + + @Test + public void shouldRespectGivenTimeoutGET() throws Throwable { + // pre-conditions + final int timeout = 1000; + final int serverDelay = timeout * 4; + assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + WaitingHttpServerFake serverFake = this.startWaitingHttpServerFake(serverDelay); + + long startTime = System.currentTimeMillis(); + // operations + try { + httpClient.get(serverFake.getUrl(), timeout); + fail("Timeout expected."); + } catch (SocketTimeoutException e) { + // assert + assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) + .isLessThan(serverDelay) + .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); + } finally { + serverFake.stop(); + } + } + protected HttpServerFake startHttServerFake(String statusLine) throws IOException { int port = new Random().nextInt(9 * 1024) + 1024; HttpServerFake serverFake = null; @@ -275,4 +368,10 @@ protected HttpServerFake startHttServerFake(String statusLine) throws IOExceptio serverFake.start(); return serverFake; } + + protected WaitingHttpServerFake startWaitingHttpServerFake(int delay) throws IOException { + WaitingHttpServerFake serverFake = new WaitingHttpServerFake(delay); + serverFake.start(); + return serverFake; + } } diff --git a/src/test/java/com/openshift/internal/client/OpenShiftExceptionTest.java b/src/test/java/com/openshift/internal/client/OpenShiftExceptionTest.java index 63e1074d..9754cba2 100644 --- a/src/test/java/com/openshift/internal/client/OpenShiftExceptionTest.java +++ b/src/test/java/com/openshift/internal/client/OpenShiftExceptionTest.java @@ -12,12 +12,9 @@ import static com.openshift.client.utils.Samples.DELETE_DOMAINS_FOOBARZ_KO_EXISTINGAPPS; import static com.openshift.client.utils.Samples.GET_DOMAINS; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; +import static com.openshift.client.utils.Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.io.FileNotFoundException; import java.io.IOException; @@ -31,15 +28,13 @@ import com.openshift.client.IDomain; import com.openshift.client.IHttpClient; -import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IUser; import com.openshift.client.Message; import com.openshift.client.Messages; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.OpenShiftEndpointException; import com.openshift.client.OpenShiftException; import com.openshift.client.utils.MessageAssert; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; import com.openshift.internal.client.httpclient.BadRequestException; import com.openshift.internal.client.httpclient.HttpClientException; @@ -49,47 +44,39 @@ public class OpenShiftExceptionTest { private IUser user; - private IHttpClient mockClient; + private IHttpClient clientMock; @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public ErrorCollector errorCollector = new ErrorCollector(); + private HttpClientMockDirector mockDirector; @Before public void setup() throws Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))) - .thenReturn(Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))) - .thenReturn(GET_DOMAINS.getContentAsString()); - final IOpenShiftConnection connection = - new OpenShiftConnectionFactory().getConnection( - new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); - this.user = connection.getUser(); + // pre-conditions + this.mockDirector = new HttpClientMockDirector(); + this.clientMock = mockDirector + .mockGetDomains(GET_DOMAINS) + .mockGetApplications("foobarz", GET_DOMAINS_FOOBARZ_APPLICATIONS) + .client(); + this.user = new TestConnectionFactory().getConnection(clientMock).getUser(); } @Test - public void shouldReportServerInTimeoutExceptionMessage() throws HttpClientException, FileNotFoundException, - OpenShiftException, IOException { + public void shouldReportServerInTimeoutExceptionMessage() throws FileNotFoundException, OpenShiftException, IOException { try { - IHttpClient mockClient = mock(IHttpClient.class); // pre-conditions - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenThrow( - new HttpClientException(new ConnectException( - "java.net.ConnectException: Connection timed out"))); + mockDirector.mockGetAPI( + new HttpClientException(new ConnectException("java.net.ConnectException: Connection timed out"))); // operation - new OpenShiftConnectionFactory().getConnection( - new RestService("http://mock", "clientId", mockClient), "foo@redhat.com", "bar"); + new TestConnectionFactory().getConnection(clientMock); // verification fail("exception expected"); } catch (OpenShiftEndpointException e) { // verification - assertThat(e.getMessage()).contains("http://mock"); + assertThat(e.getMessage()).contains("https://"); } } @@ -97,8 +84,7 @@ public void shouldReportServerInTimeoutExceptionMessage() throws HttpClientExcep public void shouldThrowWithTextAndExistCode() throws Throwable { // pre-conditions try { - when(mockClient.delete(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz"))) - .thenThrow( + mockDirector.mockDeleteDomain("foobarz", new BadRequestException( DELETE_DOMAINS_FOOBARZ_KO_EXISTINGAPPS.getContentAsString(), new IOException( diff --git a/src/test/java/com/openshift/internal/client/RestServiceTest.java b/src/test/java/com/openshift/internal/client/RestServiceTest.java index 48808a9b..172c549a 100644 --- a/src/test/java/com/openshift/internal/client/RestServiceTest.java +++ b/src/test/java/com/openshift/internal/client/RestServiceTest.java @@ -12,8 +12,6 @@ import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMapOf; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -24,7 +22,6 @@ import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; -import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; @@ -54,18 +51,21 @@ public class RestServiceTest { protected static final String KEY_PROTOCOL_VERSION = "protocol_version"; private IRestService service; + private HttpClientMockDirector mockDirector; private IHttpClient clientMock; @Before public void setUp() throws FileNotFoundException, IOException, OpenShiftException, HttpClientException { - this.clientMock = mock(IHttpClient.class); + this.mockDirector = new HttpClientMockDirector(); String jsonResponse = "{}"; + this.clientMock = mockDirector + .mockGetAny(jsonResponse) + .mockPostAny(jsonResponse) + .mockPutAny(jsonResponse) + .mockDeleteAny(jsonResponse) + .client(); when(clientMock.getAcceptVersion()).thenReturn(IRestService.SERVICE_VERSION); - when(clientMock.get(any(URL.class))).thenReturn(jsonResponse); - when(clientMock.post(anyMapOf(String.class, Object.class), any(URL.class))).thenReturn(jsonResponse); - when(clientMock.put(anyMapOf(String.class, Object.class), any(URL.class))).thenReturn(jsonResponse); - when(clientMock.delete(anyMapOf(String.class, Object.class), any(URL.class))).thenReturn(jsonResponse); - + OpenShiftTestConfiguration configuration = new OpenShiftTestConfiguration(); this.service = new RestService(configuration.getStagingServer(), configuration.getClientId(), clientMock); } @@ -91,7 +91,7 @@ public void shouldGetIfGetHttpMethod() throws OpenShiftException, SocketTimeoutE // operation service.request(new Link("0 required parameter", "http://www.redhat.com", HttpMethod.GET, null, null)); // verifications - verify(clientMock, times(1)).get(any(URL.class)); + mockDirector.verifyGetAny(1); } @Test @@ -100,7 +100,7 @@ public void shouldPostIfPostHttpMethod() throws OpenShiftException, SocketTimeou // operation service.request(new Link("0 required parameter", "http://www.redhat.com", HttpMethod.POST, null, null)); // verifications - verify(clientMock, times(1)).post(anyMapOf(String.class, Object.class), any(URL.class)); + mockDirector.verifyPostAny(1); } @Test @@ -109,7 +109,7 @@ public void shouldPutIfPutHttpMethod() throws OpenShiftException, SocketTimeoutE // operation service.request(new Link("0 required parameter", "http://www.redhat.com", HttpMethod.PUT, null, null)); // verifications - verify(clientMock, times(1)).put(anyMapOf(String.class, Object.class), any(URL.class)); + mockDirector.verifyPutAny(1); } @Test @@ -118,7 +118,7 @@ public void shouldDeleteIfDeleteHttpMethod() throws OpenShiftException, SocketTi // operation service.request(new Link("0 required parameter", "http://www.redhat.com", HttpMethod.DELETE, null, null)); // verifications - verify(clientMock, times(1)).delete(anyMapOf(String.class, Object.class), any(URL.class)); + mockDirector.verifyDeleteAny(1); } @Test @@ -128,8 +128,7 @@ public void shouldNotAddServerToAbsUrl() throws OpenShiftException, SocketTimeou String url = "http://www.redhat.com"; service.request(new Link("0 required parameter", url, HttpMethod.GET, null, null)); // verifications - verify(clientMock, times(1)).get(new URL(url)); - + mockDirector.verifyGet(url, 1); } @Test @@ -140,7 +139,7 @@ public void shouldAddServerToPath() throws OpenShiftException, SocketTimeoutExce service.request(new Link("0 require parameter", url, HttpMethod.GET, null, null)); // verifications String targetUrl = service.getServiceUrl() + url.substring(1, url.length()); - verify(clientMock, times(1)).get(new URL(targetUrl)); + mockDirector.verifyGet(targetUrl, 1); } @Test @@ -151,15 +150,14 @@ public void shouldNotAddBrokerPathIfPresent() throws OpenShiftException, SocketT service.request(new Link("0 require parameter", url, HttpMethod.GET, null, null)); // verifications String targetUrl = service.getPlatformUrl() + url; - verify(clientMock, times(1)).get(new URL(targetUrl)); + mockDirector.verifyGet(targetUrl, 1); } @Test public void shouldThrowExceptionWithResponseOnNotFound() throws Throwable { try { // pre-conditions - NotFoundException e = new NotFoundException(Samples.GET_DOMAINS_FOOBAR_KO_NOTFOUND.getContentAsString()); - when(clientMock.get(any(URL.class))).thenThrow(e); + mockDirector.mockGetAny(new NotFoundException(Samples.GET_DOMAINS_FOOBAR_KO_NOTFOUND.getContentAsString())); // operation service.request(new Link("0 require parameter", "/broker/rest/adietisheim", HttpMethod.GET, null, null)); // verifications @@ -173,8 +171,7 @@ public void shouldThrowExceptionWithResponseOnNotFound() throws Throwable { public void shouldHaveMessageIfErrors() throws Throwable { try { // pre-conditions - when(clientMock.post(anyMapOf(String.class, Object.class), any(URL.class))) - .thenThrow(new HttpClientException(Samples.POST_FOOBAR_DOMAINS_KO_INUSE.getContentAsString())); + mockDirector.mockPostAny(new HttpClientException(Samples.POST_FOOBAR_DOMAINS_KO_INUSE.getContentAsString())); // operation service.request(new Link("0 require parameter", "/broker/rest/domains", HttpMethod.POST, null, null)); // verifications @@ -196,8 +193,7 @@ public void shouldHaveMessageIfErrors() throws Throwable { public void shouldReportPlatformUrlInException() throws Throwable { try { // pre-conditions - when(clientMock.post(anyMapOf(String.class, Object.class), any(URL.class))) - .thenThrow(new HttpClientException(Samples.POST_FOOBAR_DOMAINS_KO_INUSE.getContentAsString())); + mockDirector.mockPostAny(new HttpClientException(Samples.POST_FOOBAR_DOMAINS_KO_INUSE.getContentAsString())); // operation service.request(new Link("0 require parameter", "/broker/rest/domains", HttpMethod.POST, null, null)); // verifications diff --git a/src/test/java/com/openshift/internal/client/SSHKeyTest.java b/src/test/java/com/openshift/internal/client/SSHKeyTest.java index c25ca5ff..1f02e745 100644 --- a/src/test/java/com/openshift/internal/client/SSHKeyTest.java +++ b/src/test/java/com/openshift/internal/client/SSHKeyTest.java @@ -11,32 +11,23 @@ package com.openshift.internal.client; import static com.openshift.client.utils.FileUtils.createRandomTempFile; -import static com.openshift.client.utils.Samples.GET_DOMAINS; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.io.File; import java.net.SocketTimeoutException; -import java.net.URL; import java.util.HashMap; import java.util.List; import org.junit.Before; import org.junit.Test; -import com.openshift.client.IHttpClient; import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IOpenShiftSSHKey; import com.openshift.client.ISSHPublicKey; import com.openshift.client.IUser; -import com.openshift.client.OpenShiftConnectionFactory; import com.openshift.client.OpenShiftSSHKeyException; import com.openshift.client.OpenShiftUnknonwSSHKeyTypeException; import com.openshift.client.SSHKeyPair; @@ -45,6 +36,8 @@ import com.openshift.client.utils.SSHKeyTestUtils; import com.openshift.client.utils.SSHKeyTestUtils.SSHPublicKeyAssertion; import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; +import com.openshift.internal.client.HttpClientMockDirector.Pair; import com.openshift.internal.client.httpclient.HttpClientException; /** @@ -52,22 +45,14 @@ */ public class SSHKeyTest { - private IHttpClient mockClient; private IUser user; - private RestService service; + private HttpClientMockDirector mockDirector; @Before public void setUp() throws SocketTimeoutException, HttpClientException, Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))) - .thenReturn(Samples.GET_USER_JSON.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains"))) - .thenReturn(GET_DOMAINS.getContentAsString()); - this.service = new RestService("http://mock", "clientId", mockClient); - final IOpenShiftConnection connection = - new OpenShiftConnectionFactory().getConnection(service,"foo@redhat.com", "bar"); + this.mockDirector = new HttpClientMockDirector(); + final IOpenShiftConnection connection = + new TestConnectionFactory().getConnection(mockDirector.client()); this.user = connection.getUser(); } @@ -167,11 +152,11 @@ public void shouldLoadPublicKeyDsa() throws Exception { String keyType = sshKey.getKeyType().getTypeId(); assertNotNull(publicKey); assertThat(publicKey) - // no identifier - .doesNotContain(SSHKeyTestUtils.SSH_DSA) - // no comment - .doesNotContain(" "); - + // no identifier + .doesNotContain(SSHKeyTestUtils.SSH_DSA) + // no comment + .doesNotContain(" "); + // operation SSHKeyPair keyPair = SSHKeyPair.load(privateKeyPath, publicKeyPath); assertEquals(publicKey, keyPair.getPublicKey()); @@ -192,8 +177,8 @@ public void getKeyTypeByTypeIdReturnsNullIfNoMatchingType() throws OpenShiftUnkn @Test public void shouldReturn2SSHKeys() throws HttpClientException, Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_2KEYS.getContentAsString()); + mockDirector.mockGetKeys(Samples.GET_USER_KEYS_2KEYS); + // operation List sshKeys = user.getSSHKeys(); // verifications @@ -207,18 +192,19 @@ public void shouldReturn2SSHKeys() throws HttpClientException, Throwable { @Test public void shouldAddAndUpdateKey() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions - when(mockClient.post(anyMapOf(String.class, Object.class), urlEndsWith("/user/keys"))) - .thenReturn(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY.getContentAsString()); - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_NONE.getContentAsString()); + mockDirector + .mockGetKeys(Samples.GET_USER_KEYS_NONE) + .mockCreateKey(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY); String publicKeyPath = createRandomTempFile().getAbsolutePath(); String privateKeyPath = createRandomTempFile().getAbsolutePath(); SSHKeyTestUtils.createDsaKeyPair(publicKeyPath, privateKeyPath); SSHPublicKey publicKey = new SSHPublicKey(publicKeyPath); - + assertThat(user.getSSHKeys()).isEmpty(); + String keyName = "somekey"; // operation user.putSSHKey(keyName, publicKey); + mockDirector.mockGetKeys(Samples.GET_USER_KEYS_1KEY); // verifications List keys = user.getSSHKeys(); @@ -232,68 +218,64 @@ public void shouldAddAndUpdateKey() throws SocketTimeoutException, HttpClientExc @Test public void shouldUpdateKeyTypeAndPublicKey() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions + String newPublicKeyContent = "BBCC"; String keyName = "somekey"; - String keyUrl = service.getServiceUrl() + "user/keys/" + keyName; - String newPublicKey = "BBCC"; - - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_1KEY.getContentAsString()); - when(mockClient.put(anyMapOf(String.class, Object.class), urlEndsWith(keyUrl))) - .thenReturn(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY.getContentAsString()); + mockDirector + .mockGetKeys(Samples.GET_USER_KEYS_1KEY) + .mockUpdateKey(keyName, Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY); // operation List keys = user.getSSHKeys(); assertThat(keys).hasSize(1); IOpenShiftSSHKey key = keys.get(0); - + // verification assertThat(key.getKeyType()).isEqualTo(SSHKeyType.SSH_RSA); - + // operation - key.setKeyType(SSHKeyType.SSH_DSA, newPublicKey); + key.setKeyType(SSHKeyType.SSH_DSA, newPublicKeyContent); // verification assertThat(key.getKeyType()).isEqualTo(SSHKeyType.SSH_DSA); - assertThat(key.getPublicKey()).isEqualTo(newPublicKey); - HashMap parameterMap = new HashMap(); - parameterMap.put("type", SSHKeyTestUtils.SSH_DSA); - parameterMap.put("content", key.getPublicKey()); - verify(mockClient).put(parameterMap, new URL(keyUrl)); + assertThat(key.getPublicKey()).isEqualTo(newPublicKeyContent); + mockDirector.verifyUpdateKey( + keyName, + new Pair("type", SSHKeyTestUtils.SSH_DSA), + new Pair("content", key.getPublicKey())); } @Test public void shouldUpdatePublicKey() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions + String newPublicKeyContent = "BBCC"; String keyName = "somekey"; - String keyUrl = service.getServiceUrl() + "user/keys/" + keyName; - String newPublicKey = "BBCC"; - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_1KEY.getContentAsString()); - when(mockClient.put(anyMapOf(String.class, Object.class), urlEndsWith(keyUrl))) - .thenReturn(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY.getContentAsString()); + mockDirector + .mockGetKeys(Samples.GET_USER_KEYS_1KEY) + .mockUpdateKey(keyName, Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY); // operation List keys = user.getSSHKeys(); assertThat(keys).hasSize(1); IOpenShiftSSHKey key = keys.get(0); assertThat(key.getKeyType()).isEqualTo(SSHKeyType.SSH_RSA); - assertThat(key.getPublicKey()).isNotEqualTo(newPublicKey); - key.setPublicKey(newPublicKey); + assertThat(key.getPublicKey()).isNotEqualTo(newPublicKeyContent); + key.setPublicKey(newPublicKeyContent); // verification assertThat(key.getKeyType()).isEqualTo(SSHKeyType.SSH_DSA); - assertThat(key.getPublicKey()).isEqualTo(newPublicKey); + assertThat(key.getPublicKey()).isEqualTo(newPublicKeyContent); HashMap parameterMap = new HashMap(); parameterMap.put("type", SSHKeyTestUtils.SSH_RSA); - parameterMap.put("content", newPublicKey); - verify(mockClient).put(parameterMap, new URL(keyUrl)); + mockDirector.verifyUpdateKey( + keyName, + new Pair("type", SSHKeyTestUtils.SSH_RSA), + new Pair("content", key.getPublicKey())); } @Test(expected = OpenShiftSSHKeyException.class) public void shouldNotAddKeyWithExistingName() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_1KEY.getContentAsString()); + mockDirector.mockGetKeys(Samples.GET_USER_KEYS_1KEY); String publicKeyPath = createRandomTempFile().getAbsolutePath(); String privateKeyPath = createRandomTempFile().getAbsolutePath(); SSHKeyTestUtils.createDsaKeyPair(publicKeyPath, privateKeyPath); @@ -309,11 +291,9 @@ public void shouldNotAddKeyWithExistingName() throws SocketTimeoutException, Htt public void shouldNotAddKeyTwice() throws SocketTimeoutException, HttpClientException, Throwable { // pre-conditions String keyName = "somekey"; - String keyUrl = service.getServiceUrl() + "user/keys/" + keyName; - when(mockClient.get(urlEndsWith("/user/keys"))) - .thenReturn(Samples.GET_USER_KEYS_1KEY.getContentAsString()); - when(mockClient.put(anyMapOf(String.class, Object.class), urlEndsWith(keyUrl))) - .thenReturn(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY.getContentAsString()); + mockDirector + .mockGetKeys(Samples.GET_USER_KEYS_1KEY) + .mockCreateKey(Samples.PUT_BBCC_DSA_USER_KEYS_SOMEKEY); String publicKeyPath = createRandomTempFile().getAbsolutePath(); String privateKeyPath = createRandomTempFile().getAbsolutePath(); SSHKeyTestUtils.createDsaKeyPair(publicKeyPath, privateKeyPath); diff --git a/src/test/java/com/openshift/internal/client/UserTest.java b/src/test/java/com/openshift/internal/client/UserTest.java index dc5f806e..735d08f4 100644 --- a/src/test/java/com/openshift/internal/client/UserTest.java +++ b/src/test/java/com/openshift/internal/client/UserTest.java @@ -10,29 +10,17 @@ ******************************************************************************/ package com.openshift.internal.client; -import static com.openshift.client.utils.UrlEndsWithMatcher.urlEndsWith; import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.net.URL; -import java.util.List; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -import com.openshift.client.IApplication; -import com.openshift.client.IDomain; import com.openshift.client.IHttpClient; import com.openshift.client.IOpenShiftConnection; import com.openshift.client.IUser; -import com.openshift.client.OpenShiftConnectionFactory; -import com.openshift.client.utils.Samples; +import com.openshift.client.utils.TestConnectionFactory; /** * @author Xavier Coulon @@ -40,68 +28,47 @@ */ public class UserTest { - private static final String SERVER_URL = "http://mock"; private IUser user; - private IHttpClient mockClient; + private static final String PASSWORD = "123490"; + private static final String SERVER = "openshift-origin-server.local"; + private IHttpClient clientMock; + private HttpClientMockDirector mockDirector; @Before public void setup() throws Throwable { - mockClient = mock(IHttpClient.class); - when(mockClient.get(urlEndsWith("/broker/rest/api"))) - .thenReturn(Samples.GET_API.getContentAsString()); - when(mockClient.get(urlEndsWith("/user"))).thenReturn( - Samples.GET_USER_JSON.getContentAsString()); - final IOpenShiftConnection connection = new OpenShiftConnectionFactory().getConnection(new RestService( - SERVER_URL, - "clientId", mockClient), "foo@redhat.com", "bar"); + this.mockDirector = new HttpClientMockDirector(); + this.clientMock = mockDirector.client(); + + final IOpenShiftConnection connection = + new TestConnectionFactory().getConnection(PASSWORD, SERVER, clientMock); this.user = connection.getUser(); } @Test public void shouldReturnServer() throws Throwable { + // pre-conditions // verifications - assertThat(user.getServer()).isEqualTo(SERVER_URL); + assertThat(new URL(user.getServer()).getHost()).isEqualTo(SERVER); } @Test - public void shouldLoadUser() throws Throwable { + public void shouldHaveCredentials() throws Throwable { + // pre-conditions // verifications - assertThat(user.getRhlogin()).isEqualTo("foo@redhat.com"); - assertThat(user.getPassword()).isEqualTo("bar"); + assertThat(user.getPassword()).isEqualTo(PASSWORD); } @Test - public void shouldUpdateDomainNamespace() throws Throwable { + public void shouldHaveConsumedGears() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains"))) - .thenReturn(Samples.GET_DOMAINS.getContentAsString()); - when(mockClient.put(anyMapOf(String.class, Object.class), urlEndsWith("/domains/foobarz"))) - .thenReturn(Samples.GET_DOMAINS_FOOBARS.getContentAsString()); - final IDomain domain = user.getDomain("foobarz"); - assertThat(domain).isNotNull(); - // operation - domain.rename("foobars"); // verifications - assertThat(domain.getId()).isEqualTo("foobars"); - final IDomain updatedDomain = user.getDomain("foobars"); - assertThat(updatedDomain).isNotNull(); - assertThat(updatedDomain.getId()).isEqualTo("foobars"); - assertThat(LinkRetriever.retrieveLink(updatedDomain, "UPDATE").getHref()).contains("/foobars"); - verify(mockClient, times(1)).put(anyMapOf(String.class, Object.class), any(URL.class)); + assertThat(user.getConsumedGears()).isEqualTo(3); } - @Ignore @Test - public void shouldLoadEmptyListOfApplications() throws Throwable { + public void shouldHaveMaxGears() throws Throwable { // pre-conditions - when(mockClient.get(urlEndsWith("/domains"))).thenReturn( - Samples.GET_DOMAINS.getContentAsString()); - when(mockClient.get(urlEndsWith("/domains/foobar/applications"))) - .thenReturn(Samples.GET_DOMAINS_FOOBARZ_APPLICATIONS_NOAPPS.getContentAsString()); - // operation - final List applications = user.getDomains().get(0).getApplications(); // verifications - assertThat(applications).hasSize(2); - verify(mockClient, times(2)).get(any(URL.class)); + assertThat(user.getMaxGears()).isEqualTo(10); } } diff --git a/src/test/java/com/openshift/internal/client/WaitingHttpServerFake.java b/src/test/java/com/openshift/internal/client/WaitingHttpServerFake.java new file mode 100644 index 00000000..f46b2b9e --- /dev/null +++ b/src/test/java/com/openshift/internal/client/WaitingHttpServerFake.java @@ -0,0 +1,33 @@ +package com.openshift.internal.client; + +import com.openshift.client.fakes.HttpServerFake; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Created by IntelliJ IDEA. + * User: Nicolas + * Date: 05/06/13 + * Time: 19:27 + * To change this template use File | Settings | File Templates. + */ +public class WaitingHttpServerFake extends HttpServerFake { + + private long delay; + + @Override + protected void write(byte[] text, OutputStream outputStream) throws IOException { + + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + //Intentional ignore + return ; + } + } + + public WaitingHttpServerFake(long delay){ + this.delay = delay; + } +} diff --git a/src/test/java/com/openshift/internal/client/response/ResourceDTOFactoryTest.java b/src/test/java/com/openshift/internal/client/response/ResourceDTOFactoryTest.java index 8ce3386e..d7cceb23 100755 --- a/src/test/java/com/openshift/internal/client/response/ResourceDTOFactoryTest.java +++ b/src/test/java/com/openshift/internal/client/response/ResourceDTOFactoryTest.java @@ -50,7 +50,7 @@ public boolean matches(Map links) { @Test public void shouldUnmarshallGetUserResponseBody() throws Throwable { // pre-conditions - String content = Samples.GET_USER_JSON.getContentAsString(); + String content = Samples.GET_USER.getContentAsString(); assertNotNull(content); // operation RestResponse response = ResourceDTOFactory.get(content);