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.Shorts.*;
020
021import java.io.*;
022import java.lang.reflect.*;
023
024import org.apache.juneau.commons.inject.*;
025import org.apache.juneau.commons.reflect.*;
026
027/**
028 * Base class for all assertion objects.
029 *
030 * <h2 class='section'>Test Methods:</h2>
031 * <ul class='javatree'>
032 *    <li>None
033 * </ul>
034 *
035 * <h2 class='section'>Transform Methods:</h2>
036 * <ul class='javatree'>
037 *    <li>None
038 * </ul>
039 *
040 * <h2 class='section'>Configuration Methods:</h2>
041 * <ul class='javatree'>
042 *    <li class='jc'>{@link Assertion}
043 *    <ul class='javatreec'>
044 *       <li class='jm'>{@link Assertion#setMsg(String, Object...) setMsg(String, Object...)}
045 *       <li class='jm'>{@link Assertion#setOut(PrintStream) setOut(PrintStream)}
046 *       <li class='jm'>{@link Assertion#setSilent() setSilent()}
047 *       <li class='jm'>{@link Assertion#setStdOut() setStdOut()}
048 *       <li class='jm'>{@link Assertion#setThrowable(Class) setThrowable(Class)}
049 *    </ul>
050 * </ul>
051 *
052 * <ul class='seealso'>
053 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauEcosystemOverview">Juneau Ecosystem</a>
054 * </ul>
055 */
056@SuppressWarnings({
057   "java:S106", // System.out/err usage acceptable for assertion output
058   "java:S115", // Constants use UPPER_snakeCase convention (e.g., MSG_* fields); System.err/out usage is intentional for assertion error output
059   "resource" // out field assigned to System.err which is a JVM-managed singleton not owned by this class
060})
061public class Assertion {
062
063   /**
064    * Convenience method for getting the array class of the specified element type.
065    *
066    * @param <E> The element type.
067    * @param c The object to get the class name for.
068    * @return The class name for an object.
069    */
070   @SuppressWarnings({
071      "unchecked" // Type erasure requires cast to Class<E[]> for array class
072   })
073   protected static <E> Class<E[]> arrayClass(Class<E> c) {
074      return (Class<E[]>)Array.newInstance(c, 0).getClass();
075   }
076
077   private String msg;
078   private Object[] msgArgs;
079
080   private PrintStream out = System.err;
081
082   private Class<? extends RuntimeException> throwable;
083
084   /**
085    * Constructor used when this assertion is being created from within another assertion.
086    *
087    * @param creator The creator of this assertion.
088    */
089   protected Assertion(Assertion creator) {
090      if (nn(creator)) {
091         this.msg = creator.msg;
092         this.msgArgs = creator.msgArgs;
093         this.out = creator.out;
094         this.throwable = creator.throwable;
095      }
096   }
097
098   /**
099    * Allows you to override the assertion failure message.
100    *
101    * <p>
102    * String can contain <js>"{msg}"</js> to represent the original message.
103    *
104    * <h4 class='section'>Example:</h4>
105    * <p class='bjava'>
106    *    <jk>import static</jk> org.apache.juneau.bct.assertions.Assertions.*;
107    *
108    * <jc>// Throws an assertion with a custom message instead of the default "Value was null."</jc>
109    *    <jsm>assertString</jsm>(<jv>myString</jv>)
110    *       .setMsg(<js>"My string was bad:  {msg}"</js>)
111    *       .isNotNull();
112    * </p>
113    *
114    * @param msg The assertion failure message.
115    * @param args Optional message arguments.
116    * @return This object.
117    */
118   public Assertion setMsg(String msg, Object...args) {
119      this.msg = msg.replace("{msg}", "<<<MSG>>>");
120      this.msgArgs = args;
121      return this;
122   }
123
124   /**
125    * If an error occurs, send the error message to the specified stream instead of STDERR.
126    *
127    * @param value
128    *    The output stream.
129    *    Can be <jk>null</jk> to suppress output.
130    * @return This object.
131    */
132   public Assertion setOut(PrintStream value) {
133      out = value;
134      return this;
135   }
136
137   /**
138    * Suppresses output to STDERR.
139    *
140    * <p>
141    * This is the equivalent to calling <c>out(<jk>null</jk>)</c>.
142    *
143    * @return This object.
144    */
145   public Assertion setSilent() {
146      return setOut(null);
147   }
148
149   /**
150    * If an error occurs, send the error message to STDOUT instead of STDERR.
151    *
152    * @return This object.
153    */
154   public Assertion setStdOut() {
155      return setOut(System.out);
156   }
157
158   /**
159    * If an error occurs, throw this exception instead of the standard {@link AssertionError}.
160    *
161    * <p>
162    * The throwable class must have a public constructor that takes in any of the following parameters:
163    * <ul>
164    *    <li>{@link Throwable} - The caused-by exception (if there is one).
165    *    <li>{@link String} - The assertion failure message.
166    * </ul>
167    *
168    * <p>
169    * If the throwable cannot be instantiated, a {@link RuntimeException} is thrown instead.
170    *
171    * <h4 class='section'>Example:</h4>
172    * <p class='bjava'>
173    *    <jk>import static</jk> org.apache.juneau.bct.assertions.Assertions.*;
174    *
175    * <jc>// Throws a BadRequest instead of an AssertionError if the string is null.</jc>
176    *    <jsm>assertString</jsm>(<jv>myString</jv>)
177    *       .setThrowable(BadRequest.<jk>class</jk>)
178    *       .isNotNull();
179    * </p>
180    *
181    * @param value The new value for this setting.
182    * @return This object.
183    */
184   public Assertion setThrowable(Class<? extends RuntimeException> value) {
185      throwable = value;
186      return this;
187   }
188
189   /**
190    * Creates a new {@link BasicAssertionError}.
191    *
192    * @param msg The message.
193    * @param args The message arguments.
194    * @return A new {@link BasicAssertionError}.
195    */
196   protected BasicAssertionError error(String msg, Object...args) {
197      return error(null, msg, args);
198   }
199
200   /**
201    * Creates a new {@link BasicAssertionError}.
202    *
203    * @param cause Optional caused-by throwable.
204    * @param msg The message.
205    * @param args The message arguments.
206    * @return A new {@link BasicAssertionError}.
207    */
208   protected BasicAssertionError error(Throwable cause, String msg, Object...args) {
209      msg = f(msg, args);
210      if (nn(this.msg))
211         msg = f(this.msg, this.msgArgs).replace("<<<MSG>>>", msg);
212      if (nn(out))
213         out.println(msg);
214      if (nn(throwable)) {
215         try {
216            // @formatter:off
217            throw BeanInstantiator
218               .of(throwable)
219               .addBean(Throwable.class, cause)
220               .addBean(String.class, msg)
221               .addBean(Object[].class, new Object[0])
222               .run();
223         // @formatter:on
224         } catch (@SuppressWarnings("unused") ExecutableException e) {
225         // If we couldn't create requested exception, just throw a RuntimeException.
226            throw rex(cause, msg);
227         }
228      }
229      return new BasicAssertionError(cause, msg);
230   }
231}