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.utils.CollectionUtils.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021import static org.apache.juneau.commons.utils.StringUtils.*;
022
023import java.io.*;
024import java.util.*;
025import java.util.function.*;
026
027import org.apache.juneau.commons.function.*;
028import org.apache.juneau.commons.utils.*;
029
030/**
031 * Used for fluent assertion calls against array objects.
032 *
033 * <h2 class='section'>Test Methods:</h2>
034 * <ul class='javatree'>
035 *    <li class='jc'>{@link FluentArrayAssertion}
036 *    <ul class='javatreec'>
037 *       <li class='jm'>{@link FluentArrayAssertion#isHas(Object[]) isHas(Object[])}
038 *       <li class='jm'>{@link FluentArrayAssertion#is(Predicate) is(Predicate)}
039 *       <li class='jm'>{@link FluentArrayAssertion#isAny(Predicate) isAny(Predicate)}
040 *       <li class='jm'>{@link FluentArrayAssertion#isAll(Predicate) isAll(Predicate)}
041 *       <li class='jm'>{@link FluentArrayAssertion#isEmpty() isEmpty()}
042 *       <li class='jm'>{@link FluentArrayAssertion#isNotEmpty() isNotEmpty()}
043 *       <li class='jm'>{@link FluentArrayAssertion#isSize(int size) isSize(int size)}
044 *       <li class='jm'>{@link FluentArrayAssertion#isContains(Object) isContains(Object)}
045 *       <li class='jm'>{@link FluentArrayAssertion#isNotContains(Object) isNotContains(Object)}
046 *    </ul>
047 *    <li class='jc'>{@link FluentObjectAssertion}
048 *    <ul class='javatreec'>
049 *       <li class='jm'>{@link FluentObjectAssertion#isExists() isExists()}
050 *       <li class='jm'>{@link FluentObjectAssertion#is(Object) is(Object)}
051 *       <li class='jm'>{@link FluentObjectAssertion#is(Predicate) is(Predicate)}
052 *       <li class='jm'>{@link FluentObjectAssertion#isNot(Object) isNot(Object)}
053 *       <li class='jm'>{@link FluentObjectAssertion#isAny(Object...) isAny(Object...)}
054 *       <li class='jm'>{@link FluentObjectAssertion#isNotAny(Object...) isNotAny(Object...)}
055 *       <li class='jm'>{@link FluentObjectAssertion#isNull() isNull()}
056 *       <li class='jm'>{@link FluentObjectAssertion#isNotNull() isNotNull()}
057 *       <li class='jm'>{@link FluentObjectAssertion#isString(String) isString(String)}
058 *       <li class='jm'>{@link FluentObjectAssertion#isSame(Object) isSame(Object)}
059 *       <li class='jm'>{@link FluentObjectAssertion#isType(Class) isType(Class)}
060 *       <li class='jm'>{@link FluentObjectAssertion#isExactType(Class) isExactType(Class)}
061 *    </ul>
062 * </ul>
063 *
064 * <h2 class='section'>Transform Methods:</h2>
065 * <ul class='javatree'>
066 *    <li class='jc'>{@link FluentArrayAssertion}
067 *    <ul class='javatreec'>
068 *       <li class='jm'>{@link FluentArrayAssertion#asStrings() asStrings()}
069 *       <li class='jm'>{@link FluentArrayAssertion#asStrings(Function) asStrings(Function)}
070 *       <li class='jm'>{@link FluentArrayAssertion#asCdl() asCdl()}
071 *       <li class='jm'>{@link FluentArrayAssertion#asCdl(Function) asCdl(Function)}
072 *       <li class='jm'>{@link FluentArrayAssertion#asBeanList() asBeanList()}
073 *       <li class='jm'>{@link FluentArrayAssertion#asItem(int) asItem(int)}
074 *       <li class='jm'>{@link FluentArrayAssertion#asSorted() asSorted()}
075 *       <li class='jm'>{@link FluentArrayAssertion#asSorted(Comparator) asSorted(Comparator)}
076 *    </ul>
077 *    <li class='jc'>{@link FluentObjectAssertion}
078 *    <ul class='javatreec'>
079 *       <li class='jm'>{@link FluentObjectAssertion#asString() asString()}
080 *       <li class='jm'>{@link FluentObjectAssertion#asString(ThrowingFunction) asString(ThrowingFunction)}
081 *       <li class='jm'>{@link FluentObjectAssertion#asTransformed(UnaryOperator) asTransformed(UnaryOperator)}
082 *       <li class='jm'>{@link FluentObjectAssertion#asAny() asAny()}
083 * </ul>
084 * </ul>
085 *
086 * <h2 class='section'>Configuration Methods:</h2>
087 * <ul class='javatree'>
088 *    <li class='jc'>{@link Assertion}
089 *    <ul class='javatreec'>
090 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
091 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
092 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
093 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
094 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
095 *    </ul>
096 * </ul>
097 *
098 * <h2 class='section'>See Also:</h2><ul>
099 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem</a>
100 * </ul>
101 *
102 * @param <E> The entry type.
103 * @param <R> The return type.
104 */
105@SuppressWarnings({
106   "java:S115", // Constants use UPPER_snakeCase convention
107   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
108})
109public class FluentArrayAssertion<E,R> extends FluentObjectAssertion<E[],R> {
110
111   private static final Messages MESSAGES = Messages.of(FluentArrayAssertion.class, "Messages");
112   private static final String MSG_arrayWasEmpty = MESSAGES.getString("arrayWasEmpty");
113   private static final String MSG_arrayWasNotEmpty = MESSAGES.getString("arrayWasNotEmpty");
114   private static final String MSG_arrayUnexpectedSize = MESSAGES.getString("arrayUnexpectedSize");
115   private static final String MSG_arrayDidNotContainExpectedValue = MESSAGES.getString("arrayDidNotContainExpectedValue");
116   private static final String MSG_arrayContainedUnexpectedValue = MESSAGES.getString("arrayContainedUnexpectedValue");
117   private static final String MSG_arrayDidNotContainExpectedValueAt = MESSAGES.getString("arrayDidNotContainExpectedValueAt");
118   private static final String MSG_arrayDidntContainAnyMatchingValue = MESSAGES.getString("arrayDidntContainAnyMatchingValue");
119   private static final String MSG_arrayContainedNonMatchingValueAt = MESSAGES.getString("arrayContainedNonMatchingValueAt");
120
121   /**
122    * Chained constructor.
123    *
124    * <p>
125    * Used when transforming one assertion into another so that the assertion config can be used by the new assertion.
126    *
127    * @param creator
128    *    The assertion that created this assertion.
129    *    <br>Should be <jk>null</jk> if this is the top-level assertion.
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 FluentArrayAssertion(Assertion creator, E[] value, R returns) {
139      super(creator, value, returns);
140   }
141
142   /**
143    * Constructor.
144    *
145    * @param value
146    *    The object being tested.
147    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
148    * @param returns
149    *    The object to return after a test method is called.
150    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
151    * used on the same assertion.
152    */
153   public FluentArrayAssertion(E[] value, R returns) {
154      this(null, value, returns);
155   }
156
157   /**
158    * Converts this assertion into a {@link FluentBeanListAssertion}.
159    *
160    * <h4 class='section'>Example:</h4>
161    * <p class='bjava'>
162    *    <jc>// Extracts the 'foo' property from an array of beans and validates their values.</jc>.
163    *    <jsm>assertObject</jsm>(<jv>myArrayOfBeans</jv>)
164    *       .asBeanList()
165    *       .asProperty(<js>"foo"</js>)
166    *       .asSorted()
167    *       .equals(<js>"value1"</js>,<js>"value2"</js>,<js>"value3"</js>);
168    * </p>
169    *
170    * @return A new fluent string assertion containing a copy of the values in this assertion.
171    */
172   public FluentBeanListAssertion<E,R> asBeanList() {
173      return new FluentBeanListAssertion<>(this, toList(), returns());
174   }
175
176   /**
177    * Converts the entries in this list to a simple comma-delimited list and returns the value as a fluent string assertion.
178    *
179    * @return A fluent string assertion.  Never <jk>null</jk>.
180    */
181   public FluentStringAssertion<R> asCdl() {
182      return new FluentStringAssertion<>(this, valueIsNull() ? null : join(value(), ','), returns());
183   }
184
185   /**
186    * Converts the entries to strings using the specified stringify function, combines them into a simple comma-delimited list, and returns the value as a fluent string assertion.
187    *
188    * @param function The function to apply to all values in this list.
189    * @return A fluent string assertion.  Never <jk>null</jk>.
190    */
191   public FluentStringAssertion<R> asCdl(Function<E,String> function) {
192      List<String> l = valueIsNull() ? null : stream(value()).map(function::apply).toList();
193      return new FluentStringAssertion<>(this, join(l, ','), returns());
194   }
195
196   /**
197    * Returns an object assertion on the item specified at the specified index.
198    *
199    * <p>
200    * If the array is <jk>null</jk> or the index is out-of-bounds, the returned assertion is a null assertion
201    * (meaning {@link FluentAnyAssertion#isExists()} returns <jk>false</jk>).
202    *
203    * @param index The index of the item to retrieve from the array.
204    * @return A new assertion.
205    */
206   public FluentAnyAssertion<E,R> asItem(int index) {
207      return new FluentAnyAssertion<>(this, at(index), returns());
208   }
209
210   /**
211    * Sorts the entries in this list.
212    *
213    * @return A new list assertion.  The contents of the original list remain unchanged.
214    */
215   public FluentListAssertion<E,R> asSorted() {
216      return new FluentListAssertion<>(this, toSortedList(null), returns());
217   }
218
219   /**
220    * Sorts the entries in this list using the specified comparator.
221    *
222    * @param comparator The comparator to use to sort the list.
223    * @return A new list assertion.  The contents of the original list remain unchanged.
224    */
225   public FluentListAssertion<E,R> asSorted(Comparator<E> comparator) {
226      return new FluentListAssertion<>(this, toSortedList(comparator), returns());
227   }
228
229   @Override /* Overridden from FluentBaseAssertion */
230   public FluentStringAssertion<R> asString() {
231      return new FluentStringAssertion<>(this, valueIsNull() ? null : r(value()), returns());
232   }
233
234   /**
235    * Converts this assertion into a {@link FluentListAssertion} of strings.
236    *
237    * @return A new fluent string assertion.
238    */
239   public FluentStringListAssertion<R> asStrings() {
240      return new FluentStringListAssertion<>(this, valueIsNull() ? null : stream(value()).map(Shorts::s).toList(), returns());
241   }
242
243   /**
244    * Runs the stringify function against all values in this list and returns it as a fluent string list assertion.
245    *
246    * @param function The function to apply to all values in this list.
247    * @return A new fluent string list assertion.  Never <jk>null</jk>.
248    */
249   public FluentStringListAssertion<R> asStrings(Function<E,String> function) {
250      List<String> l = valueIsNull() ? null : stream(value()).map(function::apply).toList();
251      return new FluentStringListAssertion<>(this, l, returns());
252   }
253
254   @Override /* Overridden from FluentObjectAssertion */
255   public FluentArrayAssertion<E,R> asTransformed(UnaryOperator<E[]> function) {
256      return new FluentArrayAssertion<>(this, function.apply(orElse(null)), returns());
257   }
258
259   /**
260    * Asserts that the contents of this list pass the specified tests.
261    *
262    * @param tests The tests to run.  <jk>null</jk> entries are ignored.
263    * @return This object.
264    * @throws AssertionError If assertion failed.
265    */
266   @SafeVarargs
267   public final R is(Predicate<E>...tests) throws AssertionError {
268      isSize(tests.length);
269      for (int i = 0, j = length(); i < j; i++) {
270         var t = tests[i];
271         if (nn(t) && ! t.test(at(i)))
272            throw error(MSG_arrayDidNotContainExpectedValueAt, i, getFailureMessage(t, at(i)));
273      }
274      return returns();
275   }
276
277   /**
278    * Asserts that all values in the array passes the specified test.
279    *
280    * @param test The predicate test.
281    * @return The fluent return object.
282    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
283    */
284   public R isAll(Predicate<E> test) throws AssertionError {
285      reqnn("test", test);
286      for (int i = 0, j = length(); i < j; i++)
287         if (! test.test(at(i)))
288            throw error(MSG_arrayContainedNonMatchingValueAt, i, getFailureMessage(test, at(i)));
289      return returns();
290   }
291
292   /**
293    * Asserts that at least one value in the array passes the specified test.
294    *
295    * @param test The predicate test.
296    * @return The fluent return object.
297    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
298    */
299   public R isAny(Predicate<E> test) throws AssertionError {
300      reqnn("test", test);
301      for (var v : value())
302         if (test.test(v))
303            return returns();
304      throw error(MSG_arrayDidntContainAnyMatchingValue, r(value()));
305   }
306
307   /**
308    * Asserts that the array contains the expected value.
309    *
310    * @param entry The value to check for.
311    * @return The fluent return object.
312    * @throws AssertionError If assertion failed.
313    */
314   public R isContains(E entry) throws AssertionError {
315      for (int i = 0, j = length(); i < j; i++)
316         if (eq(at(i), entry))
317            return returns();
318      throw error(MSG_arrayDidNotContainExpectedValue, r(entry), r(value()));
319   }
320
321   /**
322    * Asserts that the collection exists and is empty.
323    *
324    * @return The fluent return object.
325    * @throws AssertionError If assertion failed.
326    */
327   public R isEmpty() throws AssertionError {
328      if (length() != 0)
329         throw error(MSG_arrayWasNotEmpty);
330      return returns();
331   }
332
333   /**
334    * Asserts that the contents of this list contain the specified values.
335    *
336    * @param entries The expected entries in this list.
337    * @return This object.
338    * @throws AssertionError If assertion failed.
339    */
340   @SuppressWarnings({
341      "unchecked" // Type erasure requires cast for array has check
342   })
343   public R isHas(E...entries) throws AssertionError {
344      reqnn("entries", entries);
345      Predicate<E>[] p = stream(entries).map(AssertionPredicates::eq).toArray(Predicate[]::new);
346      return is(p);
347   }
348
349   /**
350    * Asserts that the array does not contain the expected value.
351    *
352    * @param entry The value to check for.
353    * @return The fluent return object.
354    * @throws AssertionError If assertion failed.
355    */
356   public R isNotContains(E entry) throws AssertionError {
357      for (int i = 0, j = length(); i < j; i++)
358         if (eq(at(i), entry))
359            throw error(MSG_arrayContainedUnexpectedValue, r(entry), r(value()));
360      return returns();
361   }
362
363   /**
364    * Asserts that the collection exists and is not empty.
365    *
366    * @return The fluent return object.
367    * @throws AssertionError If assertion failed.
368    */
369   public R isNotEmpty() throws AssertionError {
370      if (length() == 0)
371         throw error(MSG_arrayWasEmpty);
372      return returns();
373   }
374
375   /**
376    * Asserts that the collection exists and is the specified size.
377    *
378    * @param size The expected size.
379    * @return The fluent return object.
380    * @throws AssertionError If assertion failed.
381    */
382   public R isSize(int size) throws AssertionError {
383      if (length() != size)
384         throw error(MSG_arrayUnexpectedSize, size, length());
385      return returns();
386   }
387
388   @Override /* Overridden from Assertion */
389   public FluentArrayAssertion<E,R> setMsg(String msg, Object...args) {
390      super.setMsg(msg, args);
391      return this;
392   }
393
394   @Override /* Overridden from Assertion */
395   public FluentArrayAssertion<E,R> setOut(PrintStream value) {
396      super.setOut(value);
397      return this;
398   }
399
400   @Override /* Overridden from Assertion */
401   public FluentArrayAssertion<E,R> setSilent() {
402      super.setSilent();
403      return this;
404   }
405
406   @Override /* Overridden from Assertion */
407   public FluentArrayAssertion<E,R> setStdOut() {
408      super.setStdOut();
409      return this;
410   }
411
412   @Override /* Overridden from Assertion */
413   public FluentArrayAssertion<E,R> setThrowable(Class<? extends RuntimeException> value) {
414      super.setThrowable(value);
415      return this;
416   }
417
418   @Override
419   public String toString() {
420      return valueIsNull() ? null : Arrays.toString(value());
421   }
422
423   private E at(int index) {
424      return valueIsNull() || index >= length() || index < 0 ? null : value()[index];
425   }
426
427   private int length() {
428      return value().length;
429   }
430
431   private List<E> toList() {
432      return valueIsNull() ? null : list(value());
433   }
434
435   private List<E> toSortedList(Comparator<E> comparator) {
436      return valueIsNull() ? null : sortedList(comparator, value());
437   }
438}