Class LuceneTestCase

    • Field Detail

      • 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. Enforced with TestRuleLimitSysouts.
      • INFOSTREAM

        public static final boolean INFOSTREAM
        Enables or disables dumping of InfoStream messages.
      • 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).
      • TEST_ASSERTS_ENABLED

        public static final boolean TEST_ASSERTS_ENABLED
      • 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_MONSTER

        public static final boolean TEST_MONSTER
        Whether or not LuceneTestCase.Monster tests should run.
      • TEST_BADAPPLES

        public static final boolean TEST_BADAPPLES
        Whether or not LuceneTestCase.BadApple tests should run.
      • TEST_SLOW

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

        public static final boolean LEAVE_TEMPORARY
        Leave temporary files on disk, even on successful runs.
      • suiteFailureMarker

        protected static 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.
      • assertsAreEnabled

        public static final boolean assertsAreEnabled
        True if assertions (-ea) are enabled (at least for this class).
    • Constructor Detail

      • LuceneTestCase

        public LuceneTestCase()
    • Method Detail

      • hasWorkingMMapOnWindows

        public static boolean hasWorkingMMapOnWindows()
        Returns true, if MMapDirectory supports unmapping on this platform (required for Windows), or if we are not on Windows.
      • assumeWorkingMMapOnWindows

        public static void assumeWorkingMMapOnWindows()
        Assumes that the current MMapDirectory implementation supports unmapping, so the test will not fail on Windows.
        See Also:
        hasWorkingMMapOnWindows()
      • 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
      • setIndexWriterMaxDocs

        public void setIndexWriterMaxDocs​(int limit)
        Tells IndexWriter to enforce the specified limit as the maximum number of documents in one index; call restoreIndexWriterMaxDocs() once your test is done.
      • restoreIndexWriterMaxDocs

        public void restoreIndexWriterMaxDocs()
        Returns to the default IndexWriter.MAX_DOCS limit.
      • 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.
      • getOnlyLeafReader

        public static LeafReader getOnlyLeafReader​(IndexReader 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.
      • 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

        @SafeVarargs
        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 its own line. If iter is null this is logged differently then an empty iterator.
        stream - Stream to log messages to.
      • newIndexWriterConfig

        public static IndexWriterConfig newIndexWriterConfig()
        create a new index writer config with random defaults
      • newIndexWriterConfig

        public static IndexWriterConfig newIndexWriterConfig​(Analyzer a)
        create a new index writer config with random defaults
      • newIndexWriterConfig

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

        public static MergePolicy newMergePolicy​(Random r,
                                                 boolean includeMockMP)
      • newMergePolicy

        public static MergePolicy newMergePolicy()
      • newLogMergePolicy

        public static LogMergePolicy newLogMergePolicy()
      • newLogMergePolicy

        public static MergePolicy newLogMergePolicy​(boolean useCFS)
      • newLogMergePolicy

        public static MergePolicy newLogMergePolicy​(boolean useCFS,
                                                    int mergeFactor)
      • newLogMergePolicy

        public static MergePolicy 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.

      • addVirusChecker

        public static Path addVirusChecker​(Path path)
      • newFSDirectory

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

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

        public static Locale randomLocale​(Random random)
        Return a random Locale from the available locales on the system.
        See Also:
        LUCENE-4020
      • randomTimeZone

        public static TimeZone randomTimeZone​(Random random)
        Return a random TimeZone from the available timezones on the system
        See Also:
        LUCENE-4020
      • localeForLanguageTag

        public static Locale localeForLanguageTag​(String languageTag)
        return a Locale object equivalent to its programmatic name
      • newIOContext

        public static IOContext newIOContext​(Random random)
        TODO: javadoc
      • overrideTestDefaultQueryCache

        public void overrideTestDefaultQueryCache()
      • overrideDefaultQueryCache

        public static void overrideDefaultQueryCache()
      • resetDefaultQueryCache

        public static void resetDefaultQueryCache()
      • setupCPUCoreCount

        public static void setupCPUCoreCount()
      • restoreCPUCoreCount

        public static void restoreCPUCoreCount()
      • setupSpins

        public static void setupSpins()
      • restoreSpins

        public static void restoreSpins()
      • newSearcher

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

        public static IndexSearcher newSearcher​(IndexReader r,
                                                boolean maybeWrap)
        Create a new searcher over the reader. This searcher might randomly use threads.
      • newSearcher

        public static IndexSearcher newSearcher​(IndexReader r,
                                                boolean maybeWrap,
                                                boolean wrapWithAssertions)
        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. If wrapWithAssertions is true, this searcher might be an AssertingIndexSearcher instance.
      • assertTermsStatisticsEquals

        public void assertTermsStatisticsEquals​(String info,
                                                Terms leftTerms,
                                                Terms rightTerms)
                                         throws IOException
        checks collection-level statistics on Terms
        Throws:
        IOException
      • assertTermsEnumEquals

        public void assertTermsEnumEquals​(String info,
                                          IndexReader leftReader,
                                          TermsEnum leftTermsEnum,
                                          TermsEnum rightTermsEnum,
                                          boolean deep)
                                   throws IOException
        checks the terms enum sequentially if deep is false, it does a 'shallow' test that doesnt go down to the docsenums
        Throws:
        IOException
      • assertStoredFieldEquals

        public void assertStoredFieldEquals​(String info,
                                            IndexableField leftField,
                                            IndexableField rightField)
        checks that two stored fields are equivalent
      • callStackContains

        public static boolean callStackContains​(Class<?> clazz,
                                                String methodName)
        Inspects stack trace to figure out if a method of a specific class called us.
      • callStackContainsAnyOf

        public static boolean callStackContainsAnyOf​(String... methodNames)
        Inspects stack trace to figure out if one of the given method names (no class restriction) called us.
      • callStackContains

        public static boolean callStackContains​(Class<?> clazz)
        Inspects stack trace if the given class called us.
      • expectThrowsAnyOf

        public static <T extends Throwable> T expectThrowsAnyOf​(List<Class<? extends T>> expectedTypes,
                                                                LuceneTestCase.ThrowingRunnable runnable)
        Checks a specific exception class is thrown by the given runnable, and returns it.
      • expectThrows

        public static <TO extends Throwable,​TW extends Throwable> TW expectThrows​(Class<TO> expectedOuterType,
                                                                                        Class<TW> expectedWrappedType,
                                                                                        LuceneTestCase.ThrowingRunnable runnable)
        Checks that specific wrapped and outer exception classes are thrown by the given runnable, and returns the wrapped exception.
      • expectThrowsAnyOf

        public static <TO extends Throwable,​TW extends Throwable> TO expectThrowsAnyOf​(LinkedHashMap<Class<? extends TO>,​List<Class<? extends TW>>> expectedOuterToWrappedTypes,
                                                                                             LuceneTestCase.ThrowingRunnable runnable)
        Checks that one of the specified wrapped and outer exception classes are thrown by the given runnable, and returns the outer exception. This method accepts outer exceptions with no wrapped exception; an empty list of expected wrapped exception types indicates no wrapped exception.
      • slowFileExists

        public static boolean slowFileExists​(Directory dir,
                                             String fileName)
                                      throws IOException
        Returns true if the file exists (can be opened), false if it cannot be opened, and (unlike Java's File.exists) throws IOException if there's some unexpected error.
        Throws:
        IOException
      • createTempDir

        public static Path createTempDir()
        Creates an empty, temporary folder (when the name of the folder is of no importance).
        See Also:
        createTempDir(String)
      • createTempDir

        public static Path createTempDir​(String prefix)
        Creates an empty, temporary folder with the given name prefix under the test class's getBaseTempDirForTestClass().

        The folder will be automatically removed after the test class completes successfully. The test should close any file handles that would prevent the folder from being removed.

      • createTempFile

        public static Path createTempFile​(String prefix,
                                          String suffix)
                                   throws IOException
        Creates an empty file with the given prefix and suffix under the test class's getBaseTempDirForTestClass().

        The file will be automatically removed after the test class completes successfully. The test should close any file handles that would prevent the folder from being removed.

        Throws:
        IOException
      • runWithRestrictedPermissions

        public static <T> T runWithRestrictedPermissions​(PrivilegedExceptionAction<T> action,
                                                         Permission... permissions)
                                                  throws Exception
        Runs a code part with restricted permissions (be sure to add all required permissions, because it would start with empty permissions). You cannot grant more permissions than our policy file allows, but you may restrict writing to several dirs...

        Note: This assumes a SecurityManager enabled, otherwise it stops test execution. If enabled, it needs the following SecurityPermission: "createAccessControlContext"

        Throws:
        Exception
      • collate

        public static int collate​(Collator collator,
                                  String s1,
                                  String s2)
        Compares two strings with a collator, also looking to see if the the strings are impacted by jdk bugs. may not avoid all jdk bugs in tests. see https://bugs.openjdk.java.net/browse/JDK-8071862