File: ProvisionExceptionTest.java

package info (click to toggle)
guice 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,692 kB
  • sloc: java: 72,879; xml: 1,431; sh: 58; jsp: 12; makefile: 5
file content (472 lines) | stat: -rw-r--r-- 14,686 bytes parent folder | download
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
/*
 * Copyright (C) 2007 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.inject;

import static com.google.inject.Asserts.assertContains;
import static com.google.inject.Asserts.reserialize;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import com.google.common.base.Throwables;
import com.google.inject.spi.Message;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import junit.framework.TestCase;

/** @author jessewilson@google.com (Jesse Wilson) */
@SuppressWarnings("UnusedDeclaration")
public class ProvisionExceptionTest extends TestCase {

  public void testExceptionsCollapsed() {
    try {
      Guice.createInjector().getInstance(A.class);
      fail();
    } catch (ProvisionException e) {
      assertTrue(e.getCause() instanceof UnsupportedOperationException);
      assertContains(
          e.getMessage(),
          "UnsupportedOperationException",
          "at ProvisionExceptionTest$C.setD",
          "for 1st parameter d",
          "at ProvisionExceptionTest$B.c",
          "for field c",
          "at ProvisionExceptionTest$A.<init>",
          "for 1st parameter b");
    }
  }

  /**
   * There's a pass-through of user code in the scope. We want exceptions thrown by Guice to be
   * limited to a single exception, even if it passes through user code.
   */
  public void testExceptionsCollapsedWithScopes() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  bind(B.class).in(Scopes.SINGLETON);
                }
              })
          .getInstance(A.class);
      fail();
    } catch (ProvisionException e) {
      assertTrue(e.getCause() instanceof UnsupportedOperationException);
      assertFalse(e.getMessage().contains("custom provider"));
      assertContains(
          e.getMessage(),
          "UnsupportedOperationException",
          "at ProvisionExceptionTest$C.setD",
          "for 1st parameter d",
          "at ProvisionExceptionTest$B.c",
          "for field c",
          "at ProvisionExceptionTest$A.<init>",
          "for 1st parameter b");
    }
  }

  public void testMethodInjectionExceptions() {
    try {
      Guice.createInjector().getInstance(E.class);
      fail();
    } catch (ProvisionException e) {
      assertTrue(e.getCause() instanceof UnsupportedOperationException);
      assertContains(
          e.getMessage(),
          "[Guice/ErrorInjectingMethod]: UnsupportedOperationException",
          "at ProvisionExceptionTest$E.setObject");
    }
  }

  public void testBindToProviderInstanceExceptions() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  bind(D.class).toProvider(new DProvider());
                }
              })
          .getInstance(D.class);
      fail();
    } catch (ProvisionException e) {
      assertTrue(e.getCause() instanceof UnsupportedOperationException);
      assertContains(
          e.getMessage(),
          "1) [Guice/ErrorInCustomProvider]: UnsupportedOperationException",
          "at ProvisionExceptionTest$2.configure");
    }
  }

  /**
   * This test demonstrates that if the user throws a ProvisionException, we wrap it to add context.
   */
  public void testProvisionExceptionsAreWrappedForBindToType() {
    try {
      Guice.createInjector().getInstance(F.class);
      fail();
    } catch (ProvisionException e) {
      assertContains(e.getMessage(), "1) User Exception", "at ProvisionExceptionTest$F.<init>");
    }
  }

  public void testProvisionExceptionsAreWrappedForBindToProviderType() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  bind(F.class).toProvider(FProvider.class);
                }
              })
          .getInstance(F.class);
      fail();
    } catch (ProvisionException e) {
      assertContains(
          e.getMessage(),
          "1) User Exception",
          "while locating ProvisionExceptionTest$FProvider",
          "while locating ProvisionExceptionTest$F");
    }
  }

  public void testProvisionExceptionsAreWrappedForBindToProviderInstance() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  bind(F.class).toProvider(new FProvider());
                }
              })
          .getInstance(F.class);
      fail();
    } catch (ProvisionException e) {
      assertContains(e.getMessage(), "1) User Exception", "at ProvisionExceptionTest$4.configure");
    }
  }

  public void testProvisionExceptionIsSerializable() throws IOException {
    try {
      Guice.createInjector().getInstance(A.class);
      fail();
    } catch (ProvisionException expected) {
      ProvisionException reserialized = reserialize(expected);
      assertContains(
          reserialized.getMessage(),
          "1) [Guice/ErrorInjectingConstructor]: UnsupportedOperationException",
          "at ProvisionExceptionTest$RealD.<init>()",
          "at Key[type=ProvisionExceptionTest$RealD, annotation=[none]]",
          "@ProvisionExceptionTest$C.setD()[0]",
          "at Key[type=ProvisionExceptionTest$C, annotation=[none]]",
          "@ProvisionExceptionTest$B.c",
          "at Key[type=ProvisionExceptionTest$B, annotation=[none]]",
          "@ProvisionExceptionTest$A.<init>()[0]",
          "at Key[type=ProvisionExceptionTest$A, annotation=[none]]");
    }
  }

  // The only way to trigger an exception with _multiple_ user controlled throwables is by
  // triggering errors during injector creation.
  public void testMultipleCauses() {
    try {
      Guice.createInjector(
          Stage.PRODUCTION,
          new AbstractModule() {
            @Provides
            @Singleton
            String injectFirst() {
              throw new IllegalArgumentException(new UnsupportedOperationException("Unsupported"));
            }

            @Provides
            @Singleton
            Object injectSecond() {
              throw new NullPointerException("can't inject second either");
            }
          });
      fail();
    } catch (CreationException e) {
      assertContains(
          e.getMessage(),
          "IllegalArgumentException",
          "Caused by: IllegalArgumentException: UnsupportedOperationException",
          "Caused by: UnsupportedOperationException: Unsupported",
          "NullPointerException: can't inject second either",
          "Caused by: NullPointerException: can't inject second either",
          "2 errors");
    }
  }

  public void testInjectInnerClass() throws Exception {
    Injector injector = Guice.createInjector();
    try {
      injector.getInstance(InnerClass.class);
      fail();
    } catch (Exception expected) {
      assertContains(
          expected.getMessage(),
          "Injecting into inner classes is not supported.",
          "while locating ProvisionExceptionTest$InnerClass");
    }
  }

  public void testInjectLocalClass() throws Exception {
    class LocalClass {}

    Injector injector = Guice.createInjector();
    try {
      injector.getInstance(LocalClass.class);
      fail();
    } catch (Exception expected) {
      assertContains(
          expected.getMessage(),
          "Injecting into inner classes is not supported.",
          "while locating ProvisionExceptionTest$1LocalClass");
    }
  }

  public void testBindingAnnotationsOnMethodsAndConstructors() {
    try {
      Injector injector = Guice.createInjector();
      injector.getInstance(MethodWithBindingAnnotation.class);
      fail();
    } catch (ConfigurationException expected) {
      assertContains(
          expected.getMessage(),
          "ProvisionExceptionTest$MethodWithBindingAnnotation.injectMe() is annotated "
              + "with @ProvisionExceptionTest$Green(), but binding annotations should be "
              + "applied to its parameters instead.",
          "while locating ProvisionExceptionTest$MethodWithBindingAnnotation");
    }

    try {
      Guice.createInjector().getInstance(ConstructorWithBindingAnnotation.class);
      fail();
    } catch (ConfigurationException expected) {
      assertContains(
          expected.getMessage(),
          "ProvisionExceptionTest$ConstructorWithBindingAnnotation.<init>() is annotated with"
              + " @ProvisionExceptionTest$Green(), but binding annotations should be applied to"
              + " its parameters instead.",
          "at ProvisionExceptionTest$ConstructorWithBindingAnnotation.class",
          "while locating ProvisionExceptionTest$ConstructorWithBindingAnnotation");
    }
  }

  public void testBindingAnnotationWarningForScala() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(String.class).annotatedWith(Green.class).toInstance("lime!");
              }
            });
    injector.getInstance(LikeScala.class);
  }

  public void testLinkedBindings() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(D.class).to(RealD.class);
              }
            });

    try {
      injector.getInstance(D.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "at ProvisionExceptionTest$RealD.<init>",
          "while locating ProvisionExceptionTest$RealD",
          "while locating ProvisionExceptionTest$D");
    }
  }

  public void testProviderKeyBindings() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(D.class).toProvider(DProvider.class);
              }
            });

    try {
      injector.getInstance(D.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "while locating ProvisionExceptionTest$DProvider",
          "while locating ProvisionExceptionTest$D");
    }
  }

  public void testDuplicateCausesCollapsed() {
    final RuntimeException sharedException = new RuntimeException("fail");
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              addError(sharedException);
              addError(sharedException);
            }
          });
      fail();
    } catch (CreationException ce) {
      assertEquals(sharedException, ce.getCause());
      assertEquals(2, ce.getErrorMessages().size());
      for (Message message : ce.getErrorMessages()) {
        assertEquals(sharedException, message.getCause());
      }
    }
  }

  public void testMultipleDuplicates() {
    final RuntimeException exception1 = new RuntimeException("fail");
    final RuntimeException exception2 = new RuntimeException("abort");
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              addError(exception1);
              addError(exception1);
              addError(exception2);
              addError(exception2);
            }
          });
      fail();
    } catch (CreationException ce) {
      assertNull(ce.getCause());
      assertEquals(4, ce.getErrorMessages().size());

      String e1 = Throwables.getStackTraceAsString(exception1);
      String e2 = Throwables.getStackTraceAsString(exception2);
      assertContains(
          ce.getMessage(),
          "\n1) ",
          "Caused by: RuntimeException: fail",
          "\n2) ",
          "(same stack trace as error #1)",
          "\n3) ",
          "Caused by: RuntimeException: abort",
          "\n4) ",
          "(same stack trace as error #3)");
    }
  }

  @SuppressWarnings("ClassCanBeStatic")
  private class InnerClass {}

  static class A {
    @Inject
    A(B b) {}
  }

  static class B {
    @Inject C c;
  }

  static class C {
    @Inject
    void setD(RealD d) {}
  }

  static class E {
    @Inject
    void setObject(Object o) {
      throw new UnsupportedOperationException();
    }
  }

  static class MethodWithBindingAnnotation {
    @Inject
    @Green
    void injectMe(String greenString) {}
  }

  static class ConstructorWithBindingAnnotation {
    // Suppress compiler errors by the error-prone checker InjectedConstructorAnnotations,
    // which catches injected constructors with binding annotations.
    @SuppressWarnings("InjectedConstructorAnnotations")
    @Inject
    @Green
    ConstructorWithBindingAnnotation(String greenString) {}
  }

  /**
   * In Scala, fields automatically get accessor methods with the same name. So we don't do
   * misplaced-binding annotation detection if the offending method has a matching field.
   */
  static class LikeScala {
    @Inject @Green String green;

    @Inject
    @Green
    String green() {
      return green;
    }
  }

  @Retention(RUNTIME)
  @Target({FIELD, PARAMETER, CONSTRUCTOR, METHOD})
  @BindingAnnotation
  @interface Green {}

  interface D {}

  static class RealD implements D {
    @Inject
    RealD() {
      throw new UnsupportedOperationException();
    }
  }

  static class DProvider implements Provider<D> {
    @Override
    public D get() {
      throw new UnsupportedOperationException();
    }
  }

  static class F {
    @Inject
    public F() {
      throw new ProvisionException("User Exception", new RuntimeException());
    }
  }

  static class FProvider implements Provider<F> {
    @Override
    public F get() {
      return new F();
    }
  }
}