Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 89ba6d434579cd5b51e98e833e7ec1f7b328fea4 (plain) (blame)
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
/*
 * Copyright (c) 2007-2013 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util.tests;

import org.eclipse.net4j.internal.util.test.TestExecuter;
import org.eclipse.net4j.tests.bundle.OM;
import org.eclipse.net4j.util.ReflectUtil;
import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
import org.eclipse.net4j.util.concurrent.TrackableTimerTask;
import org.eclipse.net4j.util.event.EventUtil;
import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.io.IORuntimeException;
import org.eclipse.net4j.util.io.IOUtil;
import org.eclipse.net4j.util.io.TMPUtil;
import org.eclipse.net4j.util.lifecycle.ILifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.OMPlatform;
import org.eclipse.net4j.util.om.log.FileLogHandler;
import org.eclipse.net4j.util.om.log.OMLogger;
import org.eclipse.net4j.util.om.log.OMLogger.Level;
import org.eclipse.net4j.util.om.log.PrintLogHandler;
import org.eclipse.net4j.util.om.trace.ContextTracer;
import org.eclipse.net4j.util.om.trace.PrintTraceHandler;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.junit.Assert;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import junit.framework.TestResult;

/**
 * @author Eike Stepper
 */
public abstract class AbstractOMTest extends TestCase
{
  public static final long DEFAULT_TIMEOUT = 15 * 1000;

  public static final long DEFAULT_TIMEOUT_EXPECTED = 3 * 1000;

  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, AbstractOMTest.class);

  public static boolean EXTERNAL_LOG;

  public static boolean SUPPRESS_OUTPUT;

  private static boolean consoleEnabled;

  private static String testName;

  private transient List<File> filesToDelete = new ArrayList<File>();

  private transient String codeLink;

  static
  {
    try
    {
      if (EXTERNAL_LOG)
      {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String prefix = AbstractOMTest.class.getName() + "-" + formatter.format(new Date()) + "-";
        File logFile = TMPUtil.createTempFile(prefix, ".log");

        OMPlatform.INSTANCE.addLogHandler(new FileLogHandler(logFile, OMLogger.Level.WARN)
        {
          @Override
          protected void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable
          {
            super.writeLog(logger, level, "--> " + testName + "\n" + msg, t);
          }
        });

        IOUtil.ERR().println("Logging errors and warnings to " + logFile);
        IOUtil.ERR().println();
      }
    }
    catch (Throwable ex)
    {
      IOUtil.print(ex);
    }
  }

  protected AbstractOMTest()
  {
  }

  public String getCodeLink()
  {
    return codeLink;
  }

  public void determineCodeLink()
  {
    if (codeLink == null)
    {
      codeLink = determineCodeLink(getName());
      if (codeLink == null)
      {
        codeLink = determineCodeLink("doSetUp");
        if (codeLink == null)
        {
          codeLink = getClass().getName() + "." + getName() + "(" + getClass().getSimpleName() + ".java:1)";
        }
      }
    }
  }

  protected String determineCodeLink(String methodName)
  {
    String className = getClass().getName();
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    for (StackTraceElement frame : stackTrace)
    {
      if (frame.getClassName().equals(className) && frame.getMethodName().equals(methodName))
      {
        return frame.toString();
      }
    }

    return null;
  }

  @Override
  public void setUp() throws Exception
  {
    testName = getClass().getName() + "." + getName() + "()";
    codeLink = null;

    PrintTraceHandler.CONSOLE.setShortContext(true);
    OMPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE);
    OMPlatform.INSTANCE.addLogHandler(PrintLogHandler.CONSOLE);
    enableConsole();

    if (!SUPPRESS_OUTPUT)
    {
      IOUtil.OUT().println("*******************************************************"); //$NON-NLS-1$
      Thread.yield();
      Thread.sleep(2L);
      IOUtil.ERR().println(this);
      Thread.yield();
      Thread.sleep(2L);
      IOUtil.OUT().println("*******************************************************"); //$NON-NLS-1$
    }

    super.setUp();
    doSetUp();

    if (!SUPPRESS_OUTPUT)
    {
      IOUtil.OUT().println();
      IOUtil.OUT().println("------------------------ START ------------------------"); //$NON-NLS-1$
    }
  }

  @Override
  public void tearDown() throws Exception
  {
    enableConsole();
    if (!SUPPRESS_OUTPUT)
    {
      IOUtil.OUT().println("------------------------- END -------------------------"); //$NON-NLS-1$
      IOUtil.OUT().println();
    }

    try
    {
      doTearDown();
    }
    catch (Exception ex)
    {
      IOUtil.print(ex);
    }

    try
    {
      super.tearDown();
    }
    catch (Exception ex)
    {
      IOUtil.print(ex);
    }

    try
    {
      TrackableTimerTask.logConstructionStackTraces(2 * DEFAULT_TIMEOUT);
    }
    catch (Exception ex)
    {
      IOUtil.print(ex);
    }

    try
    {
      clearReferences(getClass());
    }
    catch (Exception ex)
    {
      IOUtil.print(ex);
    }

    if (!SUPPRESS_OUTPUT)
    {
      IOUtil.OUT().println();
      IOUtil.OUT().println();
    }
  }

  protected void clearReferences(Class<?> c)
  {
    if (c != AbstractOMTest.class)
    {
      for (Field field : c.getDeclaredFields())
      {
        if (Modifier.isStatic(field.getModifiers()))
        {
          continue;
        }

        if (field.getType().isPrimitive())
        {
          continue;
        }

        ReflectUtil.setValue(field, this, null);
      }

      clearReferences(c.getSuperclass());
    }
  }

  @Override
  public void runBare() throws Throwable
  {
    TestExecuter.execute(this, new TestExecuter.Executable()
    {
      public void execute() throws Throwable
      {
        try
        {
          Throwable exception = null;

          try
          {
            setUp();

            // Don't call super.runBare() because it does not clean up after exceptions from setUp()
            runTest();
          }
          catch (Throwable running)
          {
            exception = running;
          }
          finally
          {
            try
            {
              tearDown();
            }
            catch (Throwable tearingDown)
            {
              if (exception == null)
              {
                exception = tearingDown;
              }
            }
          }

          if (exception != null)
          {
            throw exception;
          }
        }
        catch (SkipTestException ex)
        {
          OM.LOG.info("Skipped " + this); //$NON-NLS-1$
        }
        catch (Throwable t)
        {
          if (!SUPPRESS_OUTPUT)
          {
            t.printStackTrace(IOUtil.OUT());
          }

          throw t;
        }
      }
    });
  }

  @Override
  public void run(TestResult result)
  {
    try
    {
      super.run(result);
    }
    catch (SkipTestException ex)
    {
      OM.LOG.info("Skipped " + this); //$NON-NLS-1$
    }
    catch (RuntimeException ex)
    {
      if (!SUPPRESS_OUTPUT)
      {
        ex.printStackTrace(IOUtil.OUT());
      }

      throw ex;
    }
    catch (Error err)
    {
      if (!SUPPRESS_OUTPUT)
      {
        err.printStackTrace(IOUtil.OUT());
      }

      throw err;
    }
  }

  protected void enableConsole()
  {
    if (!SUPPRESS_OUTPUT)
    {
      OMPlatform.INSTANCE.setDebugging(true);
      consoleEnabled = true;
    }
  }

  protected void disableConsole()
  {
    if (!SUPPRESS_OUTPUT)
    {
      consoleEnabled = false;
      OMPlatform.INSTANCE.setDebugging(false);
      // OMPlatform.INSTANCE.removeTraceHandler(PrintTraceHandler.CONSOLE);
      // OMPlatform.INSTANCE.removeLogHandler(PrintLogHandler.CONSOLE);
    }
  }

  protected void doSetUp() throws Exception
  {
  }

  protected void doTearDown() throws Exception
  {
    deleteFiles();
  }

  public void deleteFiles()
  {
    for (File file : filesToDelete)
    {
      IOUtil.delete(file);
    }

    filesToDelete.clear();
  }

  public void addFileToDelete(File file)
  {
    filesToDelete.add(file);
  }

  public File createTempFolder() throws IORuntimeException
  {
    File folder = TMPUtil.createTempFolder();
    addFileToDelete(folder);
    return folder;
  }

  public File createTempFolder(String prefix) throws IORuntimeException
  {
    File folder = TMPUtil.createTempFolder(prefix);
    addFileToDelete(folder);
    return folder;
  }

  public File createTempFolder(String prefix, String suffix) throws IORuntimeException
  {
    File folder = TMPUtil.createTempFolder(prefix, suffix);
    addFileToDelete(folder);
    return folder;
  }

  public File createTempFolder(String prefix, String suffix, File directory) throws IORuntimeException
  {
    File folder = TMPUtil.createTempFile(prefix, suffix, directory);
    addFileToDelete(folder);
    return folder;
  }

  public File createTempFile() throws IORuntimeException
  {
    File file = TMPUtil.createTempFile();
    addFileToDelete(file);
    return file;
  }

  public File createTempFile(String prefix) throws IORuntimeException
  {
    File file = TMPUtil.createTempFile(prefix);
    addFileToDelete(file);
    return file;
  }

  public File createTempFile(String prefix, String suffix) throws IORuntimeException
  {
    File file = TMPUtil.createTempFile(prefix, suffix);
    addFileToDelete(file);
    return file;
  }

  public File createTempFile(String prefix, String suffix, File directory) throws IORuntimeException
  {
    File file = TMPUtil.createTempFile(prefix, suffix, directory);
    addFileToDelete(file);
    return file;
  }

  public static AbstractOMTest getCurrrentTest()
  {
    return (AbstractOMTest)TestExecuter.getValue();
  }

  /**
   * @deprecated Use assertEquals(message, true, ...)
   */
  @Deprecated
  public static void assertTrue(String message, boolean condition)
  {
    throw new UnsupportedOperationException("Use assertEquals(message, true, ...)");
  }

  /**
   * @deprecated Use assertEquals(true, ...)
   */
  @Deprecated
  public static void assertTrue(boolean condition)
  {
    throw new UnsupportedOperationException("Use assertEquals(true, ...)");
  }

  /**
   * @deprecated Use assertEquals(message, false, ...)
   */
  @Deprecated
  public static void assertFalse(String message, boolean condition)
  {
    throw new UnsupportedOperationException("Use assertEquals(message, false, ...)");
  }

  /**
   * @deprecated Use assertEquals(false, ...)
   */
  @Deprecated
  public static void assertFalse(boolean condition)
  {
    throw new UnsupportedOperationException("Use assertEquals(false, ...)");
  }

  public static void assertEquals(Object[] expected, Object[] actual)
  {
    if (!Arrays.deepEquals(expected, actual))
    {
      throw new AssertionFailedError("expected:" + Arrays.deepToString(expected) + " but was:"
          + Arrays.deepToString(actual));
    }
  }

  public static void assertEquals(Object expected, Object actual)
  {
    if (actual == expected)
    {
      return;
    }

    Assert.assertEquals(expected, actual);
  }

  public static void assertEquals(String message, Object expected, Object actual)
  {
    if (expected == null && actual == null)
    {
      return;
    }

    if (expected != null && expected.equals(actual))
    {
      return;
    }

    // IMPORTANT: Give possible CDOLegacyWrapper a chance for actual, too
    if (actual != null && actual.equals(expected))
    {
      return;
    }

    failNotEquals(message, expected, actual);
  }

  public static void sleep(long millis)
  {
    msg("Sleeping " + millis);
    ConcurrencyUtil.sleep(millis);
  }

  public static void assertInstanceOf(Class<?> expected, Object object)
  {
    assertEquals("Not an instance of " + expected + ": " + object.getClass().getName(), true,
        expected.isInstance(object));
  }

  public static void assertNotInstanceOf(Class<?> expected, Object object)
  {
    assertEquals("An instance of " + expected + ": " + object.getClass().getName(), false, expected.isInstance(object));
  }

  public static void assertActive(Object object) throws InterruptedException
  {
    final LatchTimeOuter timeOuter = new LatchTimeOuter();
    IListener listener = new LifecycleEventAdapter()
    {
      @Override
      protected void onActivated(ILifecycle lifecycle)
      {
        timeOuter.countDown();
      }
    };

    EventUtil.addListener(object, listener);

    try
    {
      if (LifecycleUtil.isActive(object))
      {
        timeOuter.countDown();
      }

      timeOuter.assertNoTimeOut();
    }
    finally
    {
      EventUtil.removeListener(object, listener);
    }
  }

  public static void assertInactive(Object object) throws InterruptedException
  {
    final LatchTimeOuter timeOuter = new LatchTimeOuter();
    IListener listener = new LifecycleEventAdapter()
    {
      @Override
      protected void onDeactivated(ILifecycle lifecycle)
      {
        timeOuter.countDown();
      }
    };

    EventUtil.addListener(object, listener);

    try
    {
      if (!LifecycleUtil.isActive(object))
      {
        timeOuter.countDown();
      }

      timeOuter.assertNoTimeOut();
    }
    finally
    {
      EventUtil.removeListener(object, listener);
    }
  }

  public static void assertSimilar(double expected, double actual, int precision)
  {
    final double factor = 10 * precision;
    if (Math.round(expected * factor) != Math.round(actual * factor))
    {
      assertEquals(expected, actual);
    }
  }

  public static void assertSimilar(float expected, float actual, int precision)
  {
    final float factor = 10 * precision;
    if (Math.round(expected * factor) != Math.round(actual * factor))
    {
      assertEquals(expected, actual);
    }
  }

  protected static void msg(Object m)
  {
    if (!SUPPRESS_OUTPUT)
    {
      if (consoleEnabled && TRACER.isEnabled())
      {
        TRACER.trace("--> " + m); //$NON-NLS-1$
      }
    }
  }

  protected static void skipTest(boolean skip)
  {
    if (skip)
    {
      throw new SkipTestException();
    }
  }

  protected static void skipTest()
  {
    skipTest(true);
  }

  /**
   * @author Eike Stepper
   */
  private static final class SkipTestException extends RuntimeException
  {
    private static final long serialVersionUID = 1L;
  }

  /**
   * @author Eike Stepper
   */
  public static class AsyncResult<T>
  {
    private volatile T value;

    private CountDownLatch latch = new CountDownLatch(1);

    public AsyncResult()
    {
    }

    public void setValue(T value)
    {
      this.value = value;
      latch.countDown();
    }

    public T getValue(long timeout) throws Exception
    {
      if (!latch.await(timeout, TimeUnit.MILLISECONDS))
      {
        throw new TimeoutException("Result value not available after " + timeout + " milli seconds");
      }

      return value;
    }

    public T getValue() throws Exception
    {
      return getValue(DEFAULT_TIMEOUT);
    }
  }

  /**
   * @author Eike Stepper
   */
  public static interface ITimeOuter
  {
    public boolean timedOut(long timeoutMillis) throws InterruptedException;
  }

  /**
   * @author Eike Stepper
   */
  public static abstract class TimeOuter implements ITimeOuter
  {
    public boolean timedOut() throws InterruptedException
    {
      return timedOut(DEFAULT_TIMEOUT);
    }

    public void assertTimeOut(long timeoutMillis) throws InterruptedException
    {
      assertEquals("Timeout expected", true, timedOut(timeoutMillis));
    }

    public void assertTimeOut() throws InterruptedException
    {
      assertTimeOut(DEFAULT_TIMEOUT_EXPECTED);
    }

    public void assertNoTimeOut(long timeoutMillis) throws InterruptedException
    {
      assertEquals("Timeout after " + timeoutMillis + " millis", false, timedOut(timeoutMillis));
    }

    public void assertNoTimeOut() throws InterruptedException
    {
      assertNoTimeOut(DEFAULT_TIMEOUT);
    }
  }

  /**
   * @author Eike Stepper
   */
  public static abstract class PollingTimeOuter extends TimeOuter
  {
    public static final long DEFAULT_SLEEP_MILLIS = 1;

    private long sleepMillis = DEFAULT_SLEEP_MILLIS;

    public PollingTimeOuter(long sleepMillis)
    {
      this.sleepMillis = sleepMillis;
    }

    public PollingTimeOuter()
    {
    }

    public boolean timedOut(long timeoutMillis) throws InterruptedException
    {
      int retries = (int)Math.round(timeoutMillis / sleepMillis + .5d);
      for (int i = 0; i < retries; i++)
      {
        if (successful())
        {
          return false;
        }

        sleep(sleepMillis);
      }

      return true;
    }

    protected abstract boolean successful();
  }

  /**
   * @author Eike Stepper
   */
  public static class LockTimeOuter extends TimeOuter
  {
    private Lock lock;

    public LockTimeOuter(Lock lock)
    {
      this.lock = lock;
    }

    public Lock getLock()
    {
      return lock;
    }

    public boolean timedOut(long timeoutMillis) throws InterruptedException
    {
      Condition condition = lock.newCondition();
      return !condition.await(timeoutMillis, TimeUnit.MILLISECONDS);
    }
  }

  /**
   * @author Eike Stepper
   */
  public static class LatchTimeOuter extends TimeOuter
  {
    private CountDownLatch latch;

    public LatchTimeOuter(CountDownLatch latch)
    {
      this.latch = latch;
    }

    public LatchTimeOuter(int count)
    {
      this(new CountDownLatch(count));
    }

    public LatchTimeOuter()
    {
      this(1);
    }

    public CountDownLatch getLatch()
    {
      return latch;
    }

    public long getCount()
    {
      return latch.getCount();
    }

    public void countDown()
    {
      latch.countDown();
    }

    public void countDown(int n)
    {
      for (int i = 0; i < n; i++)
      {
        countDown();
      }
    }

    public boolean timedOut(long timeoutMillis) throws InterruptedException
    {
      return !latch.await(timeoutMillis, TimeUnit.MILLISECONDS);
    }
  }
}

Back to the top