aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/com/google/common/truth/PrimitiveDoubleArraySubject.java
blob: dc26510512b1f73d962a4163e31e5641ce3ab63e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
 * Copyright (c) 2014 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.truth;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Correspondence.tolerance;

import com.google.common.primitives.Doubles;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A Subject for {@code double[]}.
 *
 * @author Christian Gruber (cgruber@israfil.net)
 */
public final class PrimitiveDoubleArraySubject extends AbstractArraySubject {
  private final double[] actual;

  PrimitiveDoubleArraySubject(
      FailureMetadata metadata, double /*@Nullable*/[] o, @Nullable String typeDescription) {
    super(metadata, o, typeDescription);
    this.actual = o;
  }

  /**
   * A check that the actual array and {@code expected} are arrays of the same length and type,
   * containing elements such that each element in {@code expected} is equal to each element in the
   * actual array, and in the same position, with element equality defined the same way that {@link
   * Arrays#equals(double[], double[])} and {@link Double#equals(Object)} define it (which is
   * different to the way that the {@code ==} operator on primitive {@code double} defines it). This
   * method is <i>not</i> recommended when the code under test is doing any kind of arithmetic: use
   * {@link #usingTolerance} with a suitable tolerance in that case, e.g. {@code
   * assertThat(actualArray).usingTolerance(1.0e-10).containsExactly(expectedArray).inOrder()}.
   * (Remember that the exact result of floating point arithmetic is sensitive to apparently trivial
   * changes such as replacing {@code (a + b) + c} with {@code a + (b + c)}, and that unless {@code
   * strictfp} is in force even the result of {@code (a + b) + c} is sensitive to the JVM's choice
   * of precision for the intermediate result.) This method is recommended when the code under test
   * is specified as either copying values without modification from its input or returning
   * well-defined literal or constant values.
   *
   * <ul>
   *   <li>It considers {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, and
   *       {@link Double#NaN} to be equal to themselves (contrast with {@code usingTolerance(0.0)}
   *       which does not).
   *   <li>It does <i>not</i> consider {@code -0.0} to be equal to {@code 0.0} (contrast with {@code
   *       usingTolerance(0.0)} which does).
   * </ul>
   */
  // TODO(cpovirk): Move some or all of this Javadoc to the supertype, maybe deleting this override?
  @Override
  public void isEqualTo(Object expected) {
    super.isEqualTo(expected);
  }

  /**
   * A check that the actual array and {@code expected} are not arrays of the same length and type,
   * containing elements such that each element in {@code expected} is equal to each element in the
   * actual array, and in the same position, with element equality defined the same way that {@link
   * Arrays#equals(double[], double[])} and {@link Double#equals(Object)} define it (which is
   * different to the way that the {@code ==} operator on primitive {@code double} defines it). See
   * {@link #isEqualTo(Object)} for advice on when exact equality is recommended.
   *
   * <ul>
   *   <li>It considers {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, and
   *       {@link Double#NaN} to be equal to themselves.
   *   <li>It does <i>not</i> consider {@code -0.0} to be equal to {@code 0.0}.
   * </ul>
   */
  @Override
  public void isNotEqualTo(Object expected) {
    super.isNotEqualTo(expected);
  }

  /**
   * Starts a method chain for a check in which the actual values (i.e. the elements of the array
   * under test) are compared to expected elements using a {@link Correspondence} which considers
   * values to correspond if they are finite values within {@code tolerance} of each other. The
   * check is actually executed by continuing the method chain. For example:
   *
   * <pre>{@code
   * assertThat(actualDoubleArray).usingTolerance(1.0e-5).contains(3.14159);
   * }</pre>
   *
   * <ul>
   *   <li>It does not consider values to correspond if either value is infinite or NaN.
   *   <li>It considers {@code -0.0} to be within any tolerance of {@code 0.0}.
   *   <li>The expected values provided later in the chain will be {@link Number} instances which
   *       will be converted to doubles, which may result in a loss of precision for some numeric
   *       types.
   *   <li>The subsequent methods in the chain may throw a {@link NullPointerException} if any
   *       expected {@link Number} instance is null.
   * </ul>
   *
   * @param tolerance an inclusive upper bound on the difference between the double values of the
   *     actual and expected numbers, which must be a non-negative finite value, i.e. not {@link
   *     Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
   */
  public DoubleArrayAsIterable usingTolerance(double tolerance) {
    return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject());
  }

  private static final Correspondence<Double, Number> EXACT_EQUALITY_CORRESPONDENCE =
      Correspondence.from(
          // If we were allowed lambdas, this would be:
          // (a, e) -> Double.doubleToLongBits(a) == Double.doubleToLongBits(checkedToDouble(e)),
          new Correspondence.BinaryPredicate<Double, Number>() {
            @Override
            public boolean apply(Double actual, Number expected) {
              return Double.doubleToLongBits(actual)
                  == Double.doubleToLongBits(checkedToDouble(expected));
            }
          },
          "is exactly equal to");

  private static double checkedToDouble(Number expected) {
    checkNotNull(expected);
    checkArgument(
        expected instanceof Double
            || expected instanceof Float
            || expected instanceof Integer
            || expected instanceof Long,
        "Expected value in assertion using exact double equality was of unsupported type %s "
            + "(it may not have an exact double representation)",
        expected.getClass());
    if (expected instanceof Long) {
      checkArgument(
          Math.abs((Long) expected) <= 1L << 53,
          "Expected value %s in assertion using exact double equality was a long with an absolute "
              + "value greater than 2^52 which has no exact double representation",
          expected);
    }
    return expected.doubleValue();
  }

  /**
   * Starts a method chain for a check in which the actual values (i.e. the elements of the array
   * under test) are compared to expected elements using a {@link Correspondence} which considers
   * values to correspond if they are exactly equal, with equality defined by {@link Double#equals}.
   * This method is <i>not</i> recommended when the code under test is doing any kind of arithmetic:
   * use {@link #usingTolerance} with a suitable tolerance in that case. (Remember that the exact
   * result of floating point arithmetic is sensitive to apparently trivial changes such as
   * replacing {@code (a + b) + c} with {@code a + (b + c)}, and that unless {@code strictfp} is in
   * force even the result of {@code (a + b) + c} is sensitive to the JVM's choice of precision for
   * the intermediate result.) This method is recommended when the code under test is specified as
   * either copying a value without modification from its input or returning a well-defined literal
   * or constant value. The check is actually executed by continuing the method chain. For example:
   *
   * <pre>{@code
   * assertThat(actualDoubleArray).usingExactEquality().contains(3.14159);
   * }</pre>
   *
   * <p>For convenience, some subsequent methods accept expected values as {@link Number} instances.
   * These numbers must be either of type {@link Double}, {@link Float}, {@link Integer}, or {@link
   * Long}, and if they are {@link Long} then their absolute values must not exceed 2^53 which is
   * just over 9e15. (This restriction ensures that the expected values have exact {@link Double}
   * representations: using exact equality makes no sense if they do not.)
   *
   * <ul>
   *   <li>It considers {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, and
   *       {@link Double#NaN} to be equal to themselves (contrast with {@code usingTolerance(0.0)}
   *       which does not).
   *   <li>It does <i>not</i> consider {@code -0.0} to be equal to {@code 0.0} (contrast with {@code
   *       usingTolerance(0.0)} which does).
   *   <li>The subsequent methods in the chain may throw a {@link NullPointerException} if any
   *       expected {@link Double} instance is null.
   * </ul>
   */
  public DoubleArrayAsIterable usingExactEquality() {
    return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
  }

  /**
   * A partially specified check for doing assertions on the array similar to the assertions
   * supported for {@link Iterable} subjects, in which the elements of the array under test are
   * compared to expected elements using either exact or tolerant double equality: see {@link
   * #usingExactEquality} and {@link #usingTolerance}. Call methods on this object to actually
   * execute the check.
   *
   * <p>In the exact equality case, the methods on this class which take {@link Number} arguments
   * only accept certain instances: again, see {@link #usingExactEquality} for details.
   */
  public static final class DoubleArrayAsIterable
      extends IterableSubject.UsingCorrespondence<Double, Number> {

    DoubleArrayAsIterable(
        Correspondence<? super Double, Number> correspondence, IterableSubject subject) {
      super(subject, correspondence);
    }

    /**
     * As {@link #containsAtLeast(Object, Object, Object...)} but taking a primitive double array.
     */
    @CanIgnoreReturnValue
    public Ordered containsAtLeast(double[] expected) {
      return containsAtLeastElementsIn(Doubles.asList(expected));
    }

    /** As {@link #containsAnyOf(Object, Object, Object...)} but taking a primitive double array. */
    public void containsAnyOf(double[] expected) {
      containsAnyIn(Doubles.asList(expected));
    }

    /** As {@link #containsExactly(Object...)} but taking a primitive double array. */
    @CanIgnoreReturnValue
    public Ordered containsExactly(double[] expected) {
      return containsExactlyElementsIn(Doubles.asList(expected));
    }

    /**
     * As {@link #containsNoneOf(Object, Object, Object...)} but taking a primitive double array.
     */
    public void containsNoneOf(double[] excluded) {
      containsNoneIn(Doubles.asList(excluded));
    }
  }

  private IterableSubject iterableSubject() {
    return checkNoNeedToDisplayBothValues("asList()")
        .about(iterablesWithCustomDoubleToString())
        .that(Doubles.asList(actual));
  }

  /*
   * TODO(cpovirk): Should we make Doubles.asList().toString() smarter rather than do all this?
   *
   * TODO(cpovirk): Or find a general solution for this and MultimapSubject.IterableEntries. But
   * note that here we don't use _exactly_ PrimitiveDoubleArraySubject.this.toString(), as that
   * contains "double[]." Or maybe we should stop including that in
   * PrimitiveDoubleArraySubject.this.toString(), too, someday?
   */
  private Factory<IterableSubject, Iterable<?>> iterablesWithCustomDoubleToString() {
    return new Factory<IterableSubject, Iterable<?>>() {
      @Override
      public IterableSubject createSubject(FailureMetadata metadata, Iterable<?> actual) {
        return new IterableSubjectWithInheritedToString(metadata, actual);
      }
    };
  }

  private final class IterableSubjectWithInheritedToString extends IterableSubject {

    IterableSubjectWithInheritedToString(FailureMetadata metadata, Iterable<?> actual) {
      super(metadata, actual);
    }

    @Override
    protected String actualCustomStringRepresentation() {
      return PrimitiveDoubleArraySubject.this
          .actualCustomStringRepresentationForPackageMembersToCall();
    }
  }
}