001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.rest.mock;
014
015import java.util.*;
016import java.util.concurrent.*;
017
018import org.apache.juneau.rest.*;
019import org.apache.juneau.utils.*;
020
021/**
022 * Creates a mocked interface against a REST resource class.
023 *
024 * <p>
025 * Allows you to test your REST resource classes without a running servlet container.
026 *
027 * <h5 class='figure'>Example:</h5>
028 * <p class='bcode w800'>
029 *  <jk>public class</jk> MockTest {
030 *
031 *    <jc>// Our REST resource to test.</jc>
032 *    <ja>@RestResource</ja>(serializers=JsonSerializer.Simple.<jk>class</jk>, parsers=JsonParser.<jk>class</jk>)
033 *    <jk>public static class</jk> MyRest {
034 *
035 *       <ja>@RestMethod</ja>(name=<jsf>PUT</jsf>, path=<js>"/String"</js>)
036 *       <jk>public</jk> String echo(<ja>@Body</ja> String b) {
037 *          <jk>return</jk> b;
038 *       }
039 *    }
040 *
041 *  <ja>@Test</ja>
042 *  <jk>public void</jk> testEcho() <jk>throws</jk> Exception {
043 *    MockRest
044 *       .<jsf>create</jsf>(MyRest.<jk>class</jk>)
045 *       .put(<js>"/String"</js>, <js>"'foo'"</js>)
046 *       .execute()
047 *       .assertStatus(200)
048 *       .assertBody(<js>"'foo'"</js>);
049 *  }
050 * </p>
051 *
052 * <h5 class='section'>See Also:</h5>
053 * <ul>
054 *    <li class='link'>{@doc juneau-rest-server.UnitTesting}
055 *    <li class='link'>{@doc juneau-rest-client.UnitTesting}
056 * </ul>
057 */
058public class MockRest implements MockHttpConnection {
059   private static Map<Class<?>,RestContext> CONTEXTS = new ConcurrentHashMap<>();
060
061   private final RestContext rc;
062
063   private MockRest(Class<?> c, boolean debug) throws Exception {
064      if (! CONTEXTS.containsKey(c))
065         CONTEXTS.put(c, RestContext.create(c.newInstance()).logger(debug ? BasicRestLogger.class : NoOpRestLogger.class).build().postInit().postInitChildFirst());
066      rc = CONTEXTS.get(c);
067   }
068
069   /**
070    * Create a new mock REST interface
071    *
072    * @param c The REST class.
073    * @return A new mock interface.
074    * @throws RuntimeException
075    *    For testing conveniences, this method wraps all exceptions in a RuntimeException so that you can easily define mocks as reusable fields.
076    */
077   public static MockRest create(Class<?> c) throws RuntimeException {
078      return create(c, false);
079   }
080
081   /**
082    * Create a new mock REST interface
083    *
084    * @param c The REST class.
085    * @param debug
086    *    If <jk>true</jk>, the REST interface will use the {@link BasicRestLogger} for logging.
087    *    <br>Otherwise, uses {@link NoOpRestLogger}.
088    * @return A new mock interface.
089    * @throws RuntimeException
090    *    For testing conveniences, this method wraps all exceptions in a RuntimeException so that you can easily define mocks as reusable fields.
091    */
092   public static MockRest create(Class<?> c, boolean debug) throws RuntimeException {
093      try {
094         return new MockRest(c, debug);
095      } catch (Exception e) {
096         throw new RuntimeException(e);
097      }
098   }
099
100   /**
101    * Performs a REST request against the REST interface.
102    *
103    * @param method The HTTP method
104    * @param path The URI path.
105    * @param body The body of the request.
106    * @return A new servlet request.
107    * @throws Exception
108    */
109   @Override /* MockHttpConnection */
110   public MockServletRequest request(String method, String path, Object body) throws Exception {
111      return MockServletRequest.create(method, path).body(body).restContext(rc);
112   }
113
114   /**
115    * Performs a REST request against the REST interface.
116    *
117    * @param method The HTTP method
118    * @param path The URI path.
119    * @return A new servlet request.
120    * @throws Exception
121    */
122   public MockServletRequest request(String method, String path) throws Exception {
123      return request(method, path, null);
124   }
125
126   /**
127    * Perform a GET request.
128    *
129    * @param path The URI path.
130    * @return A new servlet request.
131    * @throws Exception
132    */
133   public MockServletRequest get(String path) throws Exception {
134      return request("GET", path, null);
135   }
136
137   /**
138    * Perform a PUT request.
139    *
140    * @param path The URI path.
141    * @param body The body of the request.
142    * @return A new servlet request.
143    * @throws Exception
144    */
145   public MockServletRequest put(String path, Object body) throws Exception {
146      return request("PUT", path, body);
147   }
148
149   /**
150    * Perform a POST request.
151    *
152    * @param path The URI path.
153    * @param body The body of the request.
154    * @return A new servlet request.
155    * @throws Exception
156    */
157   public MockServletRequest post(String path, Object body) throws Exception {
158      return request("POST", path, body);
159   }
160
161   /**
162    * Perform a DELETE request.
163    *
164    * @param path The URI path.
165    * @return A new servlet request.
166    * @throws Exception
167    */
168   public MockServletRequest delete(String path) throws Exception {
169      return request("DELETE", path, null);
170   }
171
172   /**
173    * Perform an OPTIONS request.
174    *
175    * @param path The URI path.
176    * @return A new servlet request.
177    * @throws Exception
178    */
179   public MockServletRequest options(String path) throws Exception {
180      return request("OPTIONS", path, null);
181   }
182}