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.Arrays.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021
022import java.io.*;
023import java.lang.reflect.*;
024import java.util.*;
025import java.util.function.*;
026
027import org.apache.juneau.commons.function.*;
028
029
030/**
031 * Used for fluent assertion calls against primitive array objects (e.g. <c><jk>int</jk>[]</c>).
032 *
033 * <h2 class='section'>Test Methods:</h2>
034 * <ul class='javatree'>
035 *    <li class='jc'>{@link FluentPrimitiveArrayAssertion}
036 *    <ul class='javatreec'>
037 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isHas(Object...) isHas(Object...)}
038 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#is(Predicate) is(Predicate)}
039 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isAny(Predicate) isAny(Predicate)}
040 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isAll(Predicate) isAll(Predicate)}
041 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isEmpty() isEmpty()}
042 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isNotEmpty() isNotEmpty()}
043 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isSize(int) isSize(int)}
044 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#isContains(Object) isContains(Object)}
045 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#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 FluentPrimitiveArrayAssertion}
067 *    <ul class='javatreec'>
068 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#asItem(int) asItem(int)}
069 *       <li class='jm'>{@link FluentPrimitiveArrayAssertion#asLength() asLength()}
070 *    </ul>
071 *    <li class='jc'>{@link FluentObjectAssertion}
072 *    <ul class='javatreec'>
073 *       <li class='jm'>{@link FluentObjectAssertion#asString() asString()}
074 *       <li class='jm'>{@link FluentObjectAssertion#asString(ThrowingFunction) asString(ThrowingFunction)}
075 *       <li class='jm'>{@link FluentObjectAssertion#asTransformed(UnaryOperator) asTransformed(UnaryOperator)}
076 *       <li class='jm'>{@link FluentObjectAssertion#asAny() asAny()}
077 * </ul>
078 * </ul>
079 *
080 * <h2 class='section'>Configuration Methods:</h2>
081 * <ul class='javatree'>
082 *    <li class='jc'>{@link Assertion}
083 *    <ul class='javatreec'>
084 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
085 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
086 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
087 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
088 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
089 *    </ul>
090 * </ul>
091 *
092 * <h2 class='section'>See Also:</h2><ul>
093 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem</a>
094 * </ul>
095 *
096 * @param <E> The array element type.
097 * @param <T> The array type.
098 * @param <R> The return type.
099 */
100@SuppressWarnings({
101   "java:S115", // Constants use UPPER_snakeCase convention
102   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
103   "unchecked" // (E) Array.get(...) in the element accessor: E is the boxed element type of the primitive array T
104})
105public class FluentPrimitiveArrayAssertion<E,T,R> extends FluentObjectAssertion<T,R> {
106
107   private static final Map<Class<?>,Function<Object,String>> STRINGIFIERS = m();
108   static {
109      STRINGIFIERS.put(boolean.class, x -> Arrays.toString((boolean[])x));
110      STRINGIFIERS.put(byte.class, x -> Arrays.toString((byte[])x));
111      STRINGIFIERS.put(char.class, x -> Arrays.toString((char[])x));
112      STRINGIFIERS.put(double.class, x -> Arrays.toString((double[])x));
113      STRINGIFIERS.put(float.class, x -> Arrays.toString((float[])x));
114      STRINGIFIERS.put(int.class, x -> Arrays.toString((int[])x));
115      STRINGIFIERS.put(long.class, x -> Arrays.toString((long[])x));
116      STRINGIFIERS.put(short.class, x -> Arrays.toString((short[])x));
117   }
118
119   private static final Messages MESSAGES = Messages.of(FluentPrimitiveArrayAssertion.class, "Messages");
120   static final String MSG_objectWasNotAnArray = MESSAGES.getString("objectWasNotAnArray");
121   static final String MSG_arrayWasNotEmpty = MESSAGES.getString("arrayWasNotEmpty");
122   static final String MSG_arrayWasEmpty = MESSAGES.getString("arrayWasEmpty");
123   static final String MSG_arrayDidNotHaveExpectedSize = MESSAGES.getString("arrayDidNotHaveExpectedSize");
124   static final String MSG_arrayDidNotContainExpectedValue = MESSAGES.getString("arrayDidNotContainExpectedValue");
125   static final String MSG_arrayDidNotContainExpectedValueAt = MESSAGES.getString("arrayDidNotContainExpectedValueAt");
126   static final String MSG_arrayContainedUnexpectedValue = MESSAGES.getString("arrayContainedUnexpectedValue");
127   static final String MSG_arrayDidntContainAnyMatchingValue = MESSAGES.getString("arrayDidntContainAnyMatchingValue");
128   static final String MSG_arrayContainedNonMatchingValueAt = MESSAGES.getString("arrayContainedNonMatchingValueAt");
129
130   /**
131    * Chained constructor.
132    *
133    * <p>
134    * Used when transforming one assertion into another so that the assertion config can be used by the new assertion.
135    *
136    * @param creator
137    *    The assertion that created this assertion.
138    *    <br>Should be <jk>null</jk> if this is the top-level assertion.
139    * @param value
140    *    The object being tested.
141    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
142    * @param returns
143    *    The object to return after a test method is called.
144    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
145    * used on the same assertion.
146    */
147   public FluentPrimitiveArrayAssertion(Assertion creator, T value, R returns) {
148      super(creator, value, returns);
149      if (nn(value)) {
150         var c = value.getClass();
151         if (! (c.isArray() && c.getComponentType().isPrimitive()))
152            throw new BasicAssertionError(MSG_objectWasNotAnArray, cn(value.getClass()));
153      }
154   }
155
156   /**
157    * Constructor.
158    *
159    * @param value
160    *    The object being tested.
161    *    <br>Can be <jk>null</jk> (assertions such as {@code isNull()} then operate on the absence of a value).
162    * @param returns
163    *    The object to return after a test method is called.
164    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
165    * used on the same assertion.
166    */
167   public FluentPrimitiveArrayAssertion(T value, R returns) {
168      this(null, value, returns);
169   }
170
171   /**
172    * Returns an object assertion on the item specified at the specified index.
173    *
174    * <p>
175    * If the array is <jk>null</jk> or the index is out-of-bounds, the returned assertion is a null assertion
176    * (meaning {@link FluentAnyAssertion#isExists()} returns <jk>false</jk>).
177    *
178    * @param index The index of the item to retrieve from the array.
179    * @return A new assertion.
180    */
181   public FluentAnyAssertion<E,R> asItem(int index) {
182      return new FluentAnyAssertion<>(this, at(index), returns());
183   }
184
185   /**
186    * Returns an integer assertion on the length of this array.
187    *
188    * <p>
189    * If the array is <jk>null</jk> or the index is out-of-bounds, the returned assertion is a null assertion
190    * (meaning {@link FluentIntegerAssertion#isExists()} returns <jk>false</jk>).
191    *
192    * @return A new assertion.
193    */
194   public FluentIntegerAssertion<R> asLength() {
195      return new FluentIntegerAssertion<>(this, valueIsNull() ? null : Array.getLength(value()), returns());
196   }
197
198   @Override /* Overridden from FluentBaseAssertion */
199   public FluentStringAssertion<R> asString() {
200      return new FluentStringAssertion<>(this, valueIsNull() ? null : r(value()), returns());
201   }
202
203   @Override /* Overridden from FluentObjectAssertion */
204   public FluentPrimitiveArrayAssertion<E,T,R> asTransformed(UnaryOperator<T> function) {
205      return new FluentPrimitiveArrayAssertion<>(this, function.apply(orElse(null)), returns());
206   }
207
208   /**
209    * Asserts that the contents of this list pass the specified tests.
210    *
211    * @param tests The tests to run.  <jk>null</jk> entries are ignored.
212    * @return This object.
213    * @throws AssertionError If assertion failed.
214    */
215   @SafeVarargs
216   public final R is(Predicate<E>...tests) throws AssertionError {
217      isSize(tests.length);
218      for (int i = 0, j = length2(); i < j; i++) {
219         var t = tests[i];
220         if (nn(t) && ! t.test(at(i)))
221            throw error(MSG_arrayDidNotContainExpectedValueAt, i, getFailureMessage(t, at(i)));
222      }
223      return returns();
224   }
225
226   /**
227    * Asserts that all values in the array pass the specified test.
228    *
229    * @param test The predicate test.
230    * @return The fluent return object.
231    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
232    */
233   public R isAll(Predicate<E> test) throws AssertionError {
234      reqnn("test", test);
235      for (int i = 0, j = length2(); i < j; i++)
236         if (! test.test(at(i)))
237            throw error(MSG_arrayContainedNonMatchingValueAt, i, getFailureMessage(test, at(i)));
238      return returns();
239   }
240
241   /**
242    * Asserts that at least one value in the array passes the specified test.
243    *
244    * @param test The predicate test.
245    * @return The fluent return object.
246    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
247    */
248   public R isAny(Predicate<E> test) throws AssertionError {
249      reqnn("test", test);
250      for (int i = 0, j = length2(); i < j; i++)
251         if (test.test(at(i)))
252            return returns();
253      throw error(MSG_arrayDidntContainAnyMatchingValue, r(value()));
254   }
255
256   /**
257    * Asserts that the array contains the expected entry.
258    *
259    * @param entry The value to check for.
260    * @return The fluent return object.
261    * @throws AssertionError If assertion failed.
262    */
263   public R isContains(E entry) throws AssertionError {
264      for (int i = 0, j = length2(); i < j; i++)
265         if (eq(at(i), entry))
266            return returns();
267      throw error(MSG_arrayDidNotContainExpectedValue, r(entry), r(value()));
268   }
269
270   /**
271    * Asserts that the collection exists and is empty.
272    *
273    * @return The fluent return object.
274    * @throws AssertionError If assertion failed.
275    */
276   public R isEmpty() throws AssertionError {
277      if (length2() != 0)
278         throw error(MSG_arrayWasNotEmpty);
279      return returns();
280   }
281
282   /**
283    * Asserts that the contents of this list contain the specified values.
284    *
285    * @param entries The expected entries in this list.
286    * @return This object.
287    * @throws AssertionError If assertion failed.
288    */
289   public R isHas(E...entries) throws AssertionError {
290      reqnn("entries", entries);
291      Predicate<E>[] p = stream(entries).map(AssertionPredicates::eq).toArray(Predicate[]::new);
292      return is(p);
293   }
294
295   /**
296    * Asserts that the array does not contain the expected value.
297    *
298    * @param entry The value to check for.
299    * @return The fluent return object.
300    * @throws AssertionError If assertion failed.
301    */
302   public R isNotContains(E entry) throws AssertionError {
303      for (var i = 0; i < length2(); i++)
304         if (eq(at(i), entry))
305            throw error(MSG_arrayContainedUnexpectedValue, r(entry), r(value()));
306      return returns();
307   }
308
309   /**
310    * Asserts that the collection exists and is not empty.
311    *
312    * @return The fluent return object.
313    * @throws AssertionError If assertion failed.
314    */
315   public R isNotEmpty() throws AssertionError {
316      if (length2() == 0)
317         throw error(MSG_arrayWasEmpty);
318      return returns();
319   }
320
321   /**
322    * Asserts that the collection exists and is the specified size.
323    *
324    * @param size The expected size.
325    * @return The fluent return object.
326    * @throws AssertionError If assertion failed.
327    */
328   public R isSize(int size) throws AssertionError {
329      if (length2() != size)
330         throw error(MSG_arrayDidNotHaveExpectedSize, size, asLength());
331      return returns();
332   }
333
334   @Override /* Overridden from Assertion */
335   public FluentPrimitiveArrayAssertion<E,T,R> setMsg(String msg, Object...args) {
336      super.setMsg(msg, args);
337      return this;
338   }
339
340   @Override /* Overridden from Assertion */
341   public FluentPrimitiveArrayAssertion<E,T,R> setOut(PrintStream value) {
342      super.setOut(value);
343      return this;
344   }
345
346   @Override /* Overridden from Assertion */
347   public FluentPrimitiveArrayAssertion<E,T,R> setSilent() {
348      super.setSilent();
349      return this;
350   }
351
352   @Override /* Overridden from Assertion */
353   public FluentPrimitiveArrayAssertion<E,T,R> setStdOut() {
354      super.setStdOut();
355      return this;
356   }
357
358   @Override /* Overridden from Assertion */
359   public FluentPrimitiveArrayAssertion<E,T,R> setThrowable(Class<? extends RuntimeException> value) {
360      super.setThrowable(value);
361      return this;
362   }
363
364   @Override
365   @SuppressWarnings({
366      "java:S2225" // Returning null from toString() is intentional; null value signals absent/unset array in assertion context
367   })
368   public String toString() {
369      if (valueIsNull())
370         return null;
371      return STRINGIFIERS.get(value().getClass().getComponentType()).apply(value());
372   }
373
374   private E at(int index) {
375      return valueIsNull() || index < 0 || index >= length2() ? null : (E)Array.get(value(), index);
376   }
377
378   private int length2() {
379      return Array.getLength(value());
380   }
381}