aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/android/desugar/runtime/ThrowableExtensionTest.java
blob: 5ac88b89deac9dbb470d473281e03578632192fc (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
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.android.desugar.runtime;

import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.android.desugar.runtime.ThrowableExtension.MimicDesugaringStrategy.SUPPRESSED_PREFIX;
import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.getTwrStrategyClassNameSpecifiedInSystemProperty;
import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.isNullStrategy;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.fail;

import com.google.devtools.build.android.desugar.runtime.ThrowableExtension.MimicDesugaringStrategy;
import com.google.devtools.build.android.desugar.runtime.ThrowableExtension.NullDesugaringStrategy;
import com.google.devtools.build.android.desugar.runtime.ThrowableExtension.ReuseDesugaringStrategy;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Test case for {@link ThrowableExtension} */
@RunWith(JUnit4.class)
public class ThrowableExtensionTest {

  /**
   * This test tests the behavior of closing resources via reflection. This is only enabled below
   * API 19. So, if the API level is 19 or above, this test will simply skip.
   */
  @Test
  public void testCloseResourceViaReflection() throws Throwable {
    class Resource extends AbstractResource {
      protected Resource(boolean exceptionOnClose) {
        super(exceptionOnClose);
      }

      public void close() throws Exception {
        super.internalClose();
      }
    }
    if (ThrowableExtension.API_LEVEL >= 19) {
      return;
    }
    {
      Resource r = new Resource(false);
      assertThat(r.isClosed()).isFalse();
      ThrowableExtension.closeResource(null, r);
      assertThat(r.isClosed()).isTrue();
    }
    {
      Resource r = new Resource(true);
      assertThat(r.isClosed()).isFalse();
      assertThrows(IOException.class, () -> ThrowableExtension.closeResource(null, r));
    }
    {
      Resource r = new Resource(false);
      assertThat(r.isClosed()).isFalse();
      ThrowableExtension.closeResource(new Exception(), r);
      assertThat(r.isClosed()).isTrue();
    }
    {
      Resource r = new Resource(true);
      assertThat(r.isClosed()).isFalse();
      assertThrows(Exception.class, () -> ThrowableExtension.closeResource(new Exception(), r));
    }
  }

  /**
   * Test the new method closeResources() in the runtime library.
   *
   * <p>The method is introduced to fix b/37167433.
   */
  @Test
  public void testCloseResource() throws Throwable {

    /**
     * A resource implementing the interface AutoCloseable. This interface is only available since
     * API 19.
     */
    class AutoCloseableResource extends AbstractResource implements AutoCloseable {

      protected AutoCloseableResource(boolean exceptionOnClose) {
        super(exceptionOnClose);
      }

      @Override
      public void close() throws Exception {
        internalClose();
      }
    }

    /** A resource implementing the interface Closeable. */
    class CloseableResource extends AbstractResource implements Closeable {

      protected CloseableResource(boolean exceptionOnClose) {
        super(exceptionOnClose);
      }

      @Override
      public void close() throws IOException {
        internalClose();
      }
    }

    {
      CloseableResource r = new CloseableResource(false);
      assertThat(r.isClosed()).isFalse();
      ThrowableExtension.closeResource(null, r);
      assertThat(r.isClosed()).isTrue();
    }
    {
      CloseableResource r = new CloseableResource(false);
      assertThat(r.isClosed()).isFalse();
      Exception suppressor = new Exception();
      ThrowableExtension.closeResource(suppressor, r);
      assertThat(r.isClosed()).isTrue();
      assertThat(ThrowableExtension.getSuppressed(suppressor)).isEmpty();
    }
    {
      CloseableResource r = new CloseableResource(true);
      assertThat(r.isClosed()).isFalse();
      assertThrows(IOException.class, () -> ThrowableExtension.closeResource(null, r));
      assertThat(r.isClosed()).isFalse();
    }
    {
      CloseableResource r = new CloseableResource(true);
      assertThat(r.isClosed()).isFalse();
      Exception suppressor = new Exception();
      assertThrows(Exception.class, () -> ThrowableExtension.closeResource(suppressor, r));
      assertThat(r.isClosed()).isFalse(); // Failed to close.
      if (!isNullStrategy()) {
        assertThat(ThrowableExtension.getSuppressed(suppressor)).hasLength(1);
        assertThat(ThrowableExtension.getSuppressed(suppressor)[0].getClass())
            .isEqualTo(IOException.class);
      }
    }
    {
      AutoCloseableResource r = new AutoCloseableResource(false);
      assertThat(r.isClosed()).isFalse();
      ThrowableExtension.closeResource(null, r);
      assertThat(r.isClosed()).isTrue();
    }
    {
      AutoCloseableResource r = new AutoCloseableResource(false);
      assertThat(r.isClosed()).isFalse();
      Exception suppressor = new Exception();
      ThrowableExtension.closeResource(suppressor, r);
      assertThat(r.isClosed()).isTrue();
      assertThat(ThrowableExtension.getSuppressed(suppressor)).isEmpty();
    }
    {
      AutoCloseableResource r = new AutoCloseableResource(true);
      assertThat(r.isClosed()).isFalse();
      assertThrows(IOException.class, () -> ThrowableExtension.closeResource(null, r));
      assertThat(r.isClosed()).isFalse();
    }
    {
      AutoCloseableResource r = new AutoCloseableResource(true);
      assertThat(r.isClosed()).isFalse();
      Exception suppressor = new Exception();
      assertThrows(Exception.class, () -> ThrowableExtension.closeResource(suppressor, r));
      assertThat(r.isClosed()).isFalse(); // Failed to close.
      if (!isNullStrategy()) {
        assertThat(ThrowableExtension.getSuppressed(suppressor)).hasLength(1);
        assertThat(ThrowableExtension.getSuppressed(suppressor)[0].getClass())
            .isEqualTo(IOException.class);
      }
      assertThat(r.isClosed()).isFalse();
    }
  }

  /**
   * LightweightStackTraceRecorder tracks the calls of various printStackTrace(*), and ensures that
   *
   * <p>suppressed exceptions are printed only once.
   */
  @Test
  public void testLightweightStackTraceRecorder() throws IOException {
    MimicDesugaringStrategy strategy = new MimicDesugaringStrategy();
    ExceptionForTest receiver = new ExceptionForTest(strategy);
    FileNotFoundException suppressed = new FileNotFoundException();
    strategy.addSuppressed(receiver, suppressed);

    String trace = printStackTraceStderrToString(() -> strategy.printStackTrace(receiver));
    assertThat(trace).contains(SUPPRESSED_PREFIX);
    assertThat(countOccurrences(trace, SUPPRESSED_PREFIX)).isEqualTo(1);
  }

  @Test
  public void testMimicDesugaringStrategy() throws IOException {
    MimicDesugaringStrategy strategy = new MimicDesugaringStrategy();
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    strategy.addSuppressed(receiver, suppressed);

    assertThat(
            printStackTracePrintStreamToString(
                stream -> strategy.printStackTrace(receiver, stream)))
        .contains(SUPPRESSED_PREFIX);

    assertThat(
            printStackTracePrintWriterToString(
                writer -> strategy.printStackTrace(receiver, writer)))
        .contains(SUPPRESSED_PREFIX);

    assertThat(printStackTraceStderrToString(() -> strategy.printStackTrace(receiver)))
        .contains(SUPPRESSED_PREFIX);
  }

  private void testThrowableExtensionWithMimicDesugaringStrategy() throws IOException {
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    ThrowableExtension.addSuppressed(receiver, suppressed);

    assertThat(
            printStackTracePrintStreamToString(
                stream -> ThrowableExtension.printStackTrace(receiver, stream)))
        .contains(SUPPRESSED_PREFIX);
    assertThat(
            printStackTracePrintWriterToString(
                writer -> ThrowableExtension.printStackTrace(receiver, writer)))
        .contains(SUPPRESSED_PREFIX);
    assertThat(printStackTraceStderrToString(() -> ThrowableExtension.printStackTrace(receiver)))
        .contains(SUPPRESSED_PREFIX);
  }

  private interface PrintStackTraceCaller {
    void printStackTrace();
  }

  private static String printStackTraceStderrToString(PrintStackTraceCaller caller)
      throws IOException {
    PrintStream err = System.err;
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
      PrintStream newErr = new PrintStream(stream);
      System.setErr(newErr);
      caller.printStackTrace();
      newErr.flush();
      return stream.toString();
    } finally {
      System.setErr(err);
    }
  }

  private static String printStackTracePrintStreamToString(Consumer<PrintStream> caller)
      throws IOException {
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
      PrintStream printStream = new PrintStream(stream);
      caller.accept(printStream);
      printStream.flush();
      return stream.toString();
    }
  }

  private static String printStackTracePrintWriterToString(Consumer<PrintWriter> caller)
      throws IOException {
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
      PrintWriter printWriter =
          new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, UTF_8)));
      caller.accept(printWriter);
      printWriter.flush();
      return stream.toString();
    }
  }

  @Test
  public void testNullDesugaringStrategy() throws IOException {
    NullDesugaringStrategy strategy = new NullDesugaringStrategy();
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    strategy.addSuppressed(receiver, suppressed);
    assertThat(strategy.getSuppressed(receiver)).isEmpty();

    strategy.addSuppressed(receiver, suppressed);
    assertThat(strategy.getSuppressed(receiver)).isEmpty();

    assertThat(printStackTracePrintStreamToString(stream -> receiver.printStackTrace(stream)))
        .isEqualTo(
            printStackTracePrintStreamToString(
                stream -> strategy.printStackTrace(receiver, stream)));

    assertThat(printStackTracePrintWriterToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTracePrintWriterToString(
                writer -> strategy.printStackTrace(receiver, writer)));

    assertThat(printStackTraceStderrToString(receiver::printStackTrace))
        .isEqualTo(printStackTraceStderrToString(() -> strategy.printStackTrace(receiver)));
  }

  private void testThrowableExtensionWithNullDesugaringStrategy() throws IOException {
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    ThrowableExtension.addSuppressed(receiver, suppressed);
    assertThat(ThrowableExtension.getSuppressed(receiver)).isEmpty();

    ThrowableExtension.addSuppressed(receiver, suppressed);
    assertThat(ThrowableExtension.getSuppressed(receiver)).isEmpty();

    assertThat(printStackTracePrintStreamToString(stream -> receiver.printStackTrace(stream)))
        .isEqualTo(
            printStackTracePrintStreamToString(
                stream -> ThrowableExtension.printStackTrace(receiver, stream)));
    assertThat(printStackTracePrintWriterToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTracePrintWriterToString(
                writer -> ThrowableExtension.printStackTrace(receiver, writer)));

    assertThat(printStackTraceStderrToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTraceStderrToString(() -> ThrowableExtension.printStackTrace(receiver)));
  }

  @Test
  public void testReuseDesugaringStrategy() throws IOException {
    ReuseDesugaringStrategy strategy = new ReuseDesugaringStrategy();
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    strategy.addSuppressed(receiver, suppressed);
    assertThat(strategy.getSuppressed(receiver))
        .asList()
        .containsExactly((Object[]) receiver.getSuppressed());

    assertThat(printStackTracePrintStreamToString(stream -> receiver.printStackTrace(stream)))
        .isEqualTo(
            printStackTracePrintStreamToString(
                stream -> strategy.printStackTrace(receiver, stream)));

    assertThat(printStackTracePrintWriterToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTracePrintWriterToString(
                writer -> strategy.printStackTrace(receiver, writer)));
    assertThat(printStackTraceStderrToString(receiver::printStackTrace))
        .isEqualTo(printStackTraceStderrToString(() -> strategy.printStackTrace(receiver)));
  }

  private void testThrowableExtensionWithReuseDesugaringStrategy() throws IOException {
    IOException receiver = new IOException();
    FileNotFoundException suppressed = new FileNotFoundException();
    ThrowableExtension.addSuppressed(receiver, suppressed);
    assertThat(ThrowableExtension.getSuppressed(receiver))
        .asList()
        .containsExactly((Object[]) receiver.getSuppressed());

    assertThat(printStackTracePrintStreamToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTracePrintStreamToString(
                stream -> ThrowableExtension.printStackTrace(receiver, stream)));

    assertThat(printStackTracePrintWriterToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTracePrintWriterToString(
                writer -> ThrowableExtension.printStackTrace(receiver, writer)));

    assertThat(printStackTraceStderrToString(receiver::printStackTrace))
        .isEqualTo(
            printStackTraceStderrToString(() -> ThrowableExtension.printStackTrace(receiver)));
  }

  /** This class */
  private static class ExceptionForTest extends Exception {

    private final MimicDesugaringStrategy strategy;

    public ExceptionForTest(MimicDesugaringStrategy strategy) {
      this.strategy = strategy;
    }

    @Override
    public void printStackTrace() {
      this.printStackTrace(System.err);
    }

    /**
     * This method should call this.printStackTrace(PrintWriter) directly. I deliberately change it
     * to strategy.printStackTrace(Throwable, PrintWriter) to simulate the behavior of Desguar, that
     * is, the direct call is intercepted and redirected to ThrowableExtension.
     */
    @Override
    public void printStackTrace(PrintStream s) {
      this.strategy.printStackTrace(
          this, new PrintWriter(new BufferedWriter(new OutputStreamWriter(s, UTF_8))));
    }
  }

  @Test
  public void testStrategySelection() throws ClassNotFoundException, IOException {
    String expectedStrategyClassName = getTwrStrategyClassNameSpecifiedInSystemProperty();
    assertThat(expectedStrategyClassName).isNotEmpty();
    assertThat(expectedStrategyClassName)
        .isEqualTo(ThrowableExtension.STRATEGY.getClass().getName());

    Class<?> expectedStrategyClass = Class.forName(expectedStrategyClassName);
    if (expectedStrategyClass.equals(ReuseDesugaringStrategy.class)) {
      testThrowableExtensionWithReuseDesugaringStrategy();
    } else if (expectedStrategyClass.equals(MimicDesugaringStrategy.class)) {
      testThrowableExtensionWithMimicDesugaringStrategy();
    } else if (expectedStrategyClass.equals(NullDesugaringStrategy.class)) {
      testThrowableExtensionWithNullDesugaringStrategy();
    } else {
      fail("unrecognized expected strategy class " + expectedStrategyClassName);
    }
  }

  private static int countOccurrences(String string, String substring) {
    int i = 0;
    int count = 0;
    while ((i = string.indexOf(substring, i)) >= 0) {
      ++count;
      i = i + string.length();
    }
    return count;
  }

  /** A mocked closeable class, which we can query the closedness. */
  private abstract static class AbstractResource {
    private final boolean exceptionOnClose;
    private boolean closed;

    protected AbstractResource(boolean exceptionOnClose) {
      this.exceptionOnClose = exceptionOnClose;
    }

    boolean isClosed() {
      return closed;
    }

    void internalClose() throws IOException {
      if (exceptionOnClose) {
        throw new IOException("intended exception");
      }
      closed = true;
    }
  }
}