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 org.apache.juneau.commons.reflect.ReflectionUtils.*;
020import static org.apache.juneau.commons.utils.ClassUtils.*;
021import static org.apache.juneau.commons.utils.Shorts.*;
022import static org.apache.juneau.commons.utils.StringUtils.*;
023
024import java.io.*;
025import java.util.*;
026import java.util.function.*;
027
028import org.apache.juneau.commons.function.*;
029import org.apache.juneau.commons.utils.*;
030
031/**
032 * Used for fluent assertion calls against POJOs.
033 *
034 * <h2 class='section'>Test Methods:</h2>
035 * <ul class='javatree'>
036 *    <li class='jc'>{@link FluentObjectAssertion}
037 *    <ul class='javatreec'>
038 *       <li class='jm'>{@link FluentObjectAssertion#isExists() isExists()}
039 *       <li class='jm'>{@link FluentObjectAssertion#is(Object) is(Object)}
040 *       <li class='jm'>{@link FluentObjectAssertion#is(Predicate) is(Predicate)}
041 *       <li class='jm'>{@link FluentObjectAssertion#isNot(Object) isNot(Object)}
042 *       <li class='jm'>{@link FluentObjectAssertion#isAny(Object...) isAny(Object...)}
043 *       <li class='jm'>{@link FluentObjectAssertion#isNotAny(Object...) isNotAny(Object...)}
044 *       <li class='jm'>{@link FluentObjectAssertion#isNull() isNull()}
045 *       <li class='jm'>{@link FluentObjectAssertion#isNotNull() isNotNull()}
046 *       <li class='jm'>{@link FluentObjectAssertion#isString(String) isString(String)}
047 *       <li class='jm'>{@link FluentObjectAssertion#isSame(Object) isSame(Object)}
048 *       <li class='jm'>{@link FluentObjectAssertion#isSameSerializedAs(Object, ThrowingFunction) isSameSerializedAs(Object, ThrowingFunction)}
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 FluentObjectAssertion}
057 *    <ul class='javatreec'>
058 *       <li class='jm'>{@link FluentObjectAssertion#asString() asString()}
059 *       <li class='jm'>{@link FluentObjectAssertion#asString(ThrowingFunction) asString(ThrowingFunction)}
060 *       <li class='jm'>{@link FluentObjectAssertion#asTransformed(UnaryOperator) asTransformed(UnaryOperator)}
061 *       <li class='jm'>{@link FluentObjectAssertion#asAny() asAny()}
062 * </ul>
063 * </ul>
064 *
065 * <h2 class='section'>Configuration Methods:</h2>
066 * <ul class='javatree'>
067 *    <li class='jc'>{@link Assertion}
068 *    <ul class='javatreec'>
069 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
070 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
071 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
072 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
073 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
074 *    </ul>
075 * </ul>
076 *
077 * <h2 class='section'>See Also:</h2><ul>
078 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem</a>
079 * </ul>
080 *
081 * @param <T> The object type.
082 * @param <R> The return type.
083 */
084@SuppressWarnings({
085   "java:S115", // Constants use UPPER_snakeCase convention
086   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
087})
088public class FluentObjectAssertion<T,R> extends FluentAssertion<R> {
089
090   private static final Messages MESSAGES = Messages.of(FluentObjectAssertion.class, "Messages");
091   private static final String MSG_unexpectedType = MESSAGES.getString("unexpectedType");
092   private static final String MSG_unexpectedComparison = MESSAGES.getString("unexpectedComparison");
093   private static final String MSG_unexpectedValue = MESSAGES.getString("unexpectedValue");
094   private static final String MSG_unexpectedValueDidNotExpect = MESSAGES.getString("unexpectedValueDidNotExpect");
095   private static final String MSG_notTheSameValue = MESSAGES.getString("notTheSameValue");
096   private static final String MSG_valueWasNull = MESSAGES.getString("valueWasNull");
097   private static final String MSG_valueWasNotNull = MESSAGES.getString("valueWasNotNull");
098   private static final String MSG_expectedValueNotFound = MESSAGES.getString("expectedValueNotFound");
099   private static final String MSG_unexpectedValueFound = MESSAGES.getString("unexpectedValueFound");
100   private static final String MSG_unexpectedValue2 = MESSAGES.getString("unexpectedValue2");
101
102   private final T value;
103
104   /**
105    * Chained constructor.
106    *
107    * <p>
108    * Used when transforming one assertion into another so that the assertion config can be used by the new assertion.
109    *
110    * @param creator
111    *    The assertion that created this assertion.
112    *    <br>Should be <jk>null</jk> if this is the top-level assertion.
113    * @param value
114    *    The object being tested.
115    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
116    * @param returns
117    *    The object to return after a test method is called.
118    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
119    * used on the same assertion.
120    */
121   public FluentObjectAssertion(Assertion creator, T value, R returns) {
122      super(creator, returns);
123      this.value = value;
124   }
125
126   /**
127    * Constructor.
128    *
129    * @param value
130    *    The object being tested.
131    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
132    * @param returns
133    *    The object to return after a test method is called.
134    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
135    * used on the same assertion.
136    */
137   public FluentObjectAssertion(T value, R returns) {
138      this(null, value, returns);
139   }
140
141   /**
142    * Converts this assertion into an {@link FluentAnyAssertion} so that it can be converted to other assertion types.
143    *
144    * @return This object.
145    */
146   public FluentAnyAssertion<T,R> asAny() {
147      return new FluentAnyAssertion<>(this, orElse(null), returns());
148   }
149
150   /**
151    * Converts this object to a string using {@link Object#toString} and returns it as a new assertion.
152    *
153    * <h4 class='section'>Example:</h4>
154    * <p class='bjava'>
155    *    <jc>// Validates that the specified object is "foobar" after converting to a string.</jc>
156    *    <jsm>assertObject</jsm>(<jv>myPojo</jv>)
157    *       .asString()
158    *       .is(<js>"foobar"</js>);
159    * </p>
160    *
161    * @return A new fluent string assertion.
162    */
163   public FluentStringAssertion<R> asString() {
164      return new FluentStringAssertion<>(this, valueAsString(), returns());
165   }
166
167   /**
168    * Converts this object to a string using the specified function and returns it as a new assertion.
169    *
170    * <h4 class='section'>Example:</h4>
171    * <p class='bjava'>
172    *    <jc>// Validates that the specified object is "foobar" after converting to a string.</jc>
173    *    <jsm>assertObject</jsm>(<jv>myPojo</jv>)
174    *       .asString(<jv>x</jv>-&gt;<jv>x</jv>.toString())
175    *       .is(<js>"foobar"</js>);
176    * </p>
177    *
178    * @param function The conversion function.  May throw a checked exception.
179    * @return A new fluent string assertion.
180    */
181   public FluentStringAssertion<R> asString(ThrowingFunction<? super T,String> function) {
182      return new FluentStringAssertion<>(this, function.apply(value), returns());
183   }
184
185   /**
186    * Applies a transform on the inner object and returns a new inner object.
187    *
188    * @param function The function to apply.
189    * @return This object.
190    */
191   public FluentObjectAssertion<T,R> asTransformed(UnaryOperator<T> function) {
192      return new FluentObjectAssertion<>(this, function.apply(orElse(null)), returns());
193   }
194
195   /**
196    * Applies a transform on the inner object and returns a new inner object.
197    *
198    * @param <T2> The transform-to type.
199    * @param function The function to apply.
200    * @return This object.
201    */
202   public <T2> FluentObjectAssertion<T2,R> asTransformedTo(Function<T,T2> function) {
203      return new FluentObjectAssertion<>(this, function.apply(orElse(null)), returns());
204   }
205
206   /**
207    * Asserts that the value passes the specified predicate test.
208    *
209    * @param test The predicate to use to test the value.
210    * @return The fluent return object.
211    * @throws AssertionError If assertion failed.
212    */
213   public R is(Predicate<T> test) throws AssertionError {
214      if (nn(test) && ! test.test(value))
215         throw error(getFailureMessage(test, value));
216      return returns();
217   }
218
219   /**
220    * Asserts that the value equals the specified value.
221    *
222    * @param value The value to check against.
223    * @return The fluent return object.
224    * @throws AssertionError If assertion failed.
225    */
226   public R is(T value) throws AssertionError {
227      if (this.value == value)
228         return returns();
229      if (! equals(orElse(null), value))
230         throw error(MSG_unexpectedValue, r(value), r(this.value));
231      return returns();
232   }
233
234   /**
235    * Asserts that the value is one of the specified values.
236    *
237    * @param values The values to check against.
238    * @return The fluent return object.
239    * @throws AssertionError If assertion failed.
240    */
241   @SafeVarargs
242   public final R isAny(T...values) throws AssertionError {
243      for (var v : values)
244         if (equals(orElse(null), v))
245            return returns();
246      throw error(MSG_expectedValueNotFound, r(values), r(value));
247   }
248
249   /**
250    * Asserts that the object is an instance of the specified class.
251    *
252    * <h4 class='section'>Example:</h4>
253    * <p class='bjava'>
254    *    <jc>// Validates that the specified object is an instance of MyBean.</jc>
255    *    <jsm>assertObject</jsm>(<jv>myPojo</jv>).isExactType(MyBean.<jk>class</jk>);
256    * </p>
257    *
258    * @param type The value to check against.
259    * @return The fluent return object.
260    * @throws AssertionError If assertion failed.
261    */
262   public R isExactType(Class<?> type) throws AssertionError {
263      reqnn("type", type);
264      if (value().getClass() != type)
265         throw error(MSG_unexpectedType, cn(type), cn(value));
266      return returns();
267   }
268
269   /**
270    * Asserts that the object is not null.
271    *
272    * <p>
273    * Equivalent to {@link #isNotNull()}.
274    *
275    * @return The fluent return object.
276    * @throws AssertionError If assertion failed.
277    */
278   public R isExists() throws AssertionError { return isNotNull(); }
279
280   /**
281    * Asserts that the value does not equal the specified value.
282    *
283    * @param value The value to check against.
284    * @return The fluent return object.
285    * @throws AssertionError If assertion failed.
286    */
287   public R isNot(T value) throws AssertionError {
288      if (equals(orElse(null), value))
289         throw error(MSG_unexpectedValueDidNotExpect, r(value), r(orElse(null)));
290      return returns();
291   }
292
293   /**
294    * Asserts that the value is not one of the specified values.
295    *
296    * @param values The values to check against.
297    * @return The fluent return object.
298    * @throws AssertionError If assertion failed.
299    */
300   @SafeVarargs
301   public final R isNotAny(T...values) throws AssertionError {
302      for (var v : values)
303         if (equals(orElse(null), v))
304            throw error(MSG_unexpectedValueFound, r(v), r(value));
305      return returns();
306   }
307
308   /**
309    * Asserts that the object is not null.
310    *
311    * <p>
312    * Equivalent to {@link #isNotNull()}.
313    *
314    * @return The fluent return object.
315    * @throws AssertionError If assertion failed.
316    */
317   public R isNotNull() throws AssertionError {
318      if (value == null)
319         throw error(MSG_valueWasNull);
320      return returns();
321   }
322
323   /**
324    * Asserts that the object i null.
325    *
326    * <p>
327    * Equivalent to {@link #isNotNull()}.
328    *
329    * @return The fluent return object.
330    * @throws AssertionError If assertion failed.
331    */
332   public R isNull() throws AssertionError {
333      if (nn(value))
334         throw error(MSG_valueWasNotNull);
335      return returns();
336   }
337
338   /**
339    * Asserts that the specified object is the same object as this object.
340    *
341    * @param value The value to check against.
342    * @return The fluent return object.
343    * @throws AssertionError If assertion failed.
344    */
345   public R isSame(T value) throws AssertionError {
346      if (this.value == value)
347         return returns();
348      throw error(MSG_notTheSameValue, r(value), id(value), r(this.value), id(this.value));
349   }
350
351   /**
352    * Asserts that the specified object is the same as this object after converting both to strings using the specified function.
353    *
354    * <h4 class='section'>Example:</h4>
355    * <p class='bjava'>
356    *    <jsm>assertObject</jsm>(<jv>myPojo</jv>).isSameSerializedAs(<jv>other</jv>, <jv>x</jv> -&gt; <jv>x</jv>.toString());
357    * </p>
358    *
359    * @param o The object to compare against.
360    * @param function The function to use to serialize the objects.  May throw a checked exception.
361    * @return The fluent return object.
362    * @throws AssertionError If assertion failed.
363    */
364   @SuppressWarnings({
365      "unchecked" // Comparison function is applied to both the typed value and the untyped comparison object.
366   })
367   public R isSameSerializedAs(Object o, ThrowingFunction<? super T,String> function) {
368      var s1 = function.apply(value);
369      var s2 = function.apply((T)o);
370      if (neq(s1, s2))
371         throw error(MSG_unexpectedComparison, s2, s1);
372      return returns();
373   }
374
375   /**
376    * Asserts that the value converted to a string equals the specified value.
377    *
378    * @param value The value to check against.
379    * @return The fluent return object.
380    * @throws AssertionError If assertion failed.
381    */
382   public R isString(String value) {
383      return asString().is(value);
384   }
385
386   /**
387    * Asserts that the object is an instance of the specified class.
388    *
389    * <h4 class='section'>Example:</h4>
390    * <p class='bjava'>
391    *    <jc>// Validates that the specified object is an instance of MyBean.</jc>
392    *    <jsm>assertObject</jsm>(<jv>myPojo</jv>).isType(MyBean.<jk>class</jk>);
393    * </p>
394    *
395    * @param parent The value to check against.
396    * @return The fluent return object.
397    * @throws AssertionError If assertion failed.
398    */
399   public R isType(Class<?> parent) throws AssertionError {
400      reqnn("parent", parent);
401      if (! info(value()).isAssignableTo(parent))
402         throw error(MSG_unexpectedType, cn(parent), cn(value));
403      return returns();
404   }
405
406   @Override /* Overridden from Assertion */
407   public FluentObjectAssertion<T,R> setMsg(String msg, Object...args) {
408      super.setMsg(msg, args);
409      return this;
410   }
411
412   @Override /* Overridden from Assertion */
413   public FluentObjectAssertion<T,R> setOut(PrintStream value) {
414      super.setOut(value);
415      return this;
416   }
417
418   @Override /* Overridden from Assertion */
419   public FluentObjectAssertion<T,R> setSilent() {
420      super.setSilent();
421      return this;
422   }
423
424   @Override /* Overridden from Assertion */
425   public FluentObjectAssertion<T,R> setStdOut() {
426      super.setStdOut();
427      return this;
428   }
429
430   @Override /* Overridden from Assertion */
431   public FluentObjectAssertion<T,R> setThrowable(Class<? extends RuntimeException> value) {
432      super.setThrowable(value);
433      return this;
434   }
435
436   /**
437    * Returns the string form of the inner object.
438    * Subclasses can override this method to affect the {@link #asString()} method (and related).
439    */
440   @Override /* Overridden from Object */
441   public String toString() {
442      return valueAsString();
443   }
444
445   /**
446    * Checks two objects for equality.
447    *
448    * @param o1 The first object.
449    * @param o2 The second object.
450    * @return <jk>true</jk> if the objects are equal.
451    */
452   protected boolean equals(Object o1, Object o2) {
453      if (o1 == o2)
454         return true;
455      if (o1 == null || o2 == null)
456         return false;
457      if (o1.equals(o2))
458         return true;
459      if (isArray(o1))
460         return readable(o1).equals(readable(o2));
461      return false;
462   }
463
464   /**
465    * Returns the predicate failure message.
466    *
467    * <p>
468    * If the predicate extends from {@link AssertionPredicate}, then the message comes from {@link AssertionPredicate#getFailureMessage()}.
469    * Otherwise, returns a generic <js>"Unexpected value: x"</js> message.
470    *
471    * @param p The function to run against the value.
472    * @param value The value that failed the test.
473    * @return The result, never <jk>null</jk>.
474    */
475   protected String getFailureMessage(Predicate<?> p, Object value) {
476      if (p instanceof AssertionPredicate<?> p2)
477         return p2.getFailureMessage();
478      return f(MSG_unexpectedValue2, r(value));
479   }
480
481   /**
482    * Returns the result of running the specified function against the value and returns the result.
483    *
484    * @param <T2> The mapper-to type.
485    * @param mapper The function to run against the value.
486    * @return The result, never <jk>null</jk>.
487    */
488   protected <T2> Optional<T2> map(Function<? super T,? extends T2> mapper) {
489      return opt().map(mapper);
490   }
491
492   /**
493    * Returns the value wrapped in an {@link Optional}.
494    *
495    * @return The value wrapped in an {@link Optional}.
496    */
497   protected Optional<T> opt() {
498      return Shorts.o(value);  // NOAI
499   }
500
501   /**
502    * Returns the inner value or the other value if the value is <jk>null</jk>.
503    *
504    * @param other The other value.
505    * @return The inner value.
506    */
507   protected T orElse(T other) {
508      return value == null ? other : value;
509   }
510
511   /**
512    * Returns the inner value after asserting it is not <jk>null</jk>.
513    *
514    * @return The inner value.
515    * @throws AssertionError If inner value was <jk>null</jk>.
516    */
517   protected T value() throws AssertionError {
518      isExists();
519      return value;
520   }
521
522   /**
523    * Returns the inner value as a string.
524    *
525    * @return The inner value as a string, or <jk>null</jk> if the value was null.
526    */
527   protected String valueAsString() {
528      return readable(value);
529   }
530
531   /**
532    * Returns <jk>true</jk> if the inner value is not null.
533    *
534    * @return <jk>true</jk> if the inner value is not null.
535    */
536   protected boolean valueIsNotNull() {
537      return nn(value);
538   }
539
540   /**
541    * Returns <jk>true</jk> if the inner value is null.
542    *
543    * @return <jk>true</jk> if the inner value is null.
544    */
545   protected boolean valueIsNull() {
546      return value == null;
547   }
548}