File: CircularDependencyTest.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 (775 lines) | stat: -rw-r--r-- 20,321 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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
/*
 * Copyright (C) 2006 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 java.lang.annotation.RetentionPolicy.RUNTIME;

import com.google.common.collect.Maps;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;

/**
 * @author crazybob@google.com (Bob Lee)
 * @author sameb@google.com (Sam Berlin)
 */
public class CircularDependencyTest extends TestCase {

  @Override
  protected void setUp() throws Exception {
    AImpl.nextId = 0;
    BImpl.nextId = 0;
  }

  public void testCircularlyDependentConstructors() throws CreationException {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(A.class).to(AImpl.class);
                bind(B.class).to(BImpl.class);
              }
            });
    assertCircularDependencies(injector);
  }

  public void testCircularlyDependentConstructorsWithProviderMethods() throws CreationException {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {

              @Provides
              @Singleton
              A a(B b) {
                return new AImpl(b);
              }

              @Provides
              B b(A a) {
                return new BImpl(a);
              }
            });
    assertCircularDependencies(injector);
  }

  public void testCircularlyDependentConstructorsWithProviderInstances() throws CreationException {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(A.class)
                    .toProvider(
                        new Provider<A>() {
                          @Inject Provider<B> bp;

                          @Override
                          public A get() {
                            return new AImpl(bp.get());
                          }
                        })
                    .in(Singleton.class);
                bind(B.class)
                    .toProvider(
                        new Provider<B>() {
                          @Inject Provider<A> ap;

                          @Override
                          public B get() {
                            return new BImpl(ap.get());
                          }
                        });
              }
            });
    assertCircularDependencies(injector);
  }

  public void testCircularlyDependentConstructorsWithProviderKeys() throws CreationException {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(A.class).toProvider(AP.class).in(Singleton.class);
                bind(B.class).toProvider(BP.class);
              }
            });
    assertCircularDependencies(injector);
  }

  public void testCircularlyDependentConstructorsWithProvidedBy() throws CreationException {
    Injector injector = Guice.createInjector();
    assertCircularDependencies(injector);
  }

  private void assertCircularDependencies(Injector injector) {
    A a = injector.getInstance(A.class);
    assertNotNull(a.getB().getA());
    assertEquals(0, a.id());
    assertEquals(a.id(), a.getB().getA().id());
    assertEquals(0, a.getB().id());
    assertEquals(1, AImpl.nextId);
    assertEquals(1, BImpl.nextId);
    assertSame(a, injector.getInstance(A.class));
  }

  @ProvidedBy(AutoAP.class)
  public interface A {
    B getB();

    int id();
  }

  @Singleton
  static class AImpl implements A {
    static int nextId;
    int id = nextId++;

    final B b;

    @Inject
    public AImpl(B b) {
      this.b = b;
    }

    @Override
    public int id() {
      return id;
    }

    @Override
    public B getB() {
      return b;
    }
  }

  static class AP implements Provider<A> {
    @Inject Provider<B> bp;

    @Override
    public A get() {
      return new AImpl(bp.get());
    }
  }

  @Singleton
  static class AutoAP implements Provider<A> {
    @Inject Provider<B> bp;
    A a;

    @Override
    public A get() {
      if (a == null) {
        a = new AImpl(bp.get());
      }
      return a;
    }
  }

  @ProvidedBy(BP.class)
  public interface B {
    A getA();

    int id();
  }

  static class BImpl implements B {
    static int nextId;
    int id = nextId++;

    final A a;

    @Inject
    public BImpl(A a) {
      this.a = a;
    }

    @Override
    public int id() {
      return id;
    }

    @Override
    public A getA() {
      return a;
    }
  }

  static class BP implements Provider<B> {
    Provider<A> ap;

    @Inject
    BP(Provider<A> ap) {
      this.ap = ap;
    }

    @Override
    public B get() {
      return new BImpl(ap.get());
    }
  }

  public void testUnresolvableCircularDependency() {
    try {
      Guice.createInjector().getInstance(C.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Tried proxying CircularDependencyTest$C to support a circular dependency, ",
          "but it is not an interface.");
    }
  }

  public void testUnresolvableCircularDependenciesWithProviderInstances() {
    try {
      Guice.createInjector(
              new AbstractModule() {

                @Provides
                C c(D d) {
                  return null;
                }

                @Provides
                D d(C c) {
                  return null;
                }
              })
          .getInstance(C.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Tried proxying CircularDependencyTest$C to support a circular dependency, ",
          "but it is not an interface.");
    }
  }

  public void testUnresolvableCircularDependenciesWithProviderKeys() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  bind(C2.class).toProvider(C2P.class);
                  bind(D2.class).toProvider(D2P.class);
                }
              })
          .getInstance(C2.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Tried proxying CircularDependencyTest$C2 to support a circular dependency, ",
          "but it is not an interface.");
    }
  }

  public void testUnresolvableCircularDependenciesWithProvidedBy() {
    try {
      Guice.createInjector().getInstance(C2.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Tried proxying CircularDependencyTest$C2 to support a circular dependency, ",
          "but it is not an interface.");
    }
  }

  static class C {
    @Inject
    C(D d) {}
  }

  static class D {
    @Inject
    D(C c) {}
  }

  static class C2P implements Provider<C2> {
    @Inject Provider<D2> dp;

    @Override
    public C2 get() {
      dp.get();
      return null;
    }
  }

  static class D2P implements Provider<D2> {
    @Inject Provider<C2> cp;

    @Override
    public D2 get() {
      cp.get();
      return null;
    }
  }

  @ProvidedBy(C2P.class)
  static class C2 {
    @Inject
    C2(D2 d) {}
  }

  @ProvidedBy(D2P.class)
  static class D2 {
    @Inject
    D2(C2 c) {}
  }

  public void testDisabledCircularDependency() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  binder().disableCircularProxies();
                }
              })
          .getInstance(C.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$C"
              + ", and circular dependencies are disabled.");
    }
  }

  public void testDisabledCircularDependenciesWithProviderInstances() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  binder().disableCircularProxies();
                }

                @Provides
                C c(D d) {
                  return null;
                }

                @Provides
                D d(C c) {
                  return null;
                }
              })
          .getInstance(C.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$C"
              + ", and circular dependencies are disabled.");
    }
  }

  public void testDisabledCircularDependenciesWithProviderKeys() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  binder().disableCircularProxies();
                  bind(C2.class).toProvider(C2P.class);
                  bind(D2.class).toProvider(D2P.class);
                }
              })
          .getInstance(C2.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$C2"
              + ", and circular dependencies are disabled.");
    }
  }

  public void testDisabledCircularDependenciesWithProvidedBy() {
    try {
      Guice.createInjector(
              new AbstractModule() {
                @Override
                protected void configure() {
                  binder().disableCircularProxies();
                }
              })
          .getInstance(C2.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$C2"
              + ", and circular dependencies are disabled.");
    }
  }

  /**
   * As reported by issue 349, we give a lousy trace when a class is circularly dependent on itself
   * in multiple ways.
   */
  public void testCircularlyDependentMultipleWays() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                binder.bind(A.class).to(E.class);
                binder.bind(B.class).to(E.class);
              }
            });
    injector.getInstance(A.class);
  }

  public void testDisablingCircularDependencies() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                binder().disableCircularProxies();
                binder.bind(A.class).to(E.class);
                binder.bind(B.class).to(E.class);
              }
            });

    try {
      injector.getInstance(A.class);
      fail("expected exception");
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$A, and circular"
              + " dependencies are disabled.");
    }
  }

  @Singleton
  static class E implements A, B {
    @Inject
    public E(A a, B b) {}

    @Override
    public B getB() {
      return this;
    }

    @Override
    public A getA() {
      return this;
    }

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

  public void testCircularDependencyProxyDelegateNeverInitialized() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(F.class).to(RealF.class);
                bind(G.class).to(RealG.class);
              }
            });
    F f = injector.getInstance(F.class);
    assertEquals("F", f.g().f().toString());
    assertEquals("G", f.g().f().g().toString());
  }

  public interface F {
    G g();
  }

  @Singleton
  public static class RealF implements F {
    private final G g;

    @Inject
    RealF(G g) {
      this.g = g;
    }

    @Override
    public G g() {
      return g;
    }

    @Override
    public String toString() {
      return "F";
    }
  }

  public interface G {
    F f();
  }

  @Singleton
  public static class RealG implements G {
    private final F f;

    @Inject
    RealG(F f) {
      this.f = f;
    }

    @Override
    public F f() {
      return f;
    }

    @Override
    public String toString() {
      return "G";
    }
  }

  /**
   * Tests that ProviderInternalFactory can detect circular dependencies before it gets to
   * Scopes.SINGLETON. This is especially important because the failure in Scopes.SINGLETON doesn't
   * have enough context to provide a decent error message.
   */
  public void testCircularDependenciesDetectedEarlyWhenDependenciesHaveDifferentTypes() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(Number.class).to(Integer.class);
              }

              @Provides
              @Singleton
              Integer provideInteger(List<Object> list) {
                return 2;
              }

              @Provides
              List<Object> provideList(Integer integer) {
                return new ArrayList<>();
              }
            });
    try {
      injector.getInstance(Number.class);
      fail();
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Tried proxying Integer to support a circular dependency, ",
          "but it is not an interface.");
    }
  }

  public void testPrivateModulesDontTriggerCircularErrorsInProviders() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                install(
                    new PrivateModule() {
                      @Override
                      protected void configure() {
                        bind(Foo.class);
                        expose(Foo.class);
                      }

                      @Provides
                      String provideString(Bar bar) {
                        return new String("private 1, " + bar.string);
                      }
                    });
                install(
                    new PrivateModule() {
                      @Override
                      protected void configure() {
                        bind(Bar.class);
                        expose(Bar.class);
                      }

                      @Provides
                      String provideString() {
                        return new String("private 2");
                      }
                    });
              }
            });
    Foo foo = injector.getInstance(Foo.class);
    assertEquals("private 1, private 2", foo.string);
  }

  static class Foo {
    @Inject String string;
  }

  static class Bar {
    @Inject String string;
  }

  /**
   * When Scope Providers call their unscoped Provider's get() methods are called, it's possible
   * that the result is a circular proxy designed for one specific parameter (not for all possible
   * parameters). But custom scopes typically cache the results without checking to see if the
   * result is a proxy. This leads to caching a result that is unsuitable for reuse for other
   * parameters.
   *
   * <p>This means that custom proxies have to do an {@code if(Scopes.isCircularProxy(..))} in order
   * to avoid exceptions.
   */
  public void testCustomScopeCircularProxies() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bindScope(SimpleSingleton.class, new BasicSingleton());
                bind(H.class).to(HImpl.class);
                bind(I.class).to(IImpl.class);
                bind(J.class).to(JImpl.class);
              }
            });

    // The reason this happens is because the Scope gets these requests, in order:
    // entry: Key<IImpl> (1 - from getInstance call)
    // entry: Key<HImpl>
    // entry: Key<IImpl> (2 - circular dependency from HImpl)
    // result of 2nd Key<IImpl> - a com.google.inject.$Proxy, because it's a circular proxy
    // result of Key<HImpl> - an HImpl
    // entry: Key<JImpl>
    // entry: Key<IImpl> (3 - another circular dependency, this time from JImpl)
    // At this point, if the first Key<Impl> result was cached, our cache would have
    //  Key<IImpl> caching to an instanceof of I, but not an an instanceof of IImpl.
    // If returned this, it would result in a ClassCastException or IllegalArgumentException
    // when filling in parameters for the constructor, because JImpl wants an IImpl, not an I.

    try {
      injector.getInstance(IImpl.class);
      fail();
    } catch (ProvisionException pe) {
      assertContains(
          pe.getMessage(),
          "Tried proxying CircularDependencyTest$IImpl"
              + " to support a circular dependency, but it is not an interface.",
          "1 error");
    }
  }

  interface H {}

  interface I {}

  interface J {}

  @SimpleSingleton
  static class HImpl implements H {
    @Inject
    HImpl(I i) {}
  }

  @SimpleSingleton
  static class IImpl implements I {
    @Inject
    IImpl(HImpl i, J j) {}
  }

  @SimpleSingleton
  static class JImpl implements J {
    @Inject
    JImpl(IImpl i) {}
  }

  @Target({ElementType.TYPE, ElementType.METHOD})
  @Retention(RUNTIME)
  @ScopeAnnotation
  public @interface SimpleSingleton {}

  public static class BasicSingleton implements Scope {
    private static Map<Key<?>, Object> cache = Maps.newHashMap();

    @Override
    public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
      return new Provider<T>() {
        @Override
        @SuppressWarnings("unchecked")
        public T get() {
          if (!cache.containsKey(key)) {
            T t = unscoped.get();
            if (Scopes.isCircularProxy(t)) {
              return t;
            }
            cache.put(key, t);
          }
          return (T) cache.get(key);
        }
      };
    }
  }

  public void testDisabledNonConstructorCircularDependencies() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                binder().disableCircularProxies();
              }
            });

    try {
      injector.getInstance(K.class);
      fail("expected exception");
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$K"
              + ", and circular dependencies are disabled.");
    }

    try {
      injector.getInstance(L.class);
      fail("expected exception");
    } catch (ProvisionException expected) {
      assertContains(
          expected.getMessage(),
          "Found a circular dependency involving CircularDependencyTest$L"
              + ", and circular dependencies are disabled.");
    }
  }

  static class K {
    @Inject L l;
  }

  static class L {
    @Inject
    void inject(K k) {}
  }
}