sis-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From desruisse...@apache.org
Subject svn commit: r1396466 - in /sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis: test/TestCase.java test/TestUtilities.java util/collection/WeakHashSetTest.java util/collection/WeakValueHashMapTest.java
Date Wed, 10 Oct 2012 04:34:14 GMT
Author: desruisseaux
Date: Wed Oct 10 04:34:14 2012
New Revision: 1396466

URL: http://svn.apache.org/viewvc?rev=1396466&view=rev
Log:
Factor out the "wait for garbage collector" code in a TestUtilities class.

Added:
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestUtilities.java
      - copied, changed from r1395068, sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java
Modified:
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakHashSetTest.java
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakValueHashMapTest.java

Modified: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java?rev=1396466&r1=1396465&r2=1396466&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java (original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java Wed Oct
10 04:34:14 2012
@@ -16,22 +16,15 @@
  */
 package org.apache.sis.test;
 
-import java.util.Date;
-import java.util.Locale;
-import java.util.TimeZone;
 import java.util.logging.Logger;
 import java.util.logging.Handler;
 import java.util.logging.ConsoleHandler;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
 import java.io.Console;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
 
-import org.apache.sis.util.ArgumentChecks;
 import org.apache.sis.util.logging.Logging;
 
 import org.junit.After;
@@ -129,54 +122,12 @@ public abstract strictfp class TestCase 
     }
 
     /**
-     * Date parser and formatter using the {@code "yyyy-MM-dd HH:mm:ss"} pattern
-     * and UTC time zone.
-     */
-    private static final DateFormat dateFormat;
-    static {
-        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA);
-        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
-        dateFormat.setLenient(false);
-    };
-
-    /**
      * Creates a new test case.
      */
     protected TestCase() {
     }
 
     /**
-     * Parses the date for the given string using the {@code "yyyy-MM-dd HH:mm:ss"} pattern
-     * in UTC timezone.
-     *
-     * @param  date The date as a {@link String}.
-     * @return The date as a {@link Date}.
-     */
-    public static Date date(final String date) {
-        ArgumentChecks.ensureNonNull("date", date);
-        try {
-            synchronized (dateFormat) {
-                return dateFormat.parse(date);
-            }
-        } catch (ParseException e) {
-            throw new AssertionError(e);
-        }
-    }
-
-    /**
-     * Formats the given date using the {@code "yyyy-MM-dd HH:mm:ss"} pattern in UTC timezone.
-     *
-     * @param  date The date to format.
-     * @return The date as a {@link String}.
-     */
-    public static String format(final Date date) {
-        ArgumentChecks.ensureNonNull("date", date);
-        synchronized (dateFormat) {
-            return dateFormat.format(date);
-        }
-    }
-
-    /**
      * If verbose output is enabled, flushes the {@link #out} stream after each test.
      * The stream will be flushed to the {@linkplain System#console() console} if
      * available, or to the {@linkplain System#out standard output stream} otherwise.

Copied: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestUtilities.java
(from r1395068, sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java)
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestUtilities.java?p2=sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestUtilities.java&p1=sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java&r1=1395068&r2=1396466&rev=1396466&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestCase.java (original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/test/TestUtilities.java Wed
Oct 10 04:34:14 2012
@@ -19,115 +19,25 @@ package org.apache.sis.test;
 import java.util.Date;
 import java.util.Locale;
 import java.util.TimeZone;
-import java.util.logging.Logger;
-import java.util.logging.Handler;
-import java.util.logging.ConsoleHandler;
+import java.util.concurrent.Callable;
 import java.text.DateFormat;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
-import java.io.Console;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-
+import org.apache.sis.util.Static;
 import org.apache.sis.util.ArgumentChecks;
-import org.apache.sis.util.logging.Logging;
-
-import org.junit.After;
-import org.junit.runner.RunWith;
 
-import static org.apache.sis.test.TestConfiguration.VERBOSE_OUTPUT_KEY;
-import static org.apache.sis.test.TestConfiguration.OUTPUT_ENCODING_KEY;
+import static org.junit.Assert.*;
 
 
 /**
- * Base class of Apache SIS tests (except the ones that extend GeoAPI tests).
- * This base class provides an {@link #out} field that sub-classes can use
- * <strong>if non-null</strong> for printing debugging information. This {@code
out}
- * field shall be used instead of {@link System#out} for the following reasons:
- *
- * <ul>
- *   <li><p>It is {@code null} by default and enabled only if a system property
is set as
- *     described in the {@linkplain org.apache.sis.test package javadoc}. This allows more
- *     quiet (and sometime faster) Maven executions for those who are not SIS developers.</p></li>
- *   <li><p>The outputs are collected and printed only after each test completion.
- *     This avoid the problem of logging messages interleaved with the output.
- *     If such interleaving is really wanted, then use the logging framework instead.</p></li>
- * </ul>
- *
- * Usage example:
- *
- * {@preformat java
- *     if (out != null) {
- *         // Performs here some potentially costly calculation to be printed.
- *         out.println("Write here some information of particular interest.");
- *     }
- * }
+ * Miscellaneous utility methods for test cases.
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3 (derived from geotk-3.16)
  * @version 0.3
  * @module
  */
-@RunWith(TestRunner.class)
-public abstract strictfp class TestCase {
-    /**
-     * If non-null, the output writer where to print debugging information.
-     * This field is non-null if the {@value org.apache.sis.test.TestConfiguration#VERBOSE_OUTPUT_KEY}
-     * system property is set to {@code true}. This writer will use the system default encoding,
unless
-     * the {@value org.apache.sis.test.TestConfiguration#OUTPUT_ENCODING_KEY} system property
has been
-     * set to a different value.
-     *
-     * @see org.apache.sis.test
-     * @see #flushVerboseOutput()
-     */
-    public static final PrintWriter out;
-
-    /**
-     * The buffer which is backing the {@linkplain #out} stream, or {@code null} if none.
-     */
-    private static final StringWriter buffer;
-
-    /**
-     * Sets the {@link #out} writer and its underlying {@link #buffer}.
-     */
-    static {
-        if (Boolean.getBoolean(VERBOSE_OUTPUT_KEY)) {
-            out = new PrintWriter(buffer = new StringWriter());
-        } else {
-            buffer = null;
-            out = null;
-        }
-    }
-
-    /**
-     * Sets the encoding of the console logging handler, if an encoding has been specified.
-     * Note that we look specifically for {@link ConsoleHandler}; we do not generalize to
-     * {@link StreamHandler} because the log files may not be intended for being show in
-     * the console.
-     * <p>
-     * In case of failure to use the given encoding, we will just print a short error
-     * message and left the encoding unchanged.
-     */
-    static {
-        final String encoding = System.getProperty(OUTPUT_ENCODING_KEY);
-        if (encoding != null) try {
-            for (Logger logger=Logger.getLogger("org.apache.sis"); logger!=null; logger=logger.getParent())
{
-                for (final Handler handler : logger.getHandlers()) {
-                    if (handler instanceof ConsoleHandler) {
-                        ((ConsoleHandler) handler).setEncoding(encoding);
-                    }
-                }
-                if (!logger.getUseParentHandlers()) {
-                    break;
-                }
-            }
-        } catch (UnsupportedEncodingException e) {
-            Logging.recoverableException(TestCase.class, "<clinit>", e);
-        }
-    }
-
+public final strictfp class TestUtilities extends Static {
     /**
      * Date parser and formatter using the {@code "yyyy-MM-dd HH:mm:ss"} pattern
      * and UTC time zone.
@@ -140,9 +50,9 @@ public abstract strictfp class TestCase 
     };
 
     /**
-     * Creates a new test case.
+     * Do not allow instantiation of this class.
      */
-    protected TestCase() {
+    private TestUtilities() {
     }
 
     /**
@@ -177,56 +87,33 @@ public abstract strictfp class TestCase 
     }
 
     /**
-     * If verbose output is enabled, flushes the {@link #out} stream after each test.
-     * The stream will be flushed to the {@linkplain System#console() console} if
-     * available, or to the {@linkplain System#out standard output stream} otherwise.
-     * <p>
-     * This method is invoked automatically by JUnit and doesn't need to be invoked
-     * explicitely, unless the developer wants to flush the output at some specific
-     * point.
-     */
-    @After
-    public void flushVerboseOutput() {
-        System.out.flush();
-        System.err.flush();
-        if (out == null) {
-            return;
-        }
-        synchronized (buffer) { // This is the lock used by the 'out' PrintWriter.
-            out.flush();
-            /*
-             * Get the text content and remove the trailing spaces
-             * (including line feeds), if any.
-             */
-            String content = buffer.toString();
-            int length = content.length();
-            do if (length == 0) return;
-            while (Character.isWhitespace(content.charAt(--length)));
-            content = content.substring(0, ++length);
-            /*
-             * Get the output writer, using the specified encoding if any.
-             */
-            PrintWriter writer = null;
-            final String encoding = System.getProperty(OUTPUT_ENCODING_KEY);
-            if (encoding == null) {
-                final Console console = System.console();
-                if (console != null) {
-                    writer = console.writer();
-                }
+     * Waits up to one second for the garbage collector to do its work. This method can be
invoked
+     * only if {@link TestConfiguration#allowGarbageCollectorDependentTests()} returns {@code
true}.
+     *
+     * @param  stopCondition A condition which return {@code true} if this method can stop
waiting,
+     *         or {@code false} if it needs to ask again for garbage collection.
+     * @return {@code true} if the given condition has been meet, or {@code false} if we
waited up
+     *         to the timeout without meeting the given condition.
+     * @throws InterruptedException If this thread has been interrupted while waiting.
+     */
+    public static boolean waitForGarbageCollection(final Callable<Boolean> stopCondition)
throws InterruptedException {
+        assertTrue("GC-dependent tests not allowed in this run.", TestConfiguration.allowGarbageCollectorDependentTests());
+        int retry = 20;
+        boolean stop;
+        do {
+            if (--retry == 0) {
+                return false;
             }
-            if (writer == null) {
-                if (encoding != null) try {
-                    writer = new PrintWriter(new OutputStreamWriter(System.out, encoding));
-                } catch (UnsupportedEncodingException e) {
-                    // Ignore. We will use the default encoding.
-                }
-                if (writer == null) {
-                    writer = new PrintWriter(System.out);
-                }
+            Thread.sleep(50);
+            System.gc();
+            try {
+                stop = stopCondition.call();
+            } catch (RuntimeException e) {
+                throw e;
+            } catch (Exception e) {
+                throw new AssertionError(e);
             }
-            writer.println(content);
-            writer.flush();
-            buffer.getBuffer().setLength(0);
-        }
+        } while (!stop);
+        return true;
     }
 }

Modified: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakHashSetTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakHashSetTest.java?rev=1396466&r1=1396465&r2=1396466&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakHashSetTest.java
(original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakHashSetTest.java
Wed Oct 10 04:34:14 2012
@@ -18,12 +18,14 @@ package org.apache.sis.util.collection;
 
 import java.util.HashSet;
 import java.util.Random;
+import java.util.concurrent.Callable;
 import org.apache.sis.test.TestCase;
 import org.apache.sis.test.DependsOnMethod;
 import org.apache.sis.test.TestConfiguration;
 import org.junit.Test;
 
 import static org.apache.sis.test.Assert.*;
+import static org.apache.sis.test.TestUtilities.waitForGarbageCollection;
 
 
 /**
@@ -150,22 +152,21 @@ public final strictfp class WeakHashSetT
              * happen too often, we may turn off the "allow garbage collector dependent tests"
flag.
              */
             if (TestConfiguration.allowGarbageCollectorDependentTests()) {
-                int retry = 4;
-                do { // Do our best to lets GC finish its work.
-                    Thread.sleep(50);
-                    System.gc();
-                } while (--retry >= 0 && weakSet.size() != strongSet.size());
+                waitForGarbageCollection(new Callable<Boolean>() {
+                    @Override public Boolean call() {
+                        return weakSet.size() == strongSet.size();
+                    }
+                });
                 assertSetEquals(strongSet, weakSet);
                 /*
                  * Clearing all strong references should make the set empty.
                  */
                 strongSet.clear();
-                retry = 4;
-                do { // Do our best to lets GC finish its work.
-                    assertTrue("Expected an empty set.", --retry >= 0);
-                    Thread.sleep(50);
-                    System.gc();
-                } while (!weakSet.isEmpty());
+                assertTrue("Expected an empty set.", waitForGarbageCollection(new Callable<Boolean>()
{
+                    @Override public Boolean call() {
+                        return weakSet.isEmpty();
+                    }
+                }));
             }
         }
     }

Modified: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakValueHashMapTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakValueHashMapTest.java?rev=1396466&r1=1396465&r2=1396466&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakValueHashMapTest.java
(original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/util/collection/WeakValueHashMapTest.java
Wed Oct 10 04:34:14 2012
@@ -18,12 +18,14 @@ package org.apache.sis.util.collection;
 
 import java.util.HashMap;
 import java.util.Random;
+import java.util.concurrent.Callable;
 import org.apache.sis.test.TestCase;
 import org.apache.sis.test.TestConfiguration;
 import org.apache.sis.test.DependsOnMethod;
 import org.junit.Test;
 
 import static org.apache.sis.test.Assert.*;
+import static org.apache.sis.test.TestUtilities.waitForGarbageCollection;
 
 
 /**
@@ -133,22 +135,21 @@ public final strictfp class WeakValueHas
              * happen too often, we may turn off the "allow garbage collector dependent tests"
flag.
              */
             if (TestConfiguration.allowGarbageCollectorDependentTests()) {
-                int retry = 4;
-                do { // Do our best to lets GC finish its work.
-                    Thread.sleep(50);
-                    System.gc();
-                } while (--retry >= 0 && weakMap.size() != strongMap.size());
+                waitForGarbageCollection(new Callable<Boolean>() {
+                    @Override public Boolean call() {
+                        return weakMap.size() == strongMap.size();
+                    }
+                });
                 assertMapEquals(strongMap, weakMap);
                 /*
                  * Clearing all strong references should make the map empty.
                  */
                 strongMap.clear();
-                retry = 4;
-                do { // Do our best to lets GC finish its work.
-                    assertTrue("Expected an empty map.", --retry >= 0);
-                    Thread.sleep(50);
-                    System.gc();
-                } while (!weakMap.isEmpty());
+                assertTrue("Expected an empty map.", waitForGarbageCollection(new Callable<Boolean>()
{
+                    @Override public Boolean call() {
+                        return weakMap.isEmpty();
+                    }
+                }));
             }
         }
     }



Mime
View raw message