aboutsummaryrefslogtreecommitdiff
path: root/android/guava-tests/test/com/google/common/util/concurrent/GeneratedMonitorTest.java
blob: 9054ea9752c844d64b45edbc5726c8230b6a5864 (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
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
776
777
778
779
780
781
782
/*
 * Copyright (C) 2014 The Guava Authors
 *
 * 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.util.concurrent;

import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;

import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Generated tests for {@link Monitor}.
 *
 * <p>This test class generates all of its own test cases in the {@link #suite()} method. Every
 * {@code enterXxx}, {@code tryEnterXxx}, and {@code waitForXxx} method of the {@code Monitor} class
 * is analyzed reflectively to determine appropriate test cases based on its signature. Additional
 * ad hoc test cases can be found in {@link SupplementalMonitorTest}.
 *
 * @author Justin T. Sampson
 */
public class GeneratedMonitorTest extends TestCase {

  public static TestSuite suite() {
    TestSuite suite = new TestSuite();

    Method[] methods = Monitor.class.getMethods();
    sortMethods(methods);
    for (Method method : methods) {
      if (isAnyEnter(method) || isWaitFor(method)) {
        validateMethod(method);
        addTests(suite, method);
      }
    }

    assertEquals(548, suite.testCount());

    return suite;
  }

  /** A typical timeout value we'll use in the tests. */
  private static final long SMALL_TIMEOUT_MILLIS = 10;

  /** How long to wait when determining that a thread is blocked if we expect it to be blocked. */
  private static final long EXPECTED_HANG_DELAY_MILLIS = 75;

  /**
   * How long to wait when determining that a thread is blocked if we DON'T expect it to be blocked.
   */
  private static final long UNEXPECTED_HANG_DELAY_MILLIS = 10000;

  /**
   * Various scenarios to be generated for each method under test. The actual scenario generation
   * (determining which scenarios are applicable to which methods and what the outcome should be)
   * takes place in {@link #addTests(TestSuite, Method)}.
   */
  private enum Scenario {
    SATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING,
    UNSATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING,
    SATISFIED_AND_OCCUPIED_BEFORE_ENTERING,
    SATISFIED_UNOCCUPIED_AND_INTERRUPTED_BEFORE_ENTERING,

    SATISFIED_BEFORE_WAITING,
    SATISFIED_WHILE_WAITING,
    SATISFIED_AND_INTERRUPTED_BEFORE_WAITING,
    UNSATISFIED_BEFORE_AND_WHILE_WAITING,
    UNSATISFIED_AND_INTERRUPTED_BEFORE_WAITING;

    @Override
    public String toString() {
      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());
    }
  }

  /** Timeout values to combine with each {@link Scenario}. */
  private enum Timeout {
    MIN(Long.MIN_VALUE, "-oo"),
    MINUS_SMALL(-SMALL_TIMEOUT_MILLIS, "-" + SMALL_TIMEOUT_MILLIS + "ms"),
    ZERO(0L, "0ms"),
    SMALL(SMALL_TIMEOUT_MILLIS, SMALL_TIMEOUT_MILLIS + "ms"),
    LARGE(UNEXPECTED_HANG_DELAY_MILLIS * 2, (2 * UNEXPECTED_HANG_DELAY_MILLIS) + "ms"),
    MAX(Long.MAX_VALUE, "+oo");

    final long millis;
    final String label;

    Timeout(long millis, String label) {
      this.millis = millis;
      this.label = label;
    }

    @Override
    public String toString() {
      return label;
    }
  }

  /** Convenient subsets of the {@link Timeout} enumeration for specifying scenario outcomes. */
  private enum TimeoutsToUse {
    ANY(Timeout.values()),
    PAST(Timeout.MIN, Timeout.MINUS_SMALL, Timeout.ZERO),
    FUTURE(Timeout.SMALL, Timeout.MAX),
    SMALL(Timeout.SMALL),
    FINITE(Timeout.MIN, Timeout.MINUS_SMALL, Timeout.ZERO, Timeout.SMALL),
    INFINITE(Timeout.LARGE, Timeout.MAX);

    final ImmutableList<Timeout> timeouts;

    TimeoutsToUse(Timeout... timeouts) {
      this.timeouts = ImmutableList.copyOf(timeouts);
    }
  }

  /** Possible outcomes of calling any of the methods under test. */
  private enum Outcome {

    /** The method returned normally and is either void or returned true. */
    SUCCESS,

    /** The method returned false. */
    FAILURE,

    /** The method threw an InterruptedException. */
    INTERRUPT,

    /** The method did not return or throw anything. */
    HANG;

    @Override
    public String toString() {
      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());
    }
  }

  /** Identifies all enterXxx and tryEnterXxx methods. */
  private static boolean isAnyEnter(Method method) {
    return method.getName().startsWith("enter") || method.getName().startsWith("tryEnter");
  }

  /** Identifies just tryEnterXxx methods (a subset of {@link #isAnyEnter}), which never block. */
  private static boolean isTryEnter(Method method) {
    return method.getName().startsWith("tryEnter");
  }

  /**
   * Identifies just enterIfXxx methods (a subset of {@link #isAnyEnter}), which are mostly like the
   * enterXxx methods but behave like tryEnterXxx in some scenarios.
   */
  private static boolean isEnterIf(Method method) {
    return method.getName().startsWith("enterIf");
  }

  /** Identifies all waitForXxx methods, which must be called while occupying the monitor. */
  private static boolean isWaitFor(Method method) {
    return method.getName().startsWith("waitFor");
  }

  /** Determines whether the given method takes a Guard as its first parameter. */
  private static boolean isGuarded(Method method) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    return parameterTypes.length >= 1 && parameterTypes[0] == Monitor.Guard.class;
  }

  /** Determines whether the given method takes a time and unit as its last two parameters. */
  private static boolean isTimed(Method method) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    return parameterTypes.length >= 2
        && parameterTypes[parameterTypes.length - 2] == long.class
        && parameterTypes[parameterTypes.length - 1] == TimeUnit.class;
  }

  /** Determines whether the given method returns a boolean value. */
  private static boolean isBoolean(Method method) {
    return method.getReturnType() == boolean.class;
  }

  /** Determines whether the given method can throw InterruptedException. */
  private static boolean isInterruptible(Method method) {
    return Arrays.asList(method.getExceptionTypes()).contains(InterruptedException.class);
  }

  /** Sorts the given methods primarily by name and secondarily by number of parameters. */
  private static void sortMethods(Method[] methods) {
    Arrays.sort(
        methods,
        new Comparator<Method>() {
          @Override
          public int compare(Method m1, Method m2) {
            int nameComparison = m1.getName().compareTo(m2.getName());
            if (nameComparison != 0) {
              return nameComparison;
            } else {
              return Ints.compare(m1.getParameterTypes().length, m2.getParameterTypes().length);
            }
          }
        });
  }

  /** Validates that the given method's signature meets all of our assumptions. */
  private static void validateMethod(Method method) {
    String desc = method.toString();

    assertTrue(desc, isAnyEnter(method) || isWaitFor(method));

    switch (method.getParameterTypes().length) {
      case 0:
        assertFalse(desc, isGuarded(method));
        assertFalse(desc, isTimed(method));
        break;
      case 1:
        assertTrue(desc, isGuarded(method));
        assertFalse(desc, isTimed(method));
        break;
      case 2:
        assertFalse(desc, isGuarded(method));
        assertTrue(desc, isTimed(method));
        break;
      case 3:
        assertTrue(desc, isGuarded(method));
        assertTrue(desc, isTimed(method));
        break;
      default:
        fail(desc);
    }

    if (method.getReturnType() == void.class) {
      assertFalse(desc, isBoolean(method));
    } else {
      assertTrue(desc, isBoolean(method));
    }

    switch (method.getExceptionTypes().length) {
      case 0:
        assertFalse(desc, isInterruptible(method));
        break;
      case 1:
        assertTrue(desc, isInterruptible(method));
        break;
      default:
        fail(desc);
    }

    if (isEnterIf(method)) {
      assertTrue(desc, isGuarded(method));
      assertTrue(desc, isBoolean(method));
    } else if (isTryEnter(method)) {
      assertFalse(desc, isTimed(method));
      assertTrue(desc, isBoolean(method));
      assertFalse(desc, isInterruptible(method));
    } else if (isWaitFor(method)) {
      assertTrue(desc, isGuarded(method));
      assertEquals(desc, isTimed(method), isBoolean(method));
    } else { // any other enterXxx method
      assertEquals(desc, isTimed(method), isBoolean(method));
    }
  }

  /** Generates all test cases appropriate for the given method. */
  private static void addTests(TestSuite suite, Method method) {
    if (isGuarded(method)) {
      for (boolean fair1 : new boolean[] {true, false}) {
        for (boolean fair2 : new boolean[] {true, false}) {
          suite.addTest(generateGuardWithWrongMonitorTestCase(method, fair1, fair2));
        }
      }
    }
    if (isAnyEnter(method)) {
      addTests(
          suite,
          method,
          Scenario.SATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING,
          TimeoutsToUse.ANY,
          Outcome.SUCCESS);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING,
          TimeoutsToUse.FINITE,
          isGuarded(method)
              ? (isBoolean(method) ? Outcome.FAILURE : Outcome.HANG)
              : Outcome.SUCCESS);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING,
          TimeoutsToUse.INFINITE,
          isGuarded(method)
              ? (isTryEnter(method) || isEnterIf(method) ? Outcome.FAILURE : Outcome.HANG)
              : Outcome.SUCCESS);
      addTests(
          suite,
          method,
          Scenario.SATISFIED_AND_OCCUPIED_BEFORE_ENTERING,
          TimeoutsToUse.FINITE,
          isBoolean(method) ? Outcome.FAILURE : Outcome.HANG);
      addTests(
          suite,
          method,
          Scenario.SATISFIED_AND_OCCUPIED_BEFORE_ENTERING,
          TimeoutsToUse.INFINITE,
          isGuarded(method) ? Outcome.HANG : (isTryEnter(method) ? Outcome.FAILURE : Outcome.HANG));
      addTests(
          suite,
          method,
          Scenario.SATISFIED_UNOCCUPIED_AND_INTERRUPTED_BEFORE_ENTERING,
          TimeoutsToUse.ANY,
          isInterruptible(method) ? Outcome.INTERRUPT : Outcome.SUCCESS);
    } else { // any waitForXxx method
      suite.addTest(generateWaitForWhenNotOccupyingTestCase(method, true));
      suite.addTest(generateWaitForWhenNotOccupyingTestCase(method, false));
      addTests(
          suite, method, Scenario.SATISFIED_BEFORE_WAITING, TimeoutsToUse.ANY, Outcome.SUCCESS);
      addTests(
          suite, method, Scenario.SATISFIED_WHILE_WAITING, TimeoutsToUse.INFINITE, Outcome.SUCCESS);
      addTests(
          suite, method, Scenario.SATISFIED_WHILE_WAITING, TimeoutsToUse.PAST, Outcome.FAILURE);
      addTests(
          suite,
          method,
          Scenario.SATISFIED_AND_INTERRUPTED_BEFORE_WAITING,
          TimeoutsToUse.ANY,
          Outcome.SUCCESS);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_BEFORE_AND_WHILE_WAITING,
          TimeoutsToUse.FINITE,
          Outcome.FAILURE);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_BEFORE_AND_WHILE_WAITING,
          TimeoutsToUse.INFINITE,
          Outcome.HANG);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_AND_INTERRUPTED_BEFORE_WAITING,
          TimeoutsToUse.PAST,
          // prefer responding to interrupt over timing out
          isInterruptible(method) ? Outcome.INTERRUPT : Outcome.FAILURE);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_AND_INTERRUPTED_BEFORE_WAITING,
          TimeoutsToUse.SMALL,
          isInterruptible(method) ? Outcome.INTERRUPT : Outcome.FAILURE);
      addTests(
          suite,
          method,
          Scenario.UNSATISFIED_AND_INTERRUPTED_BEFORE_WAITING,
          TimeoutsToUse.INFINITE,
          isInterruptible(method) ? Outcome.INTERRUPT : Outcome.HANG);
    }
  }

  /**
   * Generates test cases for the given combination of scenario and timeouts. For methods that take
   * an explicit timeout value, all of the given timeoutsToUse result in individual test cases. For
   * methods that do not take an explicit timeout value, a single test case is generated only if the
   * implicit timeout of that method matches the given timeoutsToUse. For example, enter() is
   * treated like enter(MAX, MILLIS) and tryEnter() is treated like enter(0, MILLIS).
   */
  private static void addTests(
      TestSuite suite,
      Method method,
      Scenario scenario,
      TimeoutsToUse timeoutsToUse,
      Outcome expectedOutcome) {
    for (boolean fair : new boolean[] {true, false}) {
      if (isTimed(method)) {
        for (Timeout timeout : timeoutsToUse.timeouts) {
          suite.addTest(new GeneratedMonitorTest(method, scenario, fair, timeout, expectedOutcome));
        }
      } else {
        Timeout implicitTimeout = (isTryEnter(method) ? Timeout.ZERO : Timeout.MAX);
        if (timeoutsToUse.timeouts.contains(implicitTimeout)) {
          suite.addTest(new GeneratedMonitorTest(method, scenario, fair, null, expectedOutcome));
        }
      }
    }
  }

  /** A guard that encapsulates a simple, mutable boolean flag. */
  static class FlagGuard extends Monitor.Guard {

    private boolean satisfied;

    protected FlagGuard(Monitor monitor) {
      super(monitor);
    }

    @Override
    public boolean isSatisfied() {
      return satisfied;
    }

    public void setSatisfied(boolean satisfied) {
      this.satisfied = satisfied;
    }
  }

  private final Method method;
  private final Scenario scenario;
  private final Timeout timeout;
  private final Outcome expectedOutcome;
  private final Monitor monitor;
  private final FlagGuard guard;
  private final CountDownLatch tearDownLatch;
  private final CountDownLatch doingCallLatch;
  private final CountDownLatch callCompletedLatch;

  private GeneratedMonitorTest(
      Method method,
      Scenario scenario,
      boolean fair,
      @Nullable Timeout timeout,
      Outcome expectedOutcome) {
    super(nameFor(method, scenario, fair, timeout, expectedOutcome));
    this.method = method;
    this.scenario = scenario;
    this.timeout = timeout;
    this.expectedOutcome = expectedOutcome;
    this.monitor = new Monitor(fair);
    this.guard = new FlagGuard(monitor);
    this.tearDownLatch = new CountDownLatch(1);
    this.doingCallLatch = new CountDownLatch(1);
    this.callCompletedLatch = new CountDownLatch(1);
  }

  private static String nameFor(
      Method method, Scenario scenario, boolean fair, Timeout timeout, Outcome expectedOutcome) {
    return String.format(
        Locale.ROOT,
        "%s%s(%s)/%s->%s",
        method.getName(),
        fair ? "(fair)" : "(nonfair)",
        (timeout == null) ? "untimed" : timeout,
        scenario,
        expectedOutcome);
  }

  @Override
  protected void runTest() throws Throwable {
    final Runnable runChosenTest =
        new Runnable() {
          @Override
          public void run() {
            runChosenTest();
          }
        };
    final FutureTask<@Nullable Void> task = new FutureTask<>(runChosenTest, null);
    startThread(
        new Runnable() {
          @Override
          public void run() {
            task.run();
          }
        });
    awaitUninterruptibly(doingCallLatch);
    long hangDelayMillis =
        (expectedOutcome == Outcome.HANG)
            ? EXPECTED_HANG_DELAY_MILLIS
            : UNEXPECTED_HANG_DELAY_MILLIS;
    boolean hung =
        !awaitUninterruptibly(callCompletedLatch, hangDelayMillis, TimeUnit.MILLISECONDS);
    if (hung) {
      assertEquals(expectedOutcome, Outcome.HANG);
    } else {
      assertNull(task.get(UNEXPECTED_HANG_DELAY_MILLIS, TimeUnit.MILLISECONDS));
    }
  }

  @Override
  protected void tearDown() throws Exception {
    // We don't want to leave stray threads running after each test. At this point, every thread
    // launched by this test is either:
    //
    // (a) Blocked attempting to enter the monitor.
    // (b) Waiting for the single guard to become satisfied.
    // (c) Occupying the monitor and awaiting the tearDownLatch.
    //
    // Except for (c), every thread should occupy the monitor very briefly, and every thread leaves
    // the monitor with the guard satisfied. Therefore as soon as tearDownLatch is triggered, we
    // should be able to enter the monitor, and then we set the guard to satisfied for the benefit
    // of any remaining waiting threads.

    tearDownLatch.countDown();
    assertTrue(
        "Monitor still occupied in tearDown()",
        monitor.enter(UNEXPECTED_HANG_DELAY_MILLIS, TimeUnit.MILLISECONDS));
    try {
      guard.setSatisfied(true);
    } finally {
      monitor.leave();
    }
  }

  private void runChosenTest() {
    if (isAnyEnter(method)) {
      runEnterTest();
    } else {
      runWaitTest();
    }
  }

  private void runEnterTest() {
    assertFalse(Thread.currentThread().isInterrupted());
    assertFalse(monitor.isOccupiedByCurrentThread());

    doEnterScenarioSetUp();

    boolean interruptedBeforeCall = Thread.currentThread().isInterrupted();
    Outcome actualOutcome = doCall();
    boolean occupiedAfterCall = monitor.isOccupiedByCurrentThread();
    boolean interruptedAfterCall = Thread.currentThread().isInterrupted();

    if (occupiedAfterCall) {
      guard.setSatisfied(true);
      monitor.leave();
      assertFalse(monitor.isOccupiedByCurrentThread());
    }

    assertEquals(expectedOutcome, actualOutcome);
    assertEquals(expectedOutcome == Outcome.SUCCESS, occupiedAfterCall);
    assertEquals(
        interruptedBeforeCall && expectedOutcome != Outcome.INTERRUPT, interruptedAfterCall);
  }

  private void doEnterScenarioSetUp() {
    switch (scenario) {
      case SATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING:
        enterSatisfyGuardAndLeaveInCurrentThread();
        break;
      case UNSATISFIED_AND_UNOCCUPIED_BEFORE_ENTERING:
        break;
      case SATISFIED_AND_OCCUPIED_BEFORE_ENTERING:
        enterSatisfyGuardAndLeaveInCurrentThread();
        enterAndRemainOccupyingInAnotherThread();
        break;
      case SATISFIED_UNOCCUPIED_AND_INTERRUPTED_BEFORE_ENTERING:
        enterSatisfyGuardAndLeaveInCurrentThread();
        Thread.currentThread().interrupt();
        break;
      default:
        throw new AssertionError("unsupported scenario: " + scenario);
    }
  }

  private void runWaitTest() {
    assertFalse(Thread.currentThread().isInterrupted());
    assertFalse(monitor.isOccupiedByCurrentThread());
    monitor.enter();
    try {
      assertTrue(monitor.isOccupiedByCurrentThread());

      doWaitScenarioSetUp();

      boolean interruptedBeforeCall = Thread.currentThread().isInterrupted();
      Outcome actualOutcome = doCall();
      boolean occupiedAfterCall = monitor.isOccupiedByCurrentThread();
      boolean interruptedAfterCall = Thread.currentThread().isInterrupted();

      assertEquals(expectedOutcome, actualOutcome);
      assertTrue(occupiedAfterCall);
      assertEquals(
          interruptedBeforeCall && expectedOutcome != Outcome.INTERRUPT, interruptedAfterCall);
    } finally {
      guard.setSatisfied(true);
      monitor.leave();
      assertFalse(monitor.isOccupiedByCurrentThread());
    }
  }

  private void doWaitScenarioSetUp() {
    switch (scenario) {
      case SATISFIED_BEFORE_WAITING:
        guard.setSatisfied(true);
        break;
      case SATISFIED_WHILE_WAITING:
        guard.setSatisfied(false);
        enterSatisfyGuardAndLeaveInAnotherThread(); // enter blocks until we call waitFor
        break;
      case UNSATISFIED_BEFORE_AND_WHILE_WAITING:
        guard.setSatisfied(false);
        break;
      case SATISFIED_AND_INTERRUPTED_BEFORE_WAITING:
        guard.setSatisfied(true);
        Thread.currentThread().interrupt();
        break;
      case UNSATISFIED_AND_INTERRUPTED_BEFORE_WAITING:
        guard.setSatisfied(false);
        Thread.currentThread().interrupt();
        break;
      default:
        throw new AssertionError("unsupported scenario: " + scenario);
    }
  }

  private Outcome doCall() {
    boolean guarded = isGuarded(method);
    boolean timed = isTimed(method);
    Object[] arguments = new Object[(guarded ? 1 : 0) + (timed ? 2 : 0)];
    if (guarded) {
      arguments[0] = guard;
    }
    if (timed) {
      arguments[arguments.length - 2] = timeout.millis;
      arguments[arguments.length - 1] = TimeUnit.MILLISECONDS;
    }
    try {
      Object result;
      doingCallLatch.countDown();
      try {
        result = method.invoke(monitor, arguments);
      } finally {
        callCompletedLatch.countDown();
      }
      if (result == null) {
        return Outcome.SUCCESS;
      } else if ((Boolean) result) {
        return Outcome.SUCCESS;
      } else {
        return Outcome.FAILURE;
      }
    } catch (InvocationTargetException targetException) {
      Throwable actualException = targetException.getTargetException();
      if (actualException instanceof InterruptedException) {
        return Outcome.INTERRUPT;
      } else {
        throw newAssertionError("unexpected exception", targetException);
      }
    } catch (IllegalAccessException e) {
      throw newAssertionError("unexpected exception", e);
    }
  }

  private void enterSatisfyGuardAndLeaveInCurrentThread() {
    monitor.enter();
    try {
      guard.setSatisfied(true);
    } finally {
      monitor.leave();
    }
  }

  private void enterSatisfyGuardAndLeaveInAnotherThread() {
    final CountDownLatch startedLatch = new CountDownLatch(1);
    startThread(
        new Runnable() {
          @Override
          public void run() {
            startedLatch.countDown();
            enterSatisfyGuardAndLeaveInCurrentThread();
          }
        });
    awaitUninterruptibly(startedLatch);
  }

  private void enterAndRemainOccupyingInAnotherThread() {
    final CountDownLatch enteredLatch = new CountDownLatch(1);
    startThread(
        new Runnable() {
          @Override
          public void run() {
            monitor.enter();
            try {
              enteredLatch.countDown();
              awaitUninterruptibly(tearDownLatch);
              guard.setSatisfied(true);
            } finally {
              monitor.leave();
            }
          }
        });
    awaitUninterruptibly(enteredLatch);
  }

  @CanIgnoreReturnValue
  static Thread startThread(Runnable runnable) {
    Thread thread = new Thread(runnable);
    thread.setDaemon(true);
    thread.start();
    return thread;
  }

  /**
   * Generates a test case verifying that calling any enterXxx, tryEnterXxx, or waitForXxx method
   * with a guard that doesn't match the monitor produces an IllegalMonitorStateException.
   */
  private static TestCase generateGuardWithWrongMonitorTestCase(
      final Method method, final boolean fair1, final boolean fair2) {
    final boolean timed = isTimed(method); // Not going to bother with all timeouts, just 0ms.
    return new TestCase(method.getName() + (timed ? "(0ms)" : "()") + "/WrongMonitor->IMSE") {
      @Override
      protected void runTest() throws Throwable {
        Monitor monitor1 = new Monitor(fair1);
        Monitor monitor2 = new Monitor(fair2);
        FlagGuard guard = new FlagGuard(monitor2);
        Object[] arguments =
            (timed ? new Object[] {guard, 0L, TimeUnit.MILLISECONDS} : new Object[] {guard});
        boolean occupyMonitor = isWaitFor(method);
        if (occupyMonitor) {
          // If we don't already occupy the monitor, we'll get an IMSE regardless of the guard (see
          // generateWaitForWhenNotOccupyingTestCase).
          monitor1.enter();
        }
        try {
          method.invoke(monitor1, arguments);
          fail("expected IllegalMonitorStateException");
        } catch (InvocationTargetException e) {
          assertEquals(IllegalMonitorStateException.class, e.getTargetException().getClass());
        } finally {
          if (occupyMonitor) {
            monitor1.leave();
          }
        }
      }
    };
  }

  /**
   * Generates a test case verifying that calling any waitForXxx method when not occupying the
   * monitor produces an IllegalMonitorStateException.
   */
  private static TestCase generateWaitForWhenNotOccupyingTestCase(
      final Method method, final boolean fair) {
    final boolean timed = isTimed(method); // Not going to bother with all timeouts, just 0ms.
    String testName =
        method.getName()
            + (fair ? "(fair)" : "(nonfair)")
            + (timed ? "(0ms)" : "()")
            + "/NotOccupying->IMSE";
    return new TestCase(testName) {
      @Override
      protected void runTest() throws Throwable {
        Monitor monitor = new Monitor(fair);
        FlagGuard guard = new FlagGuard(monitor);
        Object[] arguments =
            (timed ? new Object[] {guard, 0L, TimeUnit.MILLISECONDS} : new Object[] {guard});
        try {
          method.invoke(monitor, arguments);
          fail("expected IllegalMonitorStateException");
        } catch (InvocationTargetException e) {
          assertEquals(IllegalMonitorStateException.class, e.getTargetException().getClass());
        }
      }
    };
  }

  /** Alternative to AssertionError(String, Throwable), which doesn't exist in Java 1.6 */
  private static AssertionError newAssertionError(String message, Throwable cause) {
    AssertionError e = new AssertionError(message);
    e.initCause(cause);
    return e;
  }
}