org.apache.lucene.util
Class LuceneTestCase

java.lang.Object
  extended by org.junit.Assert
      extended by org.apache.lucene.util.LuceneTestCase
Direct Known Subclasses:
BaseDocValuesFormatTestCase, BasePostingsFormatTestCase, BaseTermVectorsFormatTestCase, BaseTokenStreamTestCase, CollationTestBase, SearchEquivalenceTestBase, ShardSearchingTestBase, ThreadedIndexingAndSearchingTestCase

@TestMethodProviders(value={LuceneJUnit3MethodProvider.class,com.carrotsearch.randomizedtesting.JUnit4MethodProvider.class})
@Listeners(value=RunListenerPrintReproduceInfo.class)
@SeedDecorators(value=com.carrotsearch.randomizedtesting.MixWithSuiteName.class)
public abstract class LuceneTestCase
extends Assert

Base class for all Lucene unit tests, Junit3 or Junit4 variant.

Class and instance setup.

The preferred way to specify class (suite-level) setup/cleanup is to use static methods annotated with BeforeClass and AfterClass. Any code in these methods is executed within the test framework's control and ensure proper setup has been made. Try not to use static initializers (including complex final field initializers). Static initializers are executed before any setup rules are fired and may cause you (or somebody else) headaches.

For instance-level setup, use Before and After annotated methods. If you override either setUp() or tearDown() in your subclass, make sure you call super.setUp() and super.tearDown(). This is detected and enforced.

Specifying test cases

Any test method with a testXXX prefix is considered a test case. Any test method annotated with Test is considered a test case.

Randomized execution and test facilities

LuceneTestCase uses RandomizedRunner to execute test cases. RandomizedRunner has built-in support for tests randomization including access to a repeatable Random instance. See random() method. Any test using Random acquired from random() should be fully reproducible (assuming no race conditions between threads etc.). The initial seed for a test case is reported in many ways:

There is a number of other facilities tests can use, like:


Nested Class Summary
static interface LuceneTestCase.AwaitsFix
          Annotation for tests which exhibit a known issue and are temporarily disabled.
static interface LuceneTestCase.BadApple
          Annotation for tests that fail frequently and should be moved to a "vault" plan in Jenkins.
static interface LuceneTestCase.Nightly
          Annotation for tests that should only be run during nightly builds.
static interface LuceneTestCase.Slow
          Annotation for tests that are slow.
static interface LuceneTestCase.SuppressCodecs
          Annotation for test classes that should avoid certain codec types (because they are expensive, for example).
static interface LuceneTestCase.Weekly
          Annotation for tests that should only be run during weekly builds
 
Field Summary
static org.junit.rules.TestRule classRules
          This controls how suite-level rules are nested.
static String DEFAULT_LINE_DOCS_FILE
          TODO: javadoc?
protected static Set<String> doesntSupportOffsets
           
static boolean INFOSTREAM
          TODO: javadoc?
static String JENKINS_LARGE_LINE_DOCS_FILE
          TODO: javadoc?
static boolean PREFLEX_IMPERSONATION_IS_ACTIVE
           
static int RANDOM_MULTIPLIER
          A random multiplier which you should use when writing random tests: multiply it by the number of iterations to scale your tests (for nightly builds).
 org.junit.rules.TestRule ruleChain
          This controls how individual test rules are nested.
static TestRuleMarkFailure suiteFailureMarker
          Suite failure marker (any error in the test or suite scope).
static String SYSPROP_AWAITSFIX
           
static String SYSPROP_BADAPPLES
           
static String SYSPROP_NIGHTLY
           
static String SYSPROP_SLOW
           
static String SYSPROP_WEEKLY
           
static File TEMP_DIR
          Create indexes in this directory, optimally use a subdir, named after the test
static boolean TEST_AWAITSFIX
          Whether or not LuceneTestCase.AwaitsFix tests should run.
static String TEST_CODEC
          Gets the codec to run tests with.
static String TEST_DIRECTORY
          Gets the directory to run tests with
static String TEST_DOCVALUESFORMAT
          Gets the docValuesFormat to run tests with
static String TEST_LINE_DOCS_FILE
          the line file used by LineFileDocs
static boolean TEST_NIGHTLY
          Whether or not LuceneTestCase.Nightly tests should run.
static String TEST_POSTINGSFORMAT
          Gets the postingsFormat to run tests with.
static boolean TEST_SLOW
          Whether or not LuceneTestCase.Slow tests should run.
static MockDirectoryWrapper.Throttling TEST_THROTTLING
          Throttling, see MockDirectoryWrapper.setThrottling(Throttling).
static Version TEST_VERSION_CURRENT
          Use this constant when creating Analyzers and any other version-dependent stuff.
static boolean TEST_WEEKLY
          Whether or not LuceneTestCase.Weekly tests should run.
static boolean VERBOSE
          True if and only if tests are run in verbose mode.
 
Constructor Summary
LuceneTestCase()
           
 
Method Summary
protected static void assertSaneFieldCaches(String msg)
          Asserts that FieldCacheSanityChecker does not detect any problems with FieldCache.DEFAULT.
static
<T> Set<T>
asSet(T... args)
          Return args as a Set instance.
static void assumeFalse(String msg, boolean condition)
           
static void assumeNoException(String msg, Exception e)
           
static void assumeTrue(String msg, boolean condition)
           
static int atLeast(int i)
           
static int atLeast(Random random, int i)
          Returns a number of at least i
static
<T extends Closeable>
T
closeAfterSuite(T resource)
          Registers a Closeable resource that should be closed after the suite completes.
<T extends Closeable>
T
closeAfterTest(T resource)
          Registers a Closeable resource that should be closed after the test completes.
static boolean defaultCodecSupportsDocValues()
           
static boolean defaultCodecSupportsSortedSet()
          Returns true if the default codec supports SORTED_SET docvalues
static void dumpArray(String label, Object[] objs, PrintStream stream)
          Convenience method for logging an array.
static void dumpIterator(String label, Iterator<?> iter, PrintStream stream)
          Convenience method for logging an iterator.
protected  File getDataFile(String name)
          Gets a resource from the classpath as File.
static SegmentReader getOnlySegmentReader(DirectoryReader reader)
          Some tests expect the directory to contain a single segment, and want to do tests on that segment's reader.
static Class<?> getTestClass()
          Return the current class being tested.
 String getTestName()
          Return the name of the currently executing test case.
protected  boolean isTestThread()
          Returns true if and only if the calling thread is the primary thread executing the test case.
static Locale localeForName(String localeName)
          return a Locale object equivalent to its programmatic name
static IndexReader maybeWrapReader(IndexReader r)
          Sometimes wrap the IndexReader as slow, parallel or filter reader (or combinations of that)
static AlcoholicMergePolicy newAlcoholicMergePolicy()
           
static AlcoholicMergePolicy newAlcoholicMergePolicy(Random r, TimeZone tz)
           
static BaseDirectoryWrapper newDirectory()
          Returns a new Directory instance.
static BaseDirectoryWrapper newDirectory(Directory d)
          Returns a new Directory instance, with contents copied from the provided directory.
static BaseDirectoryWrapper newDirectory(Random r)
          Returns a new Directory instance, using the specified random.
static BaseDirectoryWrapper newDirectory(Random r, Directory d)
          Returns a new Directory instance, using the specified random with contents copied from the provided directory.
static Field newField(Random random, String name, String value, FieldType type)
           
static Field newField(String name, String value, FieldType type)
           
static BaseDirectoryWrapper newFSDirectory(File f)
          Returns a new FSDirectory instance over the given file, which must be a folder.
static BaseDirectoryWrapper newFSDirectory(File f, LockFactory lf)
          Returns a new FSDirectory instance over the given file, which must be a folder.
static IndexWriterConfig newIndexWriterConfig(Random r, Version v, Analyzer a)
          create a new index writer config with random defaults using the specified random
static IndexWriterConfig newIndexWriterConfig(Version v, Analyzer a)
          create a new index writer config with random defaults
static IOContext newIOContext(Random random)
          TODO: javadoc
static IOContext newIOContext(Random random, IOContext oldContext)
          TODO: javadoc
static LogMergePolicy newLogMergePolicy()
           
static LogMergePolicy newLogMergePolicy(boolean useCFS)
           
static LogMergePolicy newLogMergePolicy(boolean useCFS, int mergeFactor)
           
static LogMergePolicy newLogMergePolicy(int mergeFactor)
           
static LogMergePolicy newLogMergePolicy(Random r)
           
static MockDirectoryWrapper newMockDirectory()
           
static MockDirectoryWrapper newMockDirectory(Random r)
           
static MockDirectoryWrapper newMockFSDirectory(File f)
           
static IndexSearcher newSearcher(IndexReader r)
          Create a new searcher over the reader.
static IndexSearcher newSearcher(IndexReader r, boolean maybeWrap)
          Create a new searcher over the reader.
static Field newStringField(Random random, String name, String value, Field.Store stored)
           
static Field newStringField(String name, String value, Field.Store stored)
           
static Field newTextField(Random random, String name, String value, Field.Store stored)
           
static Field newTextField(String name, String value, Field.Store stored)
           
static TieredMergePolicy newTieredMergePolicy()
           
static TieredMergePolicy newTieredMergePolicy(Random r)
           
static Random random()
          Access to the current RandomizedContext's Random instance.
static Locale randomLocale(Random random)
          Return a random Locale from the available locales on the system.
static TimeZone randomTimeZone(Random random)
          Return a random TimeZone from the available timezones on the system
static boolean rarely()
           
static boolean rarely(Random random)
          Returns true if something should happen rarely,
 void setUp()
          For subclasses to override.
 void tearDown()
          For subclasses to override.
static boolean usually()
           
static boolean usually(Random random)
           
 
Methods inherited from class org.junit.Assert
assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertArrayEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertThat, assertThat, assertTrue, assertTrue, fail, fail
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SYSPROP_NIGHTLY

public static final String SYSPROP_NIGHTLY
See Also:
Constant Field Values

SYSPROP_WEEKLY

public static final String SYSPROP_WEEKLY
See Also:
Constant Field Values

SYSPROP_AWAITSFIX

public static final String SYSPROP_AWAITSFIX
See Also:
Constant Field Values

SYSPROP_SLOW

public static final String SYSPROP_SLOW
See Also:
Constant Field Values

SYSPROP_BADAPPLES

public static final String SYSPROP_BADAPPLES
See Also:
Constant Field Values

TEST_VERSION_CURRENT

public static final Version TEST_VERSION_CURRENT
Use this constant when creating Analyzers and any other version-dependent stuff.

NOTE: Change this when development starts for new Lucene version:


VERBOSE

public static final boolean VERBOSE
True if and only if tests are run in verbose mode. If this flag is false tests are not expected to print any messages.


INFOSTREAM

public static final boolean INFOSTREAM
TODO: javadoc?


RANDOM_MULTIPLIER

public static final int RANDOM_MULTIPLIER
A random multiplier which you should use when writing random tests: multiply it by the number of iterations to scale your tests (for nightly builds).


DEFAULT_LINE_DOCS_FILE

public static final String DEFAULT_LINE_DOCS_FILE
TODO: javadoc?

See Also:
Constant Field Values

JENKINS_LARGE_LINE_DOCS_FILE

public static final String JENKINS_LARGE_LINE_DOCS_FILE
TODO: javadoc?

See Also:
Constant Field Values

TEST_CODEC

public static final String TEST_CODEC
Gets the codec to run tests with.


TEST_POSTINGSFORMAT

public static final String TEST_POSTINGSFORMAT
Gets the postingsFormat to run tests with.


TEST_DOCVALUESFORMAT

public static final String TEST_DOCVALUESFORMAT
Gets the docValuesFormat to run tests with


TEST_DIRECTORY

public static final String TEST_DIRECTORY
Gets the directory to run tests with


TEST_LINE_DOCS_FILE

public static final String TEST_LINE_DOCS_FILE
the line file used by LineFileDocs


TEST_NIGHTLY

public static final boolean TEST_NIGHTLY
Whether or not LuceneTestCase.Nightly tests should run.


TEST_WEEKLY

public static final boolean TEST_WEEKLY
Whether or not LuceneTestCase.Weekly tests should run.


TEST_AWAITSFIX

public static final boolean TEST_AWAITSFIX
Whether or not LuceneTestCase.AwaitsFix tests should run.


TEST_SLOW

public static final boolean TEST_SLOW
Whether or not LuceneTestCase.Slow tests should run.


TEST_THROTTLING

public static final MockDirectoryWrapper.Throttling TEST_THROTTLING
Throttling, see MockDirectoryWrapper.setThrottling(Throttling).


TEMP_DIR

public static final File TEMP_DIR
Create indexes in this directory, optimally use a subdir, named after the test


doesntSupportOffsets

protected static final Set<String> doesntSupportOffsets

PREFLEX_IMPERSONATION_IS_ACTIVE

public static boolean PREFLEX_IMPERSONATION_IS_ACTIVE
NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.

suiteFailureMarker

public static final TestRuleMarkFailure suiteFailureMarker
Suite failure marker (any error in the test or suite scope).


classRules

public static org.junit.rules.TestRule classRules
This controls how suite-level rules are nested. It is important that _all_ rules declared in LuceneTestCase are executed in proper order if they depend on each other.


ruleChain

public final org.junit.rules.TestRule ruleChain
This controls how individual test rules are nested. It is important that _all_ rules declared in LuceneTestCase are executed in proper order if they depend on each other.

Constructor Detail

LuceneTestCase

public LuceneTestCase()
Method Detail

setUp

public void setUp()
           throws Exception
For subclasses to override. Overrides must call super.setUp().

Throws:
Exception

tearDown

public void tearDown()
              throws Exception
For subclasses to override. Overrides must call super.tearDown().

Throws:
Exception

random

public static Random random()
Access to the current RandomizedContext's Random instance. It is safe to use this method from multiple threads, etc., but it should be called while within a runner's scope (so no static initializers). The returned Random instance will be different when this method is called inside a BeforeClass hook (static suite scope) and within Before/ After hooks or test methods.

The returned instance must not be shared with other threads or cross a single scope's boundary. For example, a Random acquired within a test method shouldn't be reused for another test case.

There is an overhead connected with getting the Random for a particular context and thread. It is better to cache the Random locally if tight loops with multiple invocations are present or create a derivative local Random for millions of calls like this:

 Random random = new Random(random().nextLong());
 // tight loop with many invocations. 
 


closeAfterTest

public <T extends Closeable> T closeAfterTest(T resource)
Registers a Closeable resource that should be closed after the test completes.

Returns:
resource (for call chaining).

closeAfterSuite

public static <T extends Closeable> T closeAfterSuite(T resource)
Registers a Closeable resource that should be closed after the suite completes.

Returns:
resource (for call chaining).

getTestClass

public static Class<?> getTestClass()
Return the current class being tested.


getTestName

public String getTestName()
Return the name of the currently executing test case.


getOnlySegmentReader

public static SegmentReader getOnlySegmentReader(DirectoryReader reader)
Some tests expect the directory to contain a single segment, and want to do tests on that segment's reader. This is an utility method to help them.


isTestThread

protected boolean isTestThread()
Returns true if and only if the calling thread is the primary thread executing the test case.


assertSaneFieldCaches

protected static void assertSaneFieldCaches(String msg)
Asserts that FieldCacheSanityChecker does not detect any problems with FieldCache.DEFAULT.

If any problems are found, they are logged to System.err (allong with the msg) when the Assertion is thrown.

This method is called by tearDown after every test method, however IndexReaders scoped inside test methods may be garbage collected prior to this method being called, causing errors to be overlooked. Tests are encouraged to keep their IndexReaders scoped at the class level, or to explicitly call this method directly in the same scope as the IndexReader.

See Also:
FieldCacheSanityChecker

atLeast

public static int atLeast(Random random,
                          int i)
Returns a number of at least i

The actual number returned will be influenced by whether TEST_NIGHTLY is active and RANDOM_MULTIPLIER, but also with some random fudge.


atLeast

public static int atLeast(int i)

rarely

public static boolean rarely(Random random)
Returns true if something should happen rarely,

The actual number returned will be influenced by whether TEST_NIGHTLY is active and RANDOM_MULTIPLIER.


rarely

public static boolean rarely()

usually

public static boolean usually(Random random)

usually

public static boolean usually()

assumeTrue

public static void assumeTrue(String msg,
                              boolean condition)

assumeFalse

public static void assumeFalse(String msg,
                               boolean condition)

assumeNoException

public static void assumeNoException(String msg,
                                     Exception e)

asSet

public static <T> Set<T> asSet(T... args)
Return args as a Set instance. The order of elements is not preserved in iterators.


dumpIterator

public static void dumpIterator(String label,
                                Iterator<?> iter,
                                PrintStream stream)
Convenience method for logging an iterator.

Parameters:
label - String logged before/after the items in the iterator
iter - Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator.
stream - Stream to log messages to.

dumpArray

public static void dumpArray(String label,
                             Object[] objs,
                             PrintStream stream)
Convenience method for logging an array. Wraps the array in an iterator and delegates

See Also:
dumpIterator(String,Iterator,PrintStream)

newIndexWriterConfig

public static IndexWriterConfig newIndexWriterConfig(Version v,
                                                     Analyzer a)
create a new index writer config with random defaults


newIndexWriterConfig

public static IndexWriterConfig newIndexWriterConfig(Random r,
                                                     Version v,
                                                     Analyzer a)
create a new index writer config with random defaults using the specified random


newLogMergePolicy

public static LogMergePolicy newLogMergePolicy()

newTieredMergePolicy

public static TieredMergePolicy newTieredMergePolicy()

newAlcoholicMergePolicy

public static AlcoholicMergePolicy newAlcoholicMergePolicy()

newAlcoholicMergePolicy

public static AlcoholicMergePolicy newAlcoholicMergePolicy(Random r,
                                                           TimeZone tz)

newLogMergePolicy

public static LogMergePolicy newLogMergePolicy(Random r)

newTieredMergePolicy

public static TieredMergePolicy newTieredMergePolicy(Random r)

newLogMergePolicy

public static LogMergePolicy newLogMergePolicy(boolean useCFS)

newLogMergePolicy

public static LogMergePolicy newLogMergePolicy(boolean useCFS,
                                               int mergeFactor)

newLogMergePolicy

public static LogMergePolicy newLogMergePolicy(int mergeFactor)

newDirectory

public static BaseDirectoryWrapper newDirectory()
Returns a new Directory instance. Use this when the test does not care about the specific Directory implementation (most tests).

The Directory is wrapped with BaseDirectoryWrapper. this means usually it will be picky, such as ensuring that you properly close it and all open files in your test. It will emulate some features of Windows, such as not allowing open files to be overwritten.


newDirectory

public static BaseDirectoryWrapper newDirectory(Random r)
Returns a new Directory instance, using the specified random. See newDirectory() for more information.


newMockDirectory

public static MockDirectoryWrapper newMockDirectory()

newMockDirectory

public static MockDirectoryWrapper newMockDirectory(Random r)

newMockFSDirectory

public static MockDirectoryWrapper newMockFSDirectory(File f)

newDirectory

public static BaseDirectoryWrapper newDirectory(Directory d)
                                         throws IOException
Returns a new Directory instance, with contents copied from the provided directory. See newDirectory() for more information.

Throws:
IOException

newFSDirectory

public static BaseDirectoryWrapper newFSDirectory(File f)
Returns a new FSDirectory instance over the given file, which must be a folder.


newFSDirectory

public static BaseDirectoryWrapper newFSDirectory(File f,
                                                  LockFactory lf)
Returns a new FSDirectory instance over the given file, which must be a folder.


newDirectory

public static BaseDirectoryWrapper newDirectory(Random r,
                                                Directory d)
                                         throws IOException
Returns a new Directory instance, using the specified random with contents copied from the provided directory. See newDirectory() for more information.

Throws:
IOException

newStringField

public static Field newStringField(String name,
                                   String value,
                                   Field.Store stored)

newTextField

public static Field newTextField(String name,
                                 String value,
                                 Field.Store stored)

newStringField

public static Field newStringField(Random random,
                                   String name,
                                   String value,
                                   Field.Store stored)

newTextField

public static Field newTextField(Random random,
                                 String name,
                                 String value,
                                 Field.Store stored)

newField

public static Field newField(String name,
                             String value,
                             FieldType type)

newField

public static Field newField(Random random,
                             String name,
                             String value,
                             FieldType type)

randomLocale

public static Locale randomLocale(Random random)
Return a random Locale from the available locales on the system.

See Also:
"https://issues.apache.org/jira/browse/LUCENE-4020"

randomTimeZone

public static TimeZone randomTimeZone(Random random)
Return a random TimeZone from the available timezones on the system

See Also:
"https://issues.apache.org/jira/browse/LUCENE-4020"

localeForName

public static Locale localeForName(String localeName)
return a Locale object equivalent to its programmatic name


defaultCodecSupportsDocValues

public static boolean defaultCodecSupportsDocValues()

maybeWrapReader

public static IndexReader maybeWrapReader(IndexReader r)
                                   throws IOException
Sometimes wrap the IndexReader as slow, parallel or filter reader (or combinations of that)

Throws:
IOException

newIOContext

public static IOContext newIOContext(Random random)
TODO: javadoc


newIOContext

public static IOContext newIOContext(Random random,
                                     IOContext oldContext)
TODO: javadoc


newSearcher

public static IndexSearcher newSearcher(IndexReader r)
                                 throws IOException
Create a new searcher over the reader. This searcher might randomly use threads.

Throws:
IOException

newSearcher

public static IndexSearcher newSearcher(IndexReader r,
                                        boolean maybeWrap)
                                 throws IOException
Create a new searcher over the reader. This searcher might randomly use threads. if maybeWrap is true, this searcher might wrap the reader with one that returns null for getSequentialSubReaders.

Throws:
IOException

getDataFile

protected File getDataFile(String name)
                    throws IOException
Gets a resource from the classpath as File. This method should only be used, if a real file is needed. To get a stream, code should prefer Class.getResourceAsStream(java.lang.String) using this.getClass().

Throws:
IOException

defaultCodecSupportsSortedSet

public static boolean defaultCodecSupportsSortedSet()
Returns true if the default codec supports SORTED_SET docvalues



Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.