001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.bct.assertions;
018
019import static java.util.Collections.*;
020import static org.apache.juneau.commons.utils.CollectionUtils.list;
021import static org.apache.juneau.commons.utils.Shorts.*;
022import static org.apache.juneau.commons.utils.Shorts.eq;
023import static org.apache.juneau.commons.utils.ThrowableUtils.*;
024
025import java.io.*;
026import java.util.*;
027import java.util.function.*;
028
029import org.apache.juneau.commons.function.*;
030
031
032/**
033 * Used for fluent assertion calls against throwables.
034 *
035 * <h2 class='section'>Test Methods:</h2>
036 * <ul class='javatree'>
037 *    <li class='jc'>{@link FluentObjectAssertion}
038 *    <ul class='javatreec'>
039 *       <li class='jm'>{@link FluentObjectAssertion#isExists() isExists()}
040 *       <li class='jm'>{@link FluentObjectAssertion#is(Object) is(Object)}
041 *       <li class='jm'>{@link FluentObjectAssertion#is(Predicate) is(Predicate)}
042 *       <li class='jm'>{@link FluentObjectAssertion#isNot(Object) isNot(Object)}
043 *       <li class='jm'>{@link FluentObjectAssertion#isAny(Object...) isAny(Object...)}
044 *       <li class='jm'>{@link FluentObjectAssertion#isNotAny(Object...) isNotAny(Object...)}
045 *       <li class='jm'>{@link FluentObjectAssertion#isNull() isNull()}
046 *       <li class='jm'>{@link FluentObjectAssertion#isNotNull() isNotNull()}
047 *       <li class='jm'>{@link FluentObjectAssertion#isString(String) isString(String)}
048 *       <li class='jm'>{@link FluentObjectAssertion#isSame(Object) isSame(Object)}
049 *       <li class='jm'>{@link FluentObjectAssertion#isType(Class) isType(Class)}
050 *       <li class='jm'>{@link FluentObjectAssertion#isExactType(Class) isExactType(Class)}
051 *    </ul>
052 * </ul>
053 *
054 * <h2 class='section'>Transform Methods:</h2>
055 * <ul class='javatree'>
056 *    <li class='jc'>{@link FluentThrowableAssertion}
057 *    <ul class='javatreec'>
058 *       <li class='jm'>{@link FluentThrowableAssertion#asMessage() asMessage()}
059 *       <li class='jm'>{@link FluentThrowableAssertion#asMessages() asMessages()}
060 *       <li class='jm'>{@link FluentThrowableAssertion#asLocalizedMessage() asLocalizedMessage()}
061 *       <li class='jm'>{@link FluentThrowableAssertion#asLocalizedMessages() asLocalizedMessages()}
062 *       <li class='jm'>{@link FluentThrowableAssertion#asStackTrace() asStackTrace()}
063 *       <li class='jm'>{@link FluentThrowableAssertion#asCausedBy() asCausedBy()}
064 *       <li class='jm'>{@link FluentThrowableAssertion#asCausedBy(Class) asCausedBy(Class)}
065 *       <li class='jm'>{@link FluentThrowableAssertion#asFind(Class) asFind(Class)}
066 *    </ul>
067 *    <li class='jc'>{@link FluentObjectAssertion}
068 *    <ul class='javatreec'>
069 *       <li class='jm'>{@link FluentObjectAssertion#asString() asString()}
070 *       <li class='jm'>{@link FluentObjectAssertion#asString(ThrowingFunction) asString(ThrowingFunction)}
071 *       <li class='jm'>{@link FluentObjectAssertion#asTransformed(UnaryOperator) asTransformed(UnaryOperator)}
072 *       <li class='jm'>{@link FluentObjectAssertion#asAny() asAny()}
073 * </ul>
074 * </ul>
075 *
076 * <h2 class='section'>Configuration Methods:</h2>
077 * <ul class='javatree'>
078 *    <li class='jc'>{@link Assertion}
079 *    <ul class='javatreec'>
080 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
081 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
082 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
083 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
084 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
085*  </ul>
086 * </ul>
087 *
088 * <h2 class='section'>See Also:</h2><ul>
089 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem</a>
090 * </ul>
091 *
092 * @param <T> The throwable type.
093 * @param <R> The return type.
094 */
095@SuppressWarnings({
096   "java:S115", // Constants use UPPER_snakeCase convention
097   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
098})
099public class FluentThrowableAssertion<T extends Throwable,R> extends FluentObjectAssertion<T,R> {
100
101   private static final Messages MESSAGES = Messages.of(FluentThrowableAssertion.class, "Messages");
102   private static final String MSG_exceptionWasNotExpectedType = MESSAGES.getString("exceptionWasNotExpectedType");
103   private static final String MSG_exceptionWasNotThrown = MESSAGES.getString("exceptionWasNotThrown");
104   private static final String MSG_causedByExceptionNotExpectedType = MESSAGES.getString("causedByExceptionNotExpectedType");
105
106   /**
107    * Chained constructor.
108    *
109    * <p>
110    * Used when transforming one assertion into another so that the assertion config can be used by the new assertion.
111    *
112    * @param creator
113    *    The assertion that created this assertion.
114    *    <br>Should be <jk>null</jk> if this is the top-level assertion.
115    * @param value
116    *    The object being tested.
117    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
118    * @param returns
119    *    The object to return after a test method is called.
120    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
121    * used on the same assertion.
122    */
123   public FluentThrowableAssertion(Assertion creator, T value, R returns) {
124      super(creator, value, returns);
125   }
126
127   /**
128    * Constructor.
129    *
130    * @param value
131    *    The object being tested.
132    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
133    * @param returns
134    *    The object to return after a test method is called.
135    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
136    * used on the same assertion.
137    */
138   public FluentThrowableAssertion(T value, R returns) {
139      this(null, value, returns);
140   }
141
142   /**
143    * Returns an assertion against the caused-by throwable.
144    *
145    * <h4 class='section'>Example:</h4>
146    * <p class='bjava'>
147    *    <jc>// Asserts that the specified method throws an exception whose
148    *    // caused-by message contains 'foobar'. </jc>
149    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
150    *       .asCausedBy()
151    *       .asMessage()
152    *       .isPattern(<js>"foobar"</js>);
153    * </p>
154    *
155    * @return An assertion against the caused-by.  Never <jk>null</jk>.
156    */
157   public FluentThrowableAssertion<Throwable,R> asCausedBy() {
158      return asCausedBy(Throwable.class);
159   }
160
161   /**
162    * Returns an assertion against the caused-by throwable.
163    *
164    * <h4 class='section'>Example:</h4>
165    * <p class='bjava'>
166    *    <jc>// Asserts that the specified method throws an exception whose
167    *    // caused-by message contains 'foobar'. </jc>
168    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
169    *       .asCausedBy(RuntimeException.<jk>class</jk>)
170    *       .asMessage()
171    *       .isPattern(<js>"foobar"</js>);
172    * </p>
173    *
174    * @param <X> The throwable type.
175    * @param type The expected exception type.
176    * @return An assertion against the caused-by.  Never <jk>null</jk>.
177    */
178   public <X extends Throwable> FluentThrowableAssertion<X,R> asCausedBy(Class<X> type) {
179      var t = map(Throwable::getCause).orElse(null);
180      if (t == null || type.isInstance(t))
181         return new FluentThrowableAssertion<>(this, type.cast(t), returns());
182      throw error(MSG_causedByExceptionNotExpectedType, cn(type), cn(t.getClass()));
183   }
184
185   /**
186    * Returns an assertion against the throwable localized message.
187    *
188    * <h4 class='section'>Example:</h4>
189    * <p class='bjava'>
190    *    <jc>// Asserts that the specified method throws an exception with a
191    *    // caused-by RuntimeException containing 'foobar'</jc>
192    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
193    *       .findCausedBy(RuntimeException.<jk>class</jk>)
194    *       .isExists()
195    *       .asMessage()
196    *       .isPattern(<js>"foobar"</js>);
197    * </p>
198    *
199    * @param <X> The throwable type.
200    * @param throwableClass The class type to search for in the caused-by chain.
201    * @return An assertion against the caused-by throwable.  Never <jk>null</jk>.
202    */
203   public <X extends Throwable> FluentThrowableAssertion<X,R> asFind(Class<X> throwableClass) {
204      Throwable t = orElse(null);
205      while (nn(t)) {
206         if (throwableClass.isInstance(t))
207            return new FluentThrowableAssertion<>(this, throwableClass.cast(t), returns());
208         t = t.getCause();
209      }
210      return new FluentThrowableAssertion<>(this, (X)null, returns());
211   }
212
213   /**
214    * Returns an assertion against the throwable localized message.
215    *
216    * <h4 class='section'>Example:</h4>
217    * <p class='bjava'>
218    *    <jc>// Asserts that the specified method throws an exception with
219    *    // 'foobar' somewhere in the localized messages. </jc>
220    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
221    *       .asLocalizedMessage()
222    *       .isPattern(<js>".*foobar.*"</js>);
223    * </p>
224    *
225    * @return An assertion against the throwable localized message.  Never <jk>null</jk>.
226    */
227   public FluentStringAssertion<R> asLocalizedMessage() {
228      return new FluentStringAssertion<>(this, map(Throwable::getLocalizedMessage).orElse(null), returns());
229   }
230
231   /**
232    * Returns an assertion against the throwable message and all caused-by messages.
233    *
234    * <h4 class='section'>Example:</h4>
235    * <p class='bjava'>
236    *    <jc>// Asserts that the specified method throws an exception with
237    *    // 'foobar' somewhere in the messages. </jc>
238    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
239    *       .asLocalizedMessages()
240    *       .isPattern(<js>".*foobar.*"</js>);
241    * </p>
242    *
243    * @return An assertion against the throwable message.  Never <jk>null</jk>.
244    */
245   public FluentListAssertion<String,R> asLocalizedMessages() {
246      List<String> l = null;
247      Throwable t = orElse(null);
248      if (nn(t)) {
249         if (t.getCause() == null)
250            l = singletonList(t.getMessage());
251         else {
252            l = list();
253            while (nn(t)) {
254               l.add(localizedMessage(t));
255               t = t.getCause();
256            }
257         }
258      }
259      return new FluentListAssertion<>(this, l, returns());
260   }
261
262   /**
263    * Returns an assertion against the throwable message.
264    *
265    * <h4 class='section'>Example:</h4>
266    * <p class='bjava'>
267    *    <jc>// Asserts that the specified method throws an exception
268    * // with 'foobar' somewhere in the messages. </jc>
269    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
270    *       .asMessage()
271    *       .isPattern(<js>".*foobar.*"</js>);
272    * </p>
273    *
274    * @return An assertion against the throwable message.  Never <jk>null</jk>.
275    */
276   public FluentStringAssertion<R> asMessage() {
277      return new FluentStringAssertion<>(this, map(Throwable::getMessage).orElse(null), returns());
278   }
279
280   /**
281    * Returns an assertion against the throwable message and all caused-by messages.
282    *
283    * <h4 class='section'>Example:</h4>
284    * <p class='bjava'>
285    *    <jc>// Asserts that the specified method throws an exception with
286    *    // 'foobar' somewhere in the messages. </jc>
287    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
288    *       .asMessages()
289    *       .isPattern(<js>".*foobar.*"</js>);
290    * </p>
291    *
292    * @return An assertion against the throwable message.  Never <jk>null</jk>.
293    */
294   public FluentListAssertion<String,R> asMessages() {
295      List<String> l = null;
296      Throwable t = orElse(null);
297      if (nn(t)) {
298         if (t.getCause() == null)
299            l = singletonList(t.getMessage());
300         else {
301            l = list();
302            while (nn(t)) {
303               l.add(t.getMessage());
304               t = t.getCause();
305            }
306         }
307      }
308      return new FluentListAssertion<>(this, l, returns());
309   }
310
311   /**
312    * Returns an assertion against the throwable localized message.
313    *
314    * <h4 class='section'>Example:</h4>
315    * <p class='bjava'>
316    *    <jc>// Asserts that the specified method throws an exception with
317    *    // 'foobar' somewhere in the stack trace. </jc>
318    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
319    *       .asStackTrace()
320    *       .isPattern(<js>"foobar"</js>);
321    * </p>
322    *
323    * @return An assertion against the throwable stacktrace.  Never <jk>null</jk>.
324    */
325   public FluentStringListAssertion<R> asStackTrace() {
326      return new FluentStringListAssertion<>(this, valueIsNull() ? null : l(getStackTrace(value())), returns());
327   }
328
329   @Override /* Overridden from FluentObjectAssertion */
330   public FluentThrowableAssertion<T,R> asTransformed(UnaryOperator<T> function) {
331      return new FluentThrowableAssertion<>(this, function.apply(orElse(null)), returns());
332   }
333
334   /**
335    * Asserts that this throwable is exactly the specified type.
336    *
337    * <h4 class='section'>Example:</h4>
338    * <p class='bjava'>
339    *    <jc>// Asserts that the specified method throws a RuntimeException. </jc>
340    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
341    *       .isExactType(RuntimeException.<jk>class</jk>);
342    * </p>
343    *
344    * @param type The type.
345    * @return The fluent return object.
346    */
347   @Override
348   public R isExactType(Class<?> type) {
349      reqnn("type", type);
350      if (type != value().getClass())
351         throw error(MSG_exceptionWasNotExpectedType, cn(type), cn(value()));
352      return returns();
353   }
354
355   /**
356    * Asserts that this throwable exists.
357    *
358    * <h4 class='section'>Example:</h4>
359    * <p class='bjava'>
360    *    <jc>// Asserts that the specified method throws any exception.</jc>
361    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar()).isExists();
362    * </p>
363    *
364    * @return The fluent return object.
365    */
366   @Override
367   public R isExists() {
368      if (valueIsNull())
369         throw error(MSG_exceptionWasNotThrown);
370      return returns();
371   }
372
373   /**
374    * Asserts that this throwable is of the specified type.
375    *
376    * <h4 class='section'>Example:</h4>
377    * <p class='bjava'>
378    *    <jc>// Asserts that the specified method throws a RuntimeException. </jc>
379    *    ThrowableAssertion.<jsm>assertThrown</jsm>(() -&gt; <jv>foo</jv>.getBar())
380    *       .isType(RuntimeException.<jk>class</jk>);
381    * </p>
382    *
383    * @param parent The type.
384    * @return The fluent return object.
385    */
386   @Override
387   public R isType(Class<?> parent) {
388      reqnn("parent", parent);
389      if (! parent.isInstance(value()))
390         throw error(MSG_exceptionWasNotExpectedType, cn(parent), cn(value()));
391      return returns();
392   }
393
394   @Override /* Overridden from Assertion */
395   public FluentThrowableAssertion<T,R> setMsg(String msg, Object...args) {
396      super.setMsg(msg, args);
397      return this;
398   }
399
400   @Override /* Overridden from Assertion */
401   public FluentThrowableAssertion<T,R> setOut(PrintStream value) {
402      super.setOut(value);
403      return this;
404   }
405
406   @Override /* Overridden from Assertion */
407   public FluentThrowableAssertion<T,R> setSilent() {
408      super.setSilent();
409      return this;
410   }
411
412   @Override /* Overridden from Assertion */
413   public FluentThrowableAssertion<T,R> setStdOut() {
414      super.setStdOut();
415      return this;
416   }
417
418   @Override /* Overridden from Assertion */
419   public FluentThrowableAssertion<T,R> setThrowable(Class<? extends RuntimeException> value) {
420      super.setThrowable(value);
421      return this;
422   }
423
424   @Override
425   protected boolean equals(Object o1, Object o2) {
426      if (o1 instanceof Throwable o1t && o2 instanceof Throwable o2t)
427         return eq(o1t, o2t, (x, y) -> eq(x.getClass(), y.getClass()) && eq(x.getMessage(), y.getMessage()));
428      return super.equals(o1, o2);
429   }
430}