aboutsummaryrefslogtreecommitdiff
path: root/value/src/test/java/com/google/auto/value/extension/memoized/MemoizedTest.java
blob: 5beb686b32cd15092671c62b033b1ce109f0758f (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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
 * Copyright 2016 Google LLC
 *
 * 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.auto.value.extension.memoized;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.auto.value.AutoValue;
import com.google.auto.value.AutoValue.CopyAnnotations;
import com.google.auto.value.extension.memoized.MemoizedTest.HashCodeEqualsOptimization.EqualsCounter;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.ImmutableTypeParameter;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class MemoizedTest {

  private Value value;
  private ListValue<Integer, String> listValue;

  @AutoValue
  abstract static class ValueWithKeywordName {
    abstract boolean getNative();

    abstract boolean getNative0();

    @Memoized
    boolean getMemoizedNative() {
      return getNative();
    }

    @Memoized
    boolean getMemoizedNative0() {
      return getNative0();
    }
  }

  @AutoValue
  @CopyAnnotations
  @javax.annotation.Nullable
  abstract static class ValueWithCopyAnnotations {
    abstract boolean getNative();

    @Memoized
    boolean getMemoizedNative() {
      return getNative();
    }
  }

  @AutoValue
  @javax.annotation.Nullable
  abstract static class ValueWithoutCopyAnnotations {
    abstract boolean getNative();

    @Memoized
    boolean getMemoizedNative() {
      return getNative();
    }
  }

  @AutoValue
  abstract static class Value {
    private int primitiveCount;
    private int notNullableCount;
    private int nullableCount;
    private int returnsNullCount;
    private int nullableWithTypeAnnotationCount;
    private int returnsNullWithTypeAnnotationCount;
    private int notNullableButReturnsNullCount;
    private int throwsExceptionCount;

    @javax.annotation.Nullable
    abstract String string();

    abstract @org.checkerframework.checker.nullness.qual.Nullable String stringWithTypeAnnotation();

    abstract HashCodeAndToStringCounter counter();

    @Memoized
    int primitive() {
      return ++primitiveCount;
    }

    @Memoized
    String notNullable() {
      notNullableCount++;
      return "derived " + string() + " " + notNullableCount;
    }

    @Memoized
    @javax.annotation.Nullable
    String nullable() {
      nullableCount++;
      return "nullable derived " + string() + " " + nullableCount;
    }

    @Memoized
    @javax.annotation.Nullable
    String returnsNull() {
      returnsNullCount++;
      return null;
    }

    @Memoized
    @org.checkerframework.checker.nullness.qual.Nullable
    String nullableWithTypeAnnotation() {
      nullableWithTypeAnnotationCount++;
      return "nullable derived "
          + stringWithTypeAnnotation()
          + " "
          + nullableWithTypeAnnotationCount;
    }

    @Memoized
    @org.checkerframework.checker.nullness.qual.Nullable
    String returnsNullWithTypeAnnotation() {
      returnsNullWithTypeAnnotationCount++;
      return null;
    }

    @Memoized
    String notNullableButReturnsNull() {
      notNullableButReturnsNullCount++;
      return null;
    }

    @Memoized
    String throwsException() throws SomeCheckedException {
      throwsExceptionCount++;
      throw new SomeCheckedException();
    }

    @Override
    @Memoized
    public abstract int hashCode();

    @Override
    @Memoized
    public abstract String toString();
  }

  static final class SomeCheckedException extends Exception {}

  @AutoValue
  abstract static class ListValue<T extends Number, K> {

    abstract T value();

    abstract K otherValue();

    @Memoized
    ImmutableList<T> myTypedList() {
      return ImmutableList.of(value());
    }
  }

  static class HashCodeAndToStringCounter {
    int hashCodeCount;
    int toStringCount;

    @Override
    public int hashCode() {
      return ++hashCodeCount;
    }

    @Override
    public String toString() {
      return "a string" + ++toStringCount;
    }
  }

  @AutoValue
  abstract static class HashCodeEqualsOptimization {
    int overrideHashCode;
    int hashCodeCount;

    abstract EqualsCounter equalsCounter();

    @Memoized
    @Override
    public int hashCode() {
      hashCodeCount++;
      return overrideHashCode;
    }

    static class EqualsCounter {
      int equalsCount;

      @Override
      public int hashCode() {
        return 0;
      }

      @Override
      public boolean equals(Object obj) {
        equalsCount++;
        return true;
      }
    }
  }

  @AutoValue
  abstract static class HashCodeEqualsOptimizationOffWhenEqualsIsFinal {
    int hashCodeCount;

    @Override
    @Memoized
    public int hashCode() {
      hashCodeCount++;
      return 1;
    }

    @Override
    public final boolean equals(Object that) {
      return that instanceof HashCodeEqualsOptimizationOffWhenEqualsIsFinal;
    }
  }

  @Before
  public void setUp() {
    value =
        new AutoValue_MemoizedTest_Value(
            "string", "stringWithTypeAnnotation", new HashCodeAndToStringCounter());
    listValue = new AutoValue_MemoizedTest_ListValue<Integer, String>(0, "hello");
  }

  @Test
  public void listValueList() {
    assertThat(listValue.myTypedList()).containsExactly(listValue.value());
  }

  @Test
  public void listValueString() {
    assertThat(listValue.otherValue()).isEqualTo("hello");
  }

  @Test
  public void primitive() {
    assertThat(value.primitive()).isEqualTo(1);
    assertThat(value.primitive()).isEqualTo(1);
    assertThat(value.primitiveCount).isEqualTo(1);
  }

  @Test
  public void notNullable() {
    assertThat(value.notNullable()).isEqualTo("derived string 1");
    assertThat(value.notNullable()).isSameInstanceAs(value.notNullable());
    assertThat(value.notNullableCount).isEqualTo(1);
  }

  @Test
  public void nullable() {
    assertThat(value.nullable()).isEqualTo("nullable derived string 1");
    assertThat(value.nullable()).isSameInstanceAs(value.nullable());
    assertThat(value.nullableCount).isEqualTo(1);
  }

  @Test
  public void nullableWithTypeAnnotation() {
    assertThat(value.nullableWithTypeAnnotation())
        .isEqualTo("nullable derived stringWithTypeAnnotation 1");
    assertThat(value.nullableWithTypeAnnotation())
        .isSameInstanceAs(value.nullableWithTypeAnnotation());
    assertThat(value.nullableWithTypeAnnotationCount).isEqualTo(1);
  }

  @Test
  public void returnsNull() {
    assertThat(value.returnsNull()).isNull();
    assertThat(value.returnsNull()).isNull();
    assertThat(value.returnsNullCount).isEqualTo(1);
  }

  @Test
  public void returnsNullWithTypeAnnotation() {
    assertThat(value.returnsNullWithTypeAnnotation()).isNull();
    assertThat(value.returnsNullWithTypeAnnotation()).isNull();
    assertThat(value.returnsNullWithTypeAnnotationCount).isEqualTo(1);
  }

  @Test
  public void notNullableButReturnsNull() {
    try {
      value.notNullableButReturnsNull();
      fail();
    } catch (NullPointerException expected) {
      assertThat(expected)
          .hasMessageThat()
          .isEqualTo("notNullableButReturnsNull() cannot return null");
    }
    assertThat(value.notNullableButReturnsNullCount).isEqualTo(1);
  }

  @Test
  public void methodThrows() {
    // The exception is thrown.
    try {
      value.throwsException();
      fail();
    } catch (SomeCheckedException expected1) {
      // The exception is not memoized.
      try {
        value.throwsException();
        fail();
      } catch (SomeCheckedException expected2) {
        assertThat(expected2).isNotSameInstanceAs(expected1);
      }
    }
    assertThat(value.throwsExceptionCount).isEqualTo(2);
  }

  @Test
  public void testHashCode() {
    assertThat(value.hashCode()).isEqualTo(value.hashCode());
    assertThat(value.counter().hashCodeCount).isEqualTo(1);
  }

  @Test
  public void testToString() {
    assertThat(value.toString()).isEqualTo(value.toString());
    assertThat(value.counter().toStringCount).isEqualTo(1);
  }

  @Test
  public void keywords() {
    ValueWithKeywordName value = new AutoValue_MemoizedTest_ValueWithKeywordName(true, false);
    assertThat(value.getNative()).isTrue();
    assertThat(value.getMemoizedNative()).isTrue();
    assertThat(value.getNative0()).isFalse();
    assertThat(value.getMemoizedNative0()).isFalse();
  }

  @Test
  public void copyAnnotations() {
    ValueWithCopyAnnotations valueWithCopyAnnotations =
        new AutoValue_MemoizedTest_ValueWithCopyAnnotations(true);
    ValueWithoutCopyAnnotations valueWithoutCopyAnnotations =
        new AutoValue_MemoizedTest_ValueWithoutCopyAnnotations(true);

    assertThat(
            valueWithCopyAnnotations
                .getClass()
                .isAnnotationPresent(javax.annotation.Nullable.class))
        .isTrue();
    assertThat(
            valueWithoutCopyAnnotations
                .getClass()
                .isAnnotationPresent(javax.annotation.Nullable.class))
        .isFalse();
  }

  @Test
  public void nullableHasAnnotation() throws ReflectiveOperationException {
    Method nullable = AutoValue_MemoizedTest_Value.class.getDeclaredMethod("nullable");
    assertThat(nullable.isAnnotationPresent(javax.annotation.Nullable.class)).isTrue();
  }

  @Test
  public void nullableWithTypeAnnotationHasAnnotation() throws ReflectiveOperationException {
    Method nullable =
        AutoValue_MemoizedTest_Value.class.getDeclaredMethod("nullableWithTypeAnnotation");
    AnnotatedType returnType = nullable.getAnnotatedReturnType();
    assertThat(
            returnType.isAnnotationPresent(
                org.checkerframework.checker.nullness.qual.Nullable.class))
        .isTrue();
  }

  @Test
  public void nullableConstructorParameter() throws ReflectiveOperationException {
    // Constructor parameters are potentially:
    // [0] @javax.annotation.Nullable String string,
    // [1] @org.checkerframework.checker.nullness.qual.Nullable String stringWithTypeAnnotation,
    // [2] HashCodeAndToStringCounter counter
    // We don't currently copy @javax.annotation.Nullable because it is not a TYPE_USE annotation.
    Constructor<?> constructor =
        AutoValue_MemoizedTest_Value.class.getDeclaredConstructor(
            String.class, String.class, HashCodeAndToStringCounter.class);
    AnnotatedType paramType = constructor.getAnnotatedParameterTypes()[1];
    assertThat(
            paramType.isAnnotationPresent(
                org.checkerframework.checker.nullness.qual.Nullable.class))
        .isTrue();
  }

  @Test
  public void hashCodeEqualsOptimization() {
    HashCodeEqualsOptimization first =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimization(new EqualsCounter());
    HashCodeEqualsOptimization second =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimization(new EqualsCounter());

    first.overrideHashCode = 2;
    second.overrideHashCode = 2;
    assertThat(first.equals(second)).isTrue();
    assertThat(first.equalsCounter().equalsCount).isEqualTo(1);

    HashCodeEqualsOptimization otherwiseEqualsButDifferentHashCode =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimization(new EqualsCounter());
    otherwiseEqualsButDifferentHashCode.overrideHashCode = 4;

    assertThat(otherwiseEqualsButDifferentHashCode.equals(first)).isFalse();
    assertThat(otherwiseEqualsButDifferentHashCode.equalsCounter().equalsCount).isEqualTo(0);
  }

  @Test
  public void hashCodeEqualsOptimization_otherTypes() {
    HashCodeEqualsOptimization optimizedEquals =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimization(new EqualsCounter());

    assertThat(optimizedEquals.equals(new Object())).isFalse();
    assertThat(optimizedEquals.equals(null)).isFalse();

    assertThat(optimizedEquals.equalsCounter().equalsCount).isEqualTo(0);
    assertThat(optimizedEquals.hashCodeCount).isEqualTo(0);
  }

  @Test
  public void hashCodeEqualsOptimization_hashCodeIgnoredForSameInstance() {
    HashCodeEqualsOptimization optimizedEquals =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimization(new EqualsCounter());

    assertThat(optimizedEquals.equals(optimizedEquals)).isTrue();

    assertThat(optimizedEquals.equalsCounter().equalsCount).isEqualTo(0);
    assertThat(optimizedEquals.hashCodeCount).isEqualTo(0);
  }

  @Test
  public void hashCodeEqualsOptimization_offWhenEqualsIsFinal() {
    HashCodeEqualsOptimizationOffWhenEqualsIsFinal memoizedHashCodeAndFinalEqualsMethod =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimizationOffWhenEqualsIsFinal();
    HashCodeEqualsOptimizationOffWhenEqualsIsFinal second =
        new AutoValue_MemoizedTest_HashCodeEqualsOptimizationOffWhenEqualsIsFinal();

    assertThat(memoizedHashCodeAndFinalEqualsMethod.equals(second)).isTrue();
    assertThat(memoizedHashCodeAndFinalEqualsMethod.hashCodeCount).isEqualTo(0);

    int unused1 = memoizedHashCodeAndFinalEqualsMethod.hashCode();
    int unused2 = memoizedHashCodeAndFinalEqualsMethod.hashCode();
    assertThat(memoizedHashCodeAndFinalEqualsMethod.hashCodeCount).isEqualTo(1);
  }

  interface TypeEdgeIterable<InputT, ResultT> {}

  interface ResourceUri {}

  interface TypePath<InputT, ResultT> {}

  abstract static class AbstractTypePath<InputT, ResultT> {
    abstract TypeEdgeIterable<InputT, ResultT> edges();
  }

  @AutoValue
  abstract static class ResourceUriPath<InputT> extends AbstractTypePath<InputT, ResourceUri> {
    static <InputT> ResourceUriPath<InputT> create(TypeEdgeIterable<InputT, ResourceUri> edges) {
      return new AutoValue_MemoizedTest_ResourceUriPath<>(edges);
    }

    @Memoized
    TypePath<InputT, String> toServiceName() {
      return new TypePath<InputT, String>() {};
    }
  }

  @Test
  public void methodTypeFromTypeVariableSubsitution() {
    ResourceUriPath<String> path =
        ResourceUriPath.create(new TypeEdgeIterable<String, ResourceUri>() {});
    assertThat(path.edges()).isNotNull();
  }

  @Immutable
  @AutoValue
  abstract static class Unchanging<@ImmutableTypeParameter T> {
    abstract T value();

    @Override
    @Memoized
    public abstract int hashCode();

    static <@ImmutableTypeParameter T> Unchanging<T> of(T value) {
      return new AutoValue_MemoizedTest_Unchanging<T>(value);
    }
  }

  @Test
  public void copiedTypeAnnotations() {
    for (Class<?> c = Unchanging.of("foo").getClass(); c != Object.class; c = c.getSuperclass()) {
      assertThat(c.getTypeParameters()).hasLength(1);
      assertThat(c.getTypeParameters()[0].isAnnotationPresent(ImmutableTypeParameter.class))
          .isTrue();
    }
  }
}