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.assertions;
018
019import static org.apache.juneau.common.utils.Utils.*;
020
021import java.io.*;
022import java.util.*;
023import java.util.function.*;
024
025import org.apache.juneau.common.utils.*;
026import org.apache.juneau.cp.*;
027import org.apache.juneau.internal.*;
028import org.apache.juneau.serializer.*;
029
030/**
031 * Used for fluent assertion calls against collections objects.
032 *
033 * <h5 class='section'>Test Methods:</h5>
034 * <p>
035 * <ul class='javatree'>
036 *    <li class='jc'>{@link FluentCollectionAssertion}
037 *    <ul class='javatreec'>
038 *       <li class='jm'>{@link FluentCollectionAssertion#isEmpty() isEmpty()}
039 *       <li class='jm'>{@link FluentCollectionAssertion#isNotEmpty() isNotEmpty()}
040 *       <li class='jm'>{@link FluentCollectionAssertion#isContains(Object) isContains(Object)}
041 *       <li class='jm'>{@link FluentCollectionAssertion#isNotContains(Object) isNotContains(Object)}
042 *       <li class='jm'>{@link FluentCollectionAssertion#isAny(Predicate) isAny(Predicate)}
043 *       <li class='jm'>{@link FluentCollectionAssertion#isAll(Predicate) isAll(Predicate)}
044 *       <li class='jm'>{@link FluentCollectionAssertion#isSize(int size) isSize(int size)}
045 *    </ul>
046 *    <li class='jc'>{@link FluentObjectAssertion}
047 *    <ul class='javatreec'>
048 *       <li class='jm'>{@link FluentObjectAssertion#isExists() isExists()}
049 *       <li class='jm'>{@link FluentObjectAssertion#is(Object) is(Object)}
050 *       <li class='jm'>{@link FluentObjectAssertion#is(Predicate) is(Predicate)}
051 *       <li class='jm'>{@link FluentObjectAssertion#isNot(Object) isNot(Object)}
052 *       <li class='jm'>{@link FluentObjectAssertion#isAny(Object...) isAny(Object...)}
053 *       <li class='jm'>{@link FluentObjectAssertion#isNotAny(Object...) isNotAny(Object...)}
054 *       <li class='jm'>{@link FluentObjectAssertion#isNull() isNull()}
055 *       <li class='jm'>{@link FluentObjectAssertion#isNotNull() isNotNull()}
056 *       <li class='jm'>{@link FluentObjectAssertion#isString(String) isString(String)}
057 *       <li class='jm'>{@link FluentObjectAssertion#isJson(String) isJson(String)}
058 *       <li class='jm'>{@link FluentObjectAssertion#isSame(Object) isSame(Object)}
059 *       <li class='jm'>{@link FluentObjectAssertion#isSameJsonAs(Object) isSameJsonAs(Object)}
060 *       <li class='jm'>{@link FluentObjectAssertion#isSameSortedJsonAs(Object) isSameSortedJsonAs(Object)}
061 *       <li class='jm'>{@link FluentObjectAssertion#isSameSerializedAs(Object, WriterSerializer) isSameSerializedAs(Object, WriterSerializer)}
062 *       <li class='jm'>{@link FluentObjectAssertion#isType(Class) isType(Class)}
063 *       <li class='jm'>{@link FluentObjectAssertion#isExactType(Class) isExactType(Class)}
064 *    </ul>
065 * </ul>
066 *
067 * <h5 class='section'>Transform Methods:</h5>
068 * <p>
069 * <ul class='javatree'>
070 *    <li class='jc'>{@link FluentCollectionAssertion}
071 *    <ul class='javatreec'>
072 *       <li class='jm'>{@link FluentCollectionAssertion#asStrings() asStrings()}
073 *       <li class='jm'>{@link FluentCollectionAssertion#asSize() asSize()}
074 *    </ul>
075 *    <li class='jc'>{@link FluentObjectAssertion}
076 *    <ul class='javatreec'>
077 *       <li class='jm'>{@link FluentObjectAssertion#asString() asString()}
078 *       <li class='jm'>{@link FluentObjectAssertion#asString(WriterSerializer) asString(WriterSerializer)}
079 *       <li class='jm'>{@link FluentObjectAssertion#asString(Function) asString(Function)}
080 *       <li class='jm'>{@link FluentObjectAssertion#asJson() asJson()}
081 *       <li class='jm'>{@link FluentObjectAssertion#asJsonSorted() asJsonSorted()}
082 *       <li class='jm'>{@link FluentObjectAssertion#asTransformed(Function) asApplied(Function)}
083 *       <li class='jm'>{@link FluentObjectAssertion#asAny() asAny()}
084 * </ul>
085 * </ul>
086 *
087 * <h5 class='section'>Configuration Methods:</h5>
088 * <p>
089 * <ul class='javatree'>
090 *    <li class='jc'>{@link Assertion}
091 *    <ul class='javatreec'>
092 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
093 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
094 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
095 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
096 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
097 *    </ul>
098 * </ul>
099 *
100 * <h5 class='section'>See Also:</h5><ul>
101 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem Overview</a>
102 * </ul>
103 *
104 * @param <E> The element type.
105 * @param <R> The return type.
106 */
107public class FluentCollectionAssertion<E,R> extends FluentObjectAssertion<Collection<E>,R> {
108
109   //-----------------------------------------------------------------------------------------------------------------
110   // Static
111   //-----------------------------------------------------------------------------------------------------------------
112
113   private static final Messages MESSAGES = Messages.of(FluentCollectionAssertion.class, "Messages");
114   private static final String
115      MSG_collectionWasNotEmpty = MESSAGES.getString("collectionWasNotEmpty"),
116      MSG_collectionDidNotContainExpectedValue = MESSAGES.getString("collectionDidNotContainExpectedValue"),
117      MSG_collectionDidNotContainTestedValue = MESSAGES.getString("collectionDidNotContainTestedValue"),
118      MSG_collectionContainedUnexpectedValue = MESSAGES.getString("collectionContainedUnexpectedValue"),
119      MSG_collectionWasEmpty = MESSAGES.getString("collectionWasEmpty"),
120      MSG_collectionDidNotHaveExpectedSize = MESSAGES.getString("collectionDidNotHaveExpectedSize");
121
122   //-----------------------------------------------------------------------------------------------------------------
123   // Instance
124   //-----------------------------------------------------------------------------------------------------------------
125
126   /**
127    * Constructor.
128    *
129    * @param value
130    *    The object being tested.
131    *    <br>Can be <jk>null</jk>.
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 FluentCollectionAssertion(Collection<E> value, R returns) {
138      this(null, value, returns);
139   }
140
141   /**
142    * Chained constructor.
143    *
144    * <p>
145    * Used when transforming one assertion into another so that the assertion config can be used by the new assertion.
146    *
147    * @param creator
148    *    The assertion that created this assertion.
149    *    <br>Should be <jk>null</jk> if this is the top-level assertion.
150    * @param value
151    *    The object being tested.
152    *    <br>Can be <jk>null</jk>.
153    * @param returns
154    *    The object to return after a test method is called.
155    *    <br>If <jk>null</jk>, the test method returns this object allowing multiple test method calls to be
156    * used on the same assertion.
157    */
158   public FluentCollectionAssertion(Assertion creator, Collection<E> value, R returns) {
159      super(creator, value, returns);
160   }
161
162   //-----------------------------------------------------------------------------------------------------------------
163   // Transform methods
164   //-----------------------------------------------------------------------------------------------------------------
165
166   @Override /* FluentObjectAssertion */
167   public FluentCollectionAssertion<E,R> asTransformed(Function<Collection<E>,Collection<E>> function) {  // NOSONAR - Intentional.
168      return new FluentCollectionAssertion<>(this, function.apply(orElse(null)), returns());
169   }
170
171   /**
172    * Converts this assertion into a {@link FluentListAssertion} of strings.
173    *
174    * @return A new fluent string assertion.
175    */
176   public FluentStringListAssertion<R> asStrings() {
177      return new FluentStringListAssertion<>(this, valueIsNull() ? null : value().stream().map(o -> s(o)).toList(), returns());
178   }
179
180
181   /**
182    * Returns an integer assertion on the size of this collection.
183    *
184    * <p>
185    * If the collection is <jk>null</jk>, the returned assertion is a null assertion
186    * (meaning {@link FluentIntegerAssertion#isExists()} returns <jk>false</jk>).
187    *
188    * @return A new assertion.
189    */
190   public FluentIntegerAssertion<R> asSize() {
191      return new FluentIntegerAssertion<>(this, valueIsNull() ? null : value().size(), returns());
192   }
193
194   //-----------------------------------------------------------------------------------------------------------------
195   // Test methods
196   //-----------------------------------------------------------------------------------------------------------------
197
198   /**
199    * Asserts that the collection exists and is empty.
200    *
201    * @return The fluent return object.
202    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
203    */
204   public R isEmpty() throws AssertionError {
205      if (! value().isEmpty())
206         throw error(MSG_collectionWasNotEmpty);
207      return returns();
208   }
209
210   /**
211    * Asserts that the collection exists and is not empty.
212    *
213    * @return The fluent return object.
214    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
215    */
216   public R isNotEmpty() throws AssertionError {
217      if (value().isEmpty())
218         throw error(MSG_collectionWasEmpty);
219      return returns();
220   }
221
222   /**
223    * Asserts that the collection contains the expected value.
224    *
225    * @param entry The value to check for.
226    * @return The fluent return object.
227    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
228    */
229   public R isContains(E entry) throws AssertionError {
230      for (var v : value())
231         if (Utils.eq(v, entry))
232            return returns();
233      throw error(MSG_collectionDidNotContainExpectedValue, entry, value());
234   }
235
236   /**
237    * Asserts that the collection contains the expected value.
238    *
239    * @param entry The value to check for.
240    * @return The fluent return object.
241    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
242    */
243   public R isNotContains(E entry) throws AssertionError {
244      value().forEach(x -> {
245         if (Utils.eq(x, entry))
246            throw error(MSG_collectionContainedUnexpectedValue, entry, value());
247      });
248      return returns();
249   }
250
251   /**
252    * Asserts that at least one value in the collection passes the specified test.
253    *
254    * @param test The predicate test.
255    * @return The fluent return object.
256    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
257    */
258   public R isAny(Predicate<E> test) throws AssertionError {
259      if (test == null)
260         return returns();
261      for (var v : value())
262         if (test.test(v))
263            return returns();
264      throw error(MSG_collectionDidNotContainTestedValue, value());
265   }
266
267   /**
268    * Asserts that all values in the collection pass the specified test.
269    *
270    * @param test The predicate test.
271    * @return The fluent return object.
272    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
273    */
274   public R isAll(Predicate<E> test) throws AssertionError {
275      if (test == null)
276         return returns();
277      value().forEach(x -> {
278         if (! test.test(x))
279            throw error(MSG_collectionDidNotContainTestedValue, value());
280      });
281      return returns();
282   }
283
284   /**
285    * Asserts that the collection exists and is the specified size.
286    *
287    * @param size The expected size.
288    * @return The fluent return object.
289    * @throws AssertionError If assertion failed or value was <jk>null</jk>.
290    */
291   public R isSize(int size) throws AssertionError {
292      if (getSize() != size)
293         throw error(MSG_collectionDidNotHaveExpectedSize, size, getSize());
294      return returns();
295   }
296
297   //-----------------------------------------------------------------------------------------------------------------
298   // Fluent setters
299   //-----------------------------------------------------------------------------------------------------------------
300   @Override /* Overridden from Assertion */
301   public FluentCollectionAssertion<E,R> setMsg(String msg, Object...args) {
302      super.setMsg(msg, args);
303      return this;
304   }
305
306   @Override /* Overridden from Assertion */
307   public FluentCollectionAssertion<E,R> setOut(PrintStream value) {
308      super.setOut(value);
309      return this;
310   }
311
312   @Override /* Overridden from Assertion */
313   public FluentCollectionAssertion<E,R> setSilent() {
314      super.setSilent();
315      return this;
316   }
317
318   @Override /* Overridden from Assertion */
319   public FluentCollectionAssertion<E,R> setStdOut() {
320      super.setStdOut();
321      return this;
322   }
323
324   @Override /* Overridden from Assertion */
325   public FluentCollectionAssertion<E,R> setThrowable(Class<? extends java.lang.RuntimeException> value) {
326      super.setThrowable(value);
327      return this;
328   }
329   //-----------------------------------------------------------------------------------------------------------------
330   // Utility methods
331   //-----------------------------------------------------------------------------------------------------------------
332
333   /**
334    * Returns the size of this collection if it is not <jk>null</jk>.
335    *
336    * @return the size of this collection if it is not <jk>null</jk>.
337    * @throws AssertionError If value was <jk>null</jk>.
338    */
339   protected int getSize() throws AssertionError {
340      return value().size();
341   }
342}