You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucenenet.apache.org by ni...@apache.org on 2021/11/22 22:52:36 UTC
[lucenenet] branch master updated: Lucene.Net.TestFramework: Fixed random seed functionality so it is repeatable (Fixes #288) (#547)
This is an automated email from the ASF dual-hosted git repository.
nightowl888 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/lucenenet.git
The following commit(s) were added to refs/heads/master by this push:
new 6f1ea70 Lucene.Net.TestFramework: Fixed random seed functionality so it is repeatable (Fixes #288) (#547)
6f1ea70 is described below
commit 6f1ea70229f4d99dbc65666e7ee8c085bf7d1135
Author: Shad Storhaug <sh...@shadstorhaug.com>
AuthorDate: Tue Nov 23 05:52:27 2021 +0700
Lucene.Net.TestFramework: Fixed random seed functionality so it is repeatable (Fixes #288) (#547)
* Lucene.Net.TestFramework.Util.LuceneTestCase: Added message to the test result on how to set a fixed random seed to reproduce the test result (pass or fail).
* Lucene.Net.TestFramework.Util: Added customized TestFixtureAttribute, and NUnitTestFixtureBuilder along with RandomSeedAttribute and LuceneRandomSeedInitializer to fix the broken randomized seed functionality so we can repeat test runs reliably.
* BREAKING: Lucene.Net.Util.StringHelper.GOOD_FAST_HASH_SEED: converted from a static field to a property and marked obsolete. Added a new property GoodFastHashSeed. Removed SystemProperties call to populate the value of the field, since NUnit only allows us to generate a seed per test, and we need a way to inject the seed value for repeatability.
* Lucene.Net.TestFramework.Support.Util.LuceneRandomSeedInitializer: Added line to set StringHelper.goodFastHashSeed when the test framework is attached.
* Lucene.Net.TestFramework.Util.LuceneTestCase: Stow Random instance in test properties if we are in a suite context
* Lucene.Net.TestFramework: Reworked LuceneRandomSeedIntiailizer and changed RandomSeedAttribute to be an assembly-level attribute
* Lucene.Net.TestFramework: Removed support for Randomizer.InitialSeed and store the seed in a property of the test fixture (instance-based rather than static)
* Lucene.Net.Tests.TestFramework.Support.TestApiConsistency: Added exclusion for RandomSeed constant
* Lucene.Net.TestFramework.Util.TestRuleSetupAndRestoreClassEnv: Changed system property to prefer "tests:culture" instead of "tests:locale" to set the culture, but left "tests:locale" in for backward/java compatibility.
* Lucene.Net.TestFramework: Created RandomizedContext class to store as an NUnit test property for each test. This allows us to add additional strongly-typed properties to the test without wrapping the class. Changed to use J2N.Randomizer and changed all seeds to long rather than int. Converted the number for setting the random seed to hexadecimal and updated the message to add the setting for the current culture to the attributes/.runsettings file.
* BREAKING: Added LuceneSetUpFixtureBuilder class to load either a subclass or our default instance of LuceneTestFrameworkInitializer. Also added LuceneTestCase.SetUpFixture to control initialization of LuceneTestFrameworkInitializer so it is only called on setup and teardown for the assembly. Added Initialize() method to LuceneTestFrameworkInitializer that must be used to set the factories.
* Lucene.Net.TestFramework.Util.LuceneTestCase: Only print out the detailed random repeat message on failure or error
* BREAKING: Lucene.Net.TestFramework.Util.LuceneTestCase: Deprecated GetClassType() method and added TestType property
* BREAKING: Lucene.Net.TestFramework.Util.AbstractBeforeAfterRule: Removed LuceneTestCase parameter from Before() and After() methods.
* Lucene.Net.Util.LuceneRandomSeedInitializer: Added overload of InitializeTestFixture that accepts RandomizedContext so NUnitTestFixtureBuilder doesn't have to deal with setting NUnit properties. Also added RandomizedContext.CurrentTestAssembly property.
* Lucene.Net.TestFramework.Util: Added UseTempLineDocsFileAttribute and a UseTempLineDocFileRule to scan for it and execute the file decompression and cleanup. Removed the unnecessary Startup.cs files that only served the purpose of getting NUnit to recognize LuceneTestFrameworkInitializer in the assembly scan.
* Lucene.Net.TestFramework.Util.TestRuleSetupAndRestoreClassEnv: Allow NUnit's [SetCulture] attribute to be used to set the culture
* Lucene.Net.TestFramework.Util.LuceneTestCase: Updated repeat instructions to use NUnit's SetCulture attribute, since NUnit property attributes are not currently read by the test framework
* Lucene.Net.TestFramework.Analysis.BaseTokenStreamTestCase: Switched from using System.Random to J2N.Randomizer
* Lucene.Net.Tests.Analysis.Common.Analysis.Core.TestRandomChains: Switched from using System.Random to J2N.Randomizer. Also added feature to export a random SynonymMap as source code.
* azure-pipelines.yml: set maximumAllowedFailures to 0
* SWEEP: Marked all of the latest test failures with [AwaitsFix] attribute and an issue URL.
* Lucene.Net.Classification.KNearestNeighborClassifierTest::TestPerformance(): Ignore in net461, since it runs a bit slow in that environment.
* Lucene.Net.Index.TestIndexWriter::TestThreadInterruptDeadlock(): Added [AwaitsFix] attribute, as this is sometimes failing (see #544)
* Lucene.Net.Tests.Join.TestJoinUtil::TestMultiValueRandomJoin(): Added [AwaitsFix] attribute, since this test is failing on .NET Framework x86 in Release mode.
* SWEEP: Changed all test instances of System.Random to J2N.Randomizer. APIs remain as System.Random, since J2N.Randomizer is a subclass.
* Lucene.Net.TestFramework.Util.MethodInfoComparer: Made into singleton
* Lucene.Net.Classification.KNearestNeighborClassifierTest::TestPerformance(): Adjusted limit from 2 min to 2.5 min for .NET Framework, since it runs a bit slow in CI.
---
azure-pipelines.yml | 44 +-
src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs | 2 +-
.../ByTask/Feeds/RandomFacetSource.cs | 2 +-
.../ByTask/Feeds/SortableSingleDocSource.cs | 2 +-
.../ByTask/Feeds/SpatialDocMaker.cs | 2 +-
.../JS/JavascriptCompiler.cs | 2 +-
.../Suggest/UnsortedInputIterator.cs | 2 +-
.../Analysis/BaseTokenStreamTestCase.cs | 29 +-
.../Analysis/CrankyTokenFilter.cs | 2 +-
.../Analysis/MockAnalyzer.cs | 3 +-
.../Analysis/MockGraphTokenFilter.cs | 7 +-
.../Analysis/MockHoleInjectingTokenFilter.cs | 9 +-
.../Analysis/MockRandomLookaheadTokenFilter.cs | 13 +-
.../Analysis/MockTokenizer.cs | 5 +-
.../Codecs/MockRandom/MockRandomPostingsFormat.cs | 40 +-
.../Index/BasePostingsFormatTestCase.cs | 4 +-
.../Index/MockRandomMergePolicy.cs | 3 +-
src/Lucene.Net.TestFramework/Index/RandomCodec.cs | 5 +-
.../Index/RandomIndexWriter.cs | 4 +-
.../Index/ThreadedIndexingAndSearchingTestCase.cs | 11 +-
.../Search/AssertingIndexSearcher.cs | 8 +-
.../Search/AssertingQuery.cs | 18 +-
.../Search/AssertingWeight.cs | 6 +-
src/Lucene.Net.TestFramework/Search/QueryUtils.cs | 6 +-
.../Search/ShardSearchingTestBase.cs | 9 +-
.../Store/BaseDirectoryTestCase.cs | 6 +-
.../Store/MockDirectoryWrapper.cs | 2 +-
.../Support/Util/DefaultNamespaceTypeWrapper.cs | 294 +++++++++++++
.../Support/Util/LuceneRandomSeedInitializer.cs | 159 +++++++
.../Support/Util/LuceneSetUpFixtureBuilder.cs | 87 ++++
.../Support/Util/LuceneTestCase.SetUpFixture.cs | 198 +++++++++
.../Util/LuceneTestCase.TestFixtureAttribute.cs | 265 ++++++++++++
.../Support/Util/LuceneTestFrameworkInitializer.cs | 335 ++++++++++-----
.../Support/Util/NUnitTestFixtureBuilder.cs | 474 +++++++++++++++++++++
.../Support/Util/RandomSeedAttribute.cs | 52 +++
.../Support/Util/RandomizedContext.cs | 118 +++++
.../Util/UseTempLineDocsFileAttribute.cs} | 16 +-
.../Support/Util/UseTempLineDocsFileRule.cs | 84 ++++
.../Util/AbstractBeforeAfterRule.cs | 6 +-
src/Lucene.Net.TestFramework/Util/LineFileDocs.cs | 4 +-
.../Util/LuceneTestCase.cs | 93 ++--
.../Util/TestRuleSetupAndRestoreClassEnv.cs | 37 +-
.../Analysis/Core/TestRandomChains.cs | 87 +++-
.../Pattern/TestPatternReplaceCharFilter.cs | 7 +-
src/Lucene.Net.Tests.Analysis.Common/Startup.cs | 3 -
src/Lucene.Net.Tests.Analysis.Kuromoji/Startup.cs | 25 --
.../Startup.cs | 25 --
src/Lucene.Net.Tests.Analysis.OpenNLP/Startup.cs | 25 --
src/Lucene.Net.Tests.Analysis.Phonetic/Startup.cs | 25 --
src/Lucene.Net.Tests.Analysis.SmartCn/Startup.cs | 25 --
src/Lucene.Net.Tests.Analysis.Stempel/Startup.cs | 25 --
.../ByTask/TestPerfTasksParse.cs | 2 +-
.../ClassificationTestBase.cs | 7 +-
.../KNearestNeighborClassifierTest.cs | 3 +-
src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs | 2 +-
src/Lucene.Net.Tests.Join/Support/TestJoinUtil.cs | 3 +
src/Lucene.Net.Tests.Join/TestJoinUtil.cs | 3 +
.../Index/Sorter/TestEarlyTermination.cs | 6 +-
.../Index/Sorter/TestSortingMergePolicy.cs | 8 +-
src/Lucene.Net.Tests.Misc/Util/Fst/TestFSTsMisc.cs | 5 +-
.../CommonTermsQueryTest.cs | 6 +-
.../IndexInputStreamTest.cs | 16 +-
.../Suggest/Fst/WFSTCompletionTest.cs | 5 +-
.../Suggest/LookupBenchmarkTest.cs | 2 +-
.../Startup.cs | 2 +-
.../Configuration/TestSystemProperties.cs | 4 +-
src/Lucene.Net.Tests.TestFramework/Startup.cs | 2 +-
.../Support/TestApiConsistency.cs | 2 +-
src/Lucene.Net.Tests._A-D/Startup.cs | 25 --
src/Lucene.Net.Tests._I-J/Startup.cs | 25 --
src/Lucene.Net.Tests._J-S/Startup.cs | 25 --
.../Codecs/Lucene40/TestReuseDocsEnum.cs | 5 +-
.../Codecs/Lucene41/TestBlockPostingsFormat3.cs | 4 +-
.../Codecs/PerField/TestPerFieldDocValuesFormat.cs | 5 +-
.../Codecs/PerField/TestPerFieldPostingsFormat.cs | 5 +-
src/Lucene.Net.Tests/Index/TestBagOfPositions.cs | 2 +-
src/Lucene.Net.Tests/Index/TestCompoundFile.cs | 8 +-
.../Index/TestDocValuesWithThreads.cs | 2 +-
src/Lucene.Net.Tests/Index/TestDuelingCodecs.cs | 18 +-
.../Index/TestFlushByRamOrCountsPolicy.cs | 7 +-
src/Lucene.Net.Tests/Index/TestIndexWriter.cs | 4 +-
.../Index/TestIndexWriterExceptions.cs | 4 +-
.../Index/TestIndexWriterReader.cs | 2 +-
.../Index/TestNRTReaderWithThreads.cs | 3 +-
.../Index/TestPerSegmentDeletes.cs | 3 +-
src/Lucene.Net.Tests/Index/TestRollingUpdates.cs | 2 +-
src/Lucene.Net.Tests/Index/TestStressIndexing2.cs | 2 +-
src/Lucene.Net.Tests/Index/TestStressNRT.cs | 4 +-
.../Index/TestTermVectorsReader.cs | 2 +-
src/Lucene.Net.Tests/Index/TestTermdocPerf.cs | 3 +-
src/Lucene.Net.Tests/Index/TestTermsEnum.cs | 2 +-
src/Lucene.Net.Tests/Search/TestBoolean2.cs | 2 +-
.../Search/TestBooleanMinShouldMatch.cs | 8 +-
src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs | 3 +-
.../Search/TestSimpleExplanations.cs | 5 +-
.../Search/TestSloppyPhraseQuery2.cs | 9 +-
src/Lucene.Net.Tests/Search/TestSortRandom.cs | 2 +-
src/Lucene.Net.Tests/Util/Fst/Test2BFST.cs | 23 +-
src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs | 8 +-
src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs | 2 +-
src/Lucene.Net.Tests/Util/Test2BPagedBytes.cs | 4 +-
.../Util/TestFieldCacheSanityChecker.cs | 4 +-
src/Lucene.Net.Tests/Util/TestFixedBitSet.cs | 2 +-
src/Lucene.Net.Tests/Util/TestLongBitSet.cs | 2 +-
src/Lucene.Net.Tests/Util/TestMergedIterator.cs | 5 +-
src/Lucene.Net.Tests/Util/TestOpenBitSet.cs | 2 +-
src/Lucene.Net.Tests/Util/TestSetOnce.cs | 5 +-
src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs | 2 +-
src/Lucene.Net/Util/BytesRef.cs | 4 +-
src/Lucene.Net/Util/BytesRefHash.cs | 2 +-
src/Lucene.Net/Util/StringHelper.cs | 39 +-
111 files changed, 2382 insertions(+), 706 deletions(-)
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 63cd18f..e929bbc 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -336,17 +336,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net6.0,x64 on'
pool:
vmImage: $(imageName)
@@ -370,17 +370,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net6.0,x86 on'
pool:
vmImage: $(imageName)
@@ -404,17 +404,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net5.0,x64 on'
pool:
vmImage: $(imageName)
@@ -438,17 +438,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net5.0,x86 on'
pool:
vmImage: $(imageName)
@@ -472,17 +472,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-10.15' # macOS-latest should not be used here because we may get OS Darwin 19.6.0, which isn't supported fully (we get PlatformNotSupportedException).
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test netcoreapp3.1,x64 on'
pool:
vmImage: $(imageName)
@@ -506,17 +506,17 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
Linux:
osName: 'Linux'
imageName: 'ubuntu-latest'
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
macOS:
osName: 'macOS'
imageName: 'macOS-10.15' # macOS-latest should not be used here because we may get OS Darwin 19.6.0, which isn't supported fully (we get PlatformNotSupportedException).
maximumParallelJobs: 7
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test netcoreapp3.1,x86 on'
pool:
vmImage: $(imageName)
@@ -540,7 +540,7 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net461,x64 on'
pool:
vmImage: $(imageName)
@@ -564,7 +564,7 @@ stages:
osName: 'Windows'
imageName: 'windows-2019'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
displayName: 'Test net461,x86 on'
pool:
vmImage: $(imageName)
@@ -595,7 +595,7 @@ stages:
nugetArtifactName: '$(NuGetArtifactName)'
testResultsArtifactName: '$(TestResultsArtifactName)'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
- job: Test_net48_Windows_x86 # Only run Nightly or if explicitly enabled with RunX86Tests
condition: and(succeeded(), ne(variables['RunTests'], 'false'), or(eq(variables['IsNightly'], 'true'), eq(variables['RunX86Tests'], 'true')))
@@ -612,7 +612,7 @@ stages:
nugetArtifactName: '$(NuGetArtifactName)'
testResultsArtifactName: '$(TestResultsArtifactName)'
maximumParallelJobs: 8
- maximumAllowedFailures: 2 # Maximum allowed failures for a successful build
+ maximumAllowedFailures: 0 # Maximum allowed failures for a successful build
- stage: Publish_Stage
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
index 6b2e7af..9983a21 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/DocMaker.cs
@@ -505,7 +505,7 @@ namespace Lucene.Net.Benchmarks.ByTask.Feeds
updateDocIDLimit = config.Get("doc.random.id.limit", -1);
if (updateDocIDLimit != -1)
{
- r = new Random(179);
+ r = new J2N.Randomizer(179);
}
}
}
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs
index 467180c..cd42950 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/RandomFacetSource.cs
@@ -95,7 +95,7 @@ namespace Lucene.Net.Benchmarks.ByTask.Feeds
public override void SetConfig(Config config)
{
base.SetConfig(config);
- random = new Random(config.Get("rand.seed", 13));
+ random = new J2N.Randomizer(config.Get("rand.seed", 13));
maxDocFacets = config.Get("max.doc.facets", 10);
maxDims = config.Get("max.doc.facets.dims", 5);
maxFacetDepth = config.Get("max.facet.depth", 3);
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/SortableSingleDocSource.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/SortableSingleDocSource.cs
index 1c91e81..ac7a40c 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/SortableSingleDocSource.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/SortableSingleDocSource.cs
@@ -109,7 +109,7 @@ namespace Lucene.Net.Benchmarks.ByTask.Feeds
{
base.SetConfig(config);
sortRange = config.Get("sort.rng", 20000);
- r = new Random(config.Get("rand.seed", 13));
+ r = new J2N.Randomizer(config.Get("rand.seed", 13));
}
}
}
diff --git a/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs b/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs
index a54aa33..df8e4cc 100644
--- a/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs
+++ b/src/Lucene.Net.Benchmark/ByTask/Feeds/SpatialDocMaker.cs
@@ -219,7 +219,7 @@ namespace Lucene.Net.Benchmarks.ByTask.Feeds
double radius = radiusDegrees;
if (plusMinus > 0.0)
{
- Random random = new Random(point.GetHashCode());//use hashCode so it's reproducibly random
+ Random random = new J2N.Randomizer(point.GetHashCode());//use hashCode so it's reproducibly random
radius += random.NextDouble() * 2 * plusMinus - plusMinus;
radius = Math.Abs(radius);//can happen if configured plusMinus > radiusDegrees
}
diff --git a/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs b/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs
index d2f4443..afdcf73 100644
--- a/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs
+++ b/src/Lucene.Net.Expressions/JS/JavascriptCompiler.cs
@@ -194,7 +194,7 @@ namespace Lucene.Net.Expressions.JS
private void BeginCompile()
{
- var assemblyName = new AssemblyName("Lucene.Net.Expressions.Dynamic" + new Random().Next());
+ var assemblyName = new AssemblyName("Lucene.Net.Expressions.Dynamic" + Math.Abs(new J2N.Randomizer().Next()));
asmBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect);
modBuilder = asmBuilder.DefineDynamicModule(assemblyName.Name + ".dll");
diff --git a/src/Lucene.Net.Suggest/Suggest/UnsortedInputIterator.cs b/src/Lucene.Net.Suggest/Suggest/UnsortedInputIterator.cs
index 6b1707f..ec60223 100644
--- a/src/Lucene.Net.Suggest/Suggest/UnsortedInputIterator.cs
+++ b/src/Lucene.Net.Suggest/Suggest/UnsortedInputIterator.cs
@@ -43,7 +43,7 @@ namespace Lucene.Net.Search.Suggest
: base(source)
{
ords = new int[m_entries.Length];
- Random random = new Random();
+ Random random = new J2N.Randomizer();
for (int i = 0; i < ords.Length; i++)
{
ords[i] = i;
diff --git a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
index 266a5c1..67e0fc0 100644
--- a/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/BaseTokenStreamTestCase.cs
@@ -95,6 +95,8 @@ namespace Lucene.Net.Analysis
/// </summary>
/// <seealso cref="MockAnalyzer"/>
/// <seealso cref="MockTokenizer"/>
+ // LUCENENET specific - Specify to unzip the line file docs
+ [UseTempLineDocsFile]
public abstract class BaseTokenStreamTestCase : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
@@ -126,13 +128,6 @@ namespace Lucene.Net.Analysis
// LUCENENET specific - de-nested CheckClearAttributesAttribute
- // LUCENENET specific - Specify to unzip the line file docs
- public override void BeforeClass()
- {
- UseTempLineDocsFile = true;
- base.BeforeClass();
- }
-
// offsetsAreCorrect also validates:
// - graph offsets are correct (all tokens leaving from
// pos X have the same startOffset; all tokens
@@ -715,7 +710,7 @@ namespace Lucene.Net.Analysis
if (latch != null) latch.Wait();
// see the part in checkRandomData where it replays the same text again
// to verify reproducability/reuse: hopefully this would catch thread hazards.
- CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
+ CheckRandomData(new J2N.Randomizer(seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
success = true;
}
catch (Exception e) when (e.IsException()) // LUCENENET TODO: This catch block can be removed because Rethrow.rethrow() simply does what its name says, but need to get rid of the FirstException functionality and fix ThreadJob so it re-throws ThreadInterruptedExcepetion first.
@@ -754,7 +749,7 @@ namespace Lucene.Net.Analysis
#endif
{
CheckResetException(a, "best effort");
- long seed = random.Next();
+ long seed = random.NextInt64();
bool useCharFilter = random.NextBoolean();
Directory dir = null;
RandomIndexWriter iw = null;
@@ -769,13 +764,13 @@ namespace Lucene.Net.Analysis
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
- new Random((int)seed), dir, a);
+ new J2N.Randomizer(seed), dir, a);
}
bool success = false;
try
{
- CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
+ CheckRandomData(new J2N.Randomizer(seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
// now test with multiple threads: note we do the EXACT same thing we did before in each thread,
// so this should only really fail from another thread if its an actual thread problem
int numThreads = TestUtil.NextInt32(random, 2, 4);
@@ -785,7 +780,7 @@ namespace Lucene.Net.Analysis
{
threads[i] = new AnalysisThread(seed, startingGun, a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
}
-
+
foreach (AnalysisThread thread in threads)
{
thread.Start();
@@ -948,7 +943,7 @@ namespace Lucene.Net.Analysis
{
// TODO: really we should pass a random seed to
// checkAnalysisConsistency then print it here too:
- Console.Error.WriteLine("TEST FAIL: useCharFilter=" + useCharFilter + " text='" + Escape(text) + "'");
+ Console.Error.WriteLine($"TEST FAIL (iteration {i}): useCharFilter=" + useCharFilter + " text='" + Escape(text) + "'");
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
@@ -1201,8 +1196,8 @@ namespace Lucene.Net.Analysis
}
reader = new StringReader(text);
- long seed = random.Next();
- random = new Random((int)seed);
+ long seed = random.NextInt64();
+ random = new J2N.Randomizer(seed);
if (random.Next(30) == 7)
{
if (Verbose)
@@ -1248,7 +1243,7 @@ namespace Lucene.Net.Analysis
if (field != null)
{
reader = new StringReader(text);
- random = new Random((int)seed);
+ random = new J2N.Randomizer(seed);
if (random.Next(30) == 7)
{
if (Verbose)
@@ -1297,7 +1292,7 @@ namespace Lucene.Net.Analysis
/// <summary>Returns a random <see cref="AttributeFactory"/> impl</summary>
public static AttributeFactory NewAttributeFactory(Random random)
{
- switch (random.nextInt(2))
+ switch (random.Next(2))
{
case 0:
return Token.TOKEN_ATTRIBUTE_FACTORY;
diff --git a/src/Lucene.Net.TestFramework/Analysis/CrankyTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/CrankyTokenFilter.cs
index 3fec138..d1c29d7 100644
--- a/src/Lucene.Net.TestFramework/Analysis/CrankyTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/CrankyTokenFilter.cs
@@ -62,7 +62,7 @@ namespace Lucene.Net.TestFramework.Analysis
public override void Reset()
{
base.Reset();
- thingToDo = random.nextInt(100);
+ thingToDo = random.Next(100);
if (thingToDo == 2 && random.nextBoolean())
{
throw new IOException("Fake IOException from TokenStream.Reset()");
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockAnalyzer.cs b/src/Lucene.Net.TestFramework/Analysis/MockAnalyzer.cs
index cae547a..567ec5c 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockAnalyzer.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockAnalyzer.cs
@@ -1,6 +1,7 @@
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using Lucene.Net.Util.Automaton;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using System.IO;
@@ -72,7 +73,7 @@ namespace Lucene.Net.Analysis
: base(PER_FIELD_REUSE_STRATEGY)
{
// TODO: this should be solved in a different way; Random should not be shared (!).
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
this.runAutomaton = runAutomaton;
this.lowerCase = lowerCase;
this.filter = filter;
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
index c248a72..318f197 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockGraphTokenFilter.cs
@@ -1,5 +1,6 @@
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
+using RandomizedTesting.Generators;
using System;
using Console = Lucene.Net.Util.SystemConsole;
@@ -38,13 +39,13 @@ namespace Lucene.Net.Analysis
private readonly ICharTermAttribute termAtt;
- private readonly int seed; // LUCENENET specific: changed to int, since .NET random seed is int, not long
+ private readonly long seed;
private Random random;
public MockGraphTokenFilter(Random random, TokenStream input)
: base(input)
{
- seed = random.Next();
+ seed = random.NextInt64();
termAtt = AddAttribute<ICharTermAttribute>();
}
@@ -111,7 +112,7 @@ namespace Lucene.Net.Analysis
// NOTE: must be "deterministically random" because
// baseTokenStreamTestCase pulls tokens twice on the
// same input and asserts they are the same:
- this.random = new Random(seed);
+ this.random = new J2N.Randomizer(seed);
}
protected override void Dispose(bool disposing)
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockHoleInjectingTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockHoleInjectingTokenFilter.cs
index ed5e4b5..16c4d54 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockHoleInjectingTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockHoleInjectingTokenFilter.cs
@@ -1,5 +1,6 @@
-using Lucene.Net.Analysis.TokenAttributes;
+using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Util;
+using RandomizedTesting.Generators;
using System;
namespace Lucene.Net.Analysis
@@ -30,7 +31,7 @@ namespace Lucene.Net.Analysis
/// </summary>
public sealed class MockHoleInjectingTokenFilter : TokenFilter
{
- private readonly int randomSeed; // LUCENENET specific - changed from long to int, as in .NET a System.Random seed is int
+ private readonly long randomSeed;
private Random random;
private readonly IPositionIncrementAttribute posIncAtt;
private readonly IPositionLengthAttribute posLenAtt;
@@ -40,7 +41,7 @@ namespace Lucene.Net.Analysis
public MockHoleInjectingTokenFilter(Random random, TokenStream @in)
: base(@in)
{
- randomSeed = random.Next();
+ randomSeed = random.NextInt64();
posIncAtt = AddAttribute<IPositionIncrementAttribute>();
posLenAtt = AddAttribute<IPositionLengthAttribute>();
}
@@ -48,7 +49,7 @@ namespace Lucene.Net.Analysis
public override void Reset()
{
base.Reset();
- random = new Random(randomSeed);
+ random = new J2N.Randomizer(randomSeed);
maxPos = -1;
pos = -1;
}
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockRandomLookaheadTokenFilter.cs b/src/Lucene.Net.TestFramework/Analysis/MockRandomLookaheadTokenFilter.cs
index 3aa0339..1bdcd7b 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockRandomLookaheadTokenFilter.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockRandomLookaheadTokenFilter.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Analysis.TokenAttributes;
+using Lucene.Net.Analysis.TokenAttributes;
+using RandomizedTesting.Generators;
using System;
using System.Threading;
using Console = Lucene.Net.Util.SystemConsole;
@@ -28,15 +29,15 @@ namespace Lucene.Net.Analysis
public sealed class MockRandomLookaheadTokenFilter : LookaheadTokenFilter<LookaheadTokenFilter.Position>
{
private readonly ICharTermAttribute termAtt;
- private Random random; // LUCENENET: not readonly to reset seed later
- private readonly int seed; // LUCENENET specific: changed to int, since .NET random seed is int, not long
+ private readonly J2N.Randomizer random;
+ private readonly long seed;
public MockRandomLookaheadTokenFilter(Random random, TokenStream @in)
: base(@in)
{
this.termAtt = AddAttribute<ICharTermAttribute>();
- this.seed = random.Next();
- this.random = new Random(seed);
+ this.seed = random.NextInt64();
+ this.random = new J2N.Randomizer(seed);
}
protected override Position NewPosition()
@@ -110,7 +111,7 @@ namespace Lucene.Net.Analysis
public override void Reset()
{
base.Reset();
- random = new Random(seed);
+ random.Seed = seed;
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.TestFramework/Analysis/MockTokenizer.cs b/src/Lucene.Net.TestFramework/Analysis/MockTokenizer.cs
index 05eda51..3b72dbb 100644
--- a/src/Lucene.Net.TestFramework/Analysis/MockTokenizer.cs
+++ b/src/Lucene.Net.TestFramework/Analysis/MockTokenizer.cs
@@ -1,7 +1,8 @@
-using J2N;
+using J2N;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
+using RandomizedTesting.Generators;
using System;
using System.Globalization;
using System.IO;
@@ -99,7 +100,7 @@ namespace Lucene.Net.Analysis
private bool enableChecks = true;
// evil: but we don't change the behavior with this random, we only switch up how we read
- private readonly Random random = new Random(LuceneTestCase.Random.Next() /*RandomizedContext.Current.Random.nextLong()*/); // LUCENENET TODO: Random seed synchronization
+ private readonly Random random = new J2N.Randomizer(LuceneTestCase.Random.NextInt64()); // LUCENENET: LuceneTestCase.Random instead of using RandomizedContext.CurrentContext.RandomGenerator, since the latter could be null
public MockTokenizer(AttributeFactory factory, TextReader input, CharacterRunAutomaton runAutomaton, bool lowerCase, int maxTokenLength)
: base(factory, input)
diff --git a/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs b/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
index 15deb78..12e6d14 100644
--- a/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
+++ b/src/Lucene.Net.TestFramework/Codecs/MockRandom/MockRandomPostingsFormat.cs
@@ -43,7 +43,7 @@ namespace Lucene.Net.Codecs.MockRandom
private readonly Random seedRandom;
private const string SEED_EXT = "sd";
- private class RandomAnonymousClassHelper : Random
+ private class RandomAnonymousClassHelper : J2N.Randomizer
{
public RandomAnonymousClassHelper()
: base(0)
@@ -67,7 +67,7 @@ namespace Lucene.Net.Codecs.MockRandom
if (random == null)
this.seedRandom = new RandomAnonymousClassHelper();
else
- this.seedRandom = new Random(random.Next());
+ this.seedRandom = new J2N.Randomizer(random.NextInt64());
}
// Chooses random IntStreamFactory depending on file's extension
@@ -78,7 +78,7 @@ namespace Lucene.Net.Codecs.MockRandom
public MockInt32StreamFactory(Random random)
{
- salt = random.nextInt();
+ salt = random.Next();
delegates.Add(new MockSingleInt32Factory());
int blockSize = TestUtil.NextInt32(random, 1, 2000);
delegates.Add(new MockFixedInt32BlockPostingsFormat.MockInt32Factory(blockSize));
@@ -98,7 +98,7 @@ namespace Lucene.Net.Codecs.MockRandom
{
// Must only use extension, because IW.addIndexes can
// rename segment!
- Int32StreamFactory f = delegates[(Math.Abs(salt ^ GetExtension(fileName).GetHashCode())) % delegates.size()];
+ Int32StreamFactory f = delegates[(Math.Abs(salt ^ GetExtension(fileName).GetHashCode())) % delegates.Count];
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockRandomCodec: read using int factory " + f + " from fileName=" + fileName);
@@ -108,7 +108,7 @@ namespace Lucene.Net.Codecs.MockRandom
public override Int32IndexOutput CreateOutput(Directory dir, string fileName, IOContext context)
{
- Int32StreamFactory f = delegates[(Math.Abs(salt ^ GetExtension(fileName).GetHashCode())) % delegates.size()];
+ Int32StreamFactory f = delegates[(Math.Abs(salt ^ GetExtension(fileName).GetHashCode())) % delegates.Count];
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockRandomCodec: write using int factory " + f + " to fileName=" + fileName);
@@ -121,9 +121,9 @@ namespace Lucene.Net.Codecs.MockRandom
{
private readonly Random rand;
private readonly int gap;
- public IndexTermSelectorAnonymousClass(int seed, int gap)
+ public IndexTermSelectorAnonymousClass(long seed, int gap)
{
- rand = new Random(seed);
+ rand = new J2N.Randomizer(seed);
this.gap = gap;
}
public override bool IsIndexTerm(BytesRef term, TermStats stats)
@@ -158,7 +158,7 @@ namespace Lucene.Net.Codecs.MockRandom
Console.WriteLine("MockRandomCodec: skipInterval=" + skipInterval);
}
- long seed = seedRandom.nextLong();
+ long seed = seedRandom.NextInt64();
if (LuceneTestCase.Verbose)
{
@@ -176,9 +176,9 @@ namespace Lucene.Net.Codecs.MockRandom
@out.Dispose();
}
- Random random = new Random((int)seed);
+ Random random = new J2N.Randomizer(seed);
- random.nextInt(); // consume a random for buffersize
+ random.Next(); // consume a random for buffersize
PostingsWriterBase postingsWriter;
if (random.nextBoolean())
@@ -195,7 +195,7 @@ namespace Lucene.Net.Codecs.MockRandom
postingsWriter = new Lucene41PostingsWriter(state, skipInterval);
}
- if (random.nextBoolean())
+ if (random.NextBoolean())
{
int totTFCutoff = TestUtil.NextInt32(random, 1, 20);
if (LuceneTestCase.Verbose)
@@ -206,7 +206,7 @@ namespace Lucene.Net.Codecs.MockRandom
}
FieldsConsumer fields;
- int t1 = random.nextInt(4);
+ int t1 = random.Next(4);
if (t1 == 0)
{
@@ -252,7 +252,7 @@ namespace Lucene.Net.Codecs.MockRandom
// TODO: would be nice to allow 1 but this is very
// slow to write
int minTermsInBlock = TestUtil.NextInt32(random, 2, 100);
- int maxTermsInBlock = Math.Max(2, (minTermsInBlock - 1) * 2 + random.nextInt(100));
+ int maxTermsInBlock = Math.Max(2, (minTermsInBlock - 1) * 2 + random.Next(100));
bool success = false;
try
@@ -281,7 +281,7 @@ namespace Lucene.Net.Codecs.MockRandom
TermsIndexWriterBase indexWriter;
try
{
- if (random.nextBoolean())
+ if (random.NextBoolean())
{
state.TermIndexInterval = TestUtil.NextInt32(random, 1, 100);
if (LuceneTestCase.Verbose)
@@ -293,7 +293,7 @@ namespace Lucene.Net.Codecs.MockRandom
else
{
VariableGapTermsIndexWriter.IndexTermSelector selector;
- int n2 = random.nextInt(3);
+ int n2 = random.Next(3);
if (n2 == 0)
{
int tii = TestUtil.NextInt32(random, 1, 100);
@@ -311,7 +311,7 @@ namespace Lucene.Net.Codecs.MockRandom
}
else
{
- int seed2 = random.Next();
+ long seed2 = random.NextInt64();
int gap = TestUtil.NextInt32(random, 2, 40);
if (LuceneTestCase.Verbose)
{
@@ -368,7 +368,7 @@ namespace Lucene.Net.Codecs.MockRandom
}
@in.Dispose();
- Random random = new Random((int)seed);
+ Random random = new J2N.Randomizer(seed);
int readBufferSize = TestUtil.NextInt32(random, 1, 4096);
if (LuceneTestCase.Verbose)
@@ -378,7 +378,7 @@ namespace Lucene.Net.Codecs.MockRandom
PostingsReaderBase postingsReader;
- if (random.nextBoolean())
+ if (random.NextBoolean())
{
if (LuceneTestCase.Verbose)
{
@@ -396,7 +396,7 @@ namespace Lucene.Net.Codecs.MockRandom
postingsReader = new Lucene41PostingsReader(state.Directory, state.FieldInfos, state.SegmentInfo, state.Context, state.SegmentSuffix);
}
- if (random.nextBoolean())
+ if (random.NextBoolean())
{
int totTFCutoff = TestUtil.NextInt32(random, 1, 20);
if (LuceneTestCase.Verbose)
@@ -407,7 +407,7 @@ namespace Lucene.Net.Codecs.MockRandom
}
FieldsProducer fields;
- int t1 = random.nextInt(4);
+ int t1 = random.Next(4);
if (t1 == 0)
{
bool success = false;
diff --git a/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs b/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
index 36d6814..1fe19d3 100644
--- a/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/BasePostingsFormatTestCase.cs
@@ -142,8 +142,8 @@ namespace Lucene.Net.Index
public SeedPostings(long seed, int minDocFreq, int maxDocFreq, IBits liveDocs, IndexOptions options)
{
- random = new Random((int)seed);
- docRandom = new Random(random.Next());
+ random = new J2N.Randomizer(seed);
+ docRandom = new J2N.Randomizer(random.NextInt64());
DocFreq = TestUtil.NextInt32(random, minDocFreq, maxDocFreq);
this.liveDocs = liveDocs;
diff --git a/src/Lucene.Net.TestFramework/Index/MockRandomMergePolicy.cs b/src/Lucene.Net.TestFramework/Index/MockRandomMergePolicy.cs
index 3a811ff..5f1fca6 100644
--- a/src/Lucene.Net.TestFramework/Index/MockRandomMergePolicy.cs
+++ b/src/Lucene.Net.TestFramework/Index/MockRandomMergePolicy.cs
@@ -1,6 +1,7 @@
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
@@ -35,7 +36,7 @@ namespace Lucene.Net.Index
{
// fork a private random, since we are called
// unpredictably from threads:
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
}
public override MergeSpecification FindMerges(MergeTrigger mergeTrigger, SegmentInfos segmentInfos)
diff --git a/src/Lucene.Net.TestFramework/Index/RandomCodec.cs b/src/Lucene.Net.TestFramework/Index/RandomCodec.cs
index 0f41316..5b517aa 100644
--- a/src/Lucene.Net.TestFramework/Index/RandomCodec.cs
+++ b/src/Lucene.Net.TestFramework/Index/RandomCodec.cs
@@ -16,6 +16,7 @@ using Lucene.Net.Codecs.SimpleText;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using Lucene.Net.Util;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -157,8 +158,8 @@ namespace Lucene.Net.Index
new Lucene41WithOrds(),
new SimpleTextPostingsFormat(),
new AssertingPostingsFormat(),
- new MemoryPostingsFormat(true, random.nextFloat()),
- new MemoryPostingsFormat(false, random.nextFloat())
+ new MemoryPostingsFormat(true, random.NextSingle()),
+ new MemoryPostingsFormat(false, random.NextSingle())
);
AddDocValues(avoidCodecs,
diff --git a/src/Lucene.Net.TestFramework/Index/RandomIndexWriter.cs b/src/Lucene.Net.TestFramework/Index/RandomIndexWriter.cs
index f34829a..f9776fc 100644
--- a/src/Lucene.Net.TestFramework/Index/RandomIndexWriter.cs
+++ b/src/Lucene.Net.TestFramework/Index/RandomIndexWriter.cs
@@ -49,7 +49,7 @@ namespace Lucene.Net.Index
public static IndexWriter MockIndexWriter(Directory dir, IndexWriterConfig conf, Random r)
{
// Randomly calls Thread.yield so we mixup thread scheduling
- Random random = new Random(r.Next());
+ Random random = new J2N.Randomizer(r.NextInt64());
return MockIndexWriter(dir, conf, new TestPointAnonymousClass(random));
}
@@ -162,7 +162,7 @@ namespace Lucene.Net.Index
public RandomIndexWriter(Random r, Directory dir, IndexWriterConfig c)
{
// TODO: this should be solved in a different way; Random should not be shared (!).
- this.r = new Random(r.Next());
+ this.r = new J2N.Randomizer(r.NextInt64());
IndexWriter = MockIndexWriter(dir, c, r);
flushAt = TestUtil.NextInt32(r, 10, 1000);
codec = IndexWriter.Config.Codec;
diff --git a/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs b/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
index 9cb64ef..7eeea39 100644
--- a/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Index/ThreadedIndexingAndSearchingTestCase.cs
@@ -49,6 +49,8 @@ namespace Lucene.Net.Index
/// Utility class that spawns multiple indexing and
/// searching threads.
/// </summary>
+ // LUCENENET specific - Specify to unzip the line file docs
+ [UseTempLineDocsFile]
public abstract class ThreadedIndexingAndSearchingTestCase : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
@@ -81,13 +83,6 @@ namespace Lucene.Net.Index
}
}
- // LUCENENET specific - Specify to unzip the line file docs
- public override void BeforeClass()
- {
- UseTempLineDocsFile = true;
- base.BeforeClass();
- }
-
// Called per-search
protected abstract IndexSearcher GetCurrentSearcher();
@@ -570,7 +565,7 @@ namespace Lucene.Net.Index
long t0 = J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues);
DirectoryInfo tempDir = CreateTempDir(testName);
m_dir = GetDirectory(NewMockFSDirectory(tempDir)); // some subclasses rely on this being MDW
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
index 907a59b..3ef8c83 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingIndexSearcher.cs
@@ -35,25 +35,25 @@ namespace Lucene.Net.Search
public AssertingIndexSearcher(Random random, IndexReader r)
: base(r)
{
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
}
public AssertingIndexSearcher(Random random, IndexReaderContext context)
: base(context)
{
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
}
public AssertingIndexSearcher(Random random, IndexReader r, TaskScheduler ex)
: base(r, ex)
{
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
}
public AssertingIndexSearcher(Random random, IndexReaderContext context, TaskScheduler ex)
: base(context, ex)
{
- this.random = new Random(random.Next());
+ this.random = new J2N.Randomizer(random.NextInt64());
}
/// <summary>
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingQuery.cs b/src/Lucene.Net.TestFramework/Search/AssertingQuery.cs
index 6ac7259..e73bfb7 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingQuery.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingQuery.cs
@@ -1,4 +1,5 @@
-using Lucene.Net.Index;
+using Lucene.Net.Index;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
@@ -41,13 +42,12 @@ namespace Lucene.Net.Search
/// Wrap a query if necessary. </summary>
public static Query Wrap(Random random, Query query)
{
- var aq = query as AssertingQuery;
- return aq ?? new AssertingQuery(random, query);
+ return query is AssertingQuery ? query : new AssertingQuery(random, query);
}
public override Weight CreateWeight(IndexSearcher searcher)
{
- return AssertingWeight.Wrap(new Random(random.Next()), @in.CreateWeight(searcher));
+ return AssertingWeight.Wrap(new J2N.Randomizer(random.NextInt64()), @in.CreateWeight(searcher));
}
public override void ExtractTerms(ISet<Term> terms)
@@ -74,7 +74,7 @@ namespace Lucene.Net.Search
public override object Clone()
{
- return Wrap(new Random(random.Next()), (Query)@in.Clone());
+ return Wrap(new J2N.Randomizer(random.NextInt64()), (Query)@in.Clone());
}
public override Query Rewrite(IndexReader reader)
@@ -86,18 +86,14 @@ namespace Lucene.Net.Search
}
else
{
- return Wrap(new Random(random.Next()), rewritten);
+ return Wrap(new J2N.Randomizer(random.NextInt64()), rewritten);
}
}
public override float Boost
{
get => @in.Boost;
- set
- {
- if (@in != null)
- @in.Boost = value;
- }
+ set => @in.Boost = value;
}
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.TestFramework/Search/AssertingWeight.cs b/src/Lucene.Net.TestFramework/Search/AssertingWeight.cs
index 98422b2..3cf978c 100644
--- a/src/Lucene.Net.TestFramework/Search/AssertingWeight.cs
+++ b/src/Lucene.Net.TestFramework/Search/AssertingWeight.cs
@@ -58,7 +58,7 @@ namespace Lucene.Net.Search
// if the caller asks for in-order scoring or if the weight does not support
// out-of order scoring then collection will have to happen in-order.
Scorer inScorer = @in.GetScorer(context, acceptDocs);
- return AssertingScorer.Wrap(new Random(random.Next()), inScorer);
+ return AssertingScorer.Wrap(new J2N.Randomizer(random.NextInt64()), inScorer);
}
public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs)
@@ -75,7 +75,7 @@ namespace Lucene.Net.Search
{
// The incoming scorer already has a specialized
// implementation for BulkScorer, so we should use it:
- inScorer = AssertingBulkScorer.Wrap(new Random(random.Next()), inScorer);
+ inScorer = AssertingBulkScorer.Wrap(new J2N.Randomizer(random.NextInt64()), inScorer);
}
else if (random.NextBoolean())
{
@@ -89,7 +89,7 @@ namespace Lucene.Net.Search
// The caller claims it can handle out-of-order
// docs; let's confirm that by pulling docs and
// randomly shuffling them before collection:
- inScorer = new AssertingBulkOutOfOrderScorer(new Random(random.Next()), inScorer);
+ inScorer = new AssertingBulkOutOfOrderScorer(new J2N.Randomizer(random.NextInt64()), inScorer);
}
return inScorer;
}
diff --git a/src/Lucene.Net.TestFramework/Search/QueryUtils.cs b/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
index 128f5e1..94cc7c7 100644
--- a/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
+++ b/src/Lucene.Net.TestFramework/Search/QueryUtils.cs
@@ -281,9 +281,9 @@ namespace Lucene.Net.Search
try
{
emptyReaders[0] = new MultiReader();
- emptyReaders[4] = MakeEmptyIndex(new Random(0), 4);
- emptyReaders[5] = MakeEmptyIndex(new Random(0), 5);
- emptyReaders[7] = MakeEmptyIndex(new Random(0), 7);
+ emptyReaders[4] = MakeEmptyIndex(new J2N.Randomizer(0), 4);
+ emptyReaders[5] = MakeEmptyIndex(new J2N.Randomizer(0), 5);
+ emptyReaders[7] = MakeEmptyIndex(new J2N.Randomizer(0), 7);
}
catch (Exception ex) when (ex.IsIOException())
{
diff --git a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
index 6e8b798..727ae2c 100644
--- a/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
+++ b/src/Lucene.Net.TestFramework/Search/ShardSearchingTestBase.cs
@@ -72,6 +72,8 @@ namespace Lucene.Net.Search
/// <summary>
/// Base test class for simulating distributed search across multiple shards.
/// </summary>
+ // LUCENENET specific - Specify to unzip the line file docs
+ [UseTempLineDocsFile]
public abstract class ShardSearchingTestBase : LuceneTestCase
#if TESTFRAMEWORK_XUNIT
, Xunit.IClassFixture<BeforeAfterClass>
@@ -83,13 +85,6 @@ namespace Lucene.Net.Search
#else
{
#endif
- // LUCENENET specific - Specify to unzip the line file docs
- public override void BeforeClass()
- {
- UseTempLineDocsFile = true;
- base.BeforeClass();
- }
-
// LUCENENET specific - de-nested SearcherExpiredException
diff --git a/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs b/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
index 552fe88..14ec3bd 100644
--- a/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Store/BaseDirectoryTestCase.cs
@@ -445,7 +445,7 @@ namespace Lucene.Net.Store
public virtual void TestChecksum()
{
CRC32 expected = new CRC32();
- int numBytes = Random.nextInt(20000);
+ int numBytes = Random.Next(20000);
byte[] bytes = new byte[numBytes];
Random.NextBytes(bytes);
expected.Update(bytes);
@@ -494,7 +494,7 @@ namespace Lucene.Net.Store
// {
// try
// {
- // Random rnd = new Random(Random.Next() + 1); // LUCENENET: Changed from Long to Int32
+ // Random rnd = new J2N.Randomizer(Random.NextInt64() + 1);
// for (int i = 0, max = RandomInts.RandomInt32Between(Random, 500, 1000); i < max; i++)
// {
// string fileName = "file-" + i;
@@ -534,7 +534,7 @@ namespace Lucene.Net.Store
// {
// try
// {
- // Random rnd = new Random(Random.Next()); // LUCENENET: Changed from Long to Int32
+ // Random rnd = new J2N.Randomizer(Random.NextInt64());
// while (!stop.Get())
// {
// string[] files = dir.ListAll()
diff --git a/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs b/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
index ead37aa..c341334 100644
--- a/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
+++ b/src/Lucene.Net.TestFramework/Store/MockDirectoryWrapper.cs
@@ -166,7 +166,7 @@ namespace Lucene.Net.Store
// must make a private random since our methods are
// called from different threads; else test failures may
// not be reproducible from the original seed
- this.randomState = new Random(random.Next());
+ this.randomState = new J2N.Randomizer(random.NextInt64());
this.throttledOutput = new ThrottledIndexOutput(ThrottledIndexOutput.MBitsToBytes(40 + randomState.Next(10)), 5 + randomState.Next(5), null);
// force wrapping of lockfactory
this.m_lockFactory = new MockLockFactoryWrapper(this, @delegate.LockFactory);
diff --git a/src/Lucene.Net.TestFramework/Support/Util/DefaultNamespaceTypeWrapper.cs b/src/Lucene.Net.TestFramework/Support/Util/DefaultNamespaceTypeWrapper.cs
new file mode 100644
index 0000000..4a3de06
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/DefaultNamespaceTypeWrapper.cs
@@ -0,0 +1,294 @@
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using System;
+using System.Linq;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ #region Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License.
+
+ // Copyright (c) 2021 Charlie Poole, Rob Prouse
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
+ // of this software and associated documentation files (the "Software"), to deal
+ // in the Software without restriction, including without limitation the rights
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ // copies of the Software, and to permit persons to whom the Software is
+ // furnished to do so, subject to the following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included in
+ // all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ // THE SOFTWARE.
+
+ #endregion
+
+ /// <summary>
+ /// The TypeWrapper class wraps a Type so it may be used in
+ /// a platform-independent manner. This class overrides the
+ /// namespace to return <c>null</c> so it is only run once per
+ /// assembly.
+ /// </summary>
+ public class DefaultNamespaceTypeWrapper : ITypeInfo
+ {
+ /// <summary>
+ /// Construct a TypeWrapper for a specified Type.
+ /// </summary>
+ public DefaultNamespaceTypeWrapper(Type type)
+ {
+ Type = type ?? throw new ArgumentNullException(nameof(type));
+ }
+
+ /// <summary>
+ /// Gets the underlying Type on which this TypeWrapper is based.
+ /// </summary>
+ public Type Type { get; private set; }
+
+ /// <summary>
+ /// Gets the base type of this type as an ITypeInfo
+ /// </summary>
+ public ITypeInfo BaseType
+ {
+ get
+ {
+ var baseType = Type.GetTypeInfo().BaseType;
+
+ return baseType != null
+ ? new TypeWrapper(baseType)
+ : null;
+ }
+ }
+
+ /// <summary>
+ /// Gets the Name of the Type
+ /// </summary>
+ public string Name
+ {
+ get { return Type.Name; }
+ }
+
+ /// <summary>
+ /// Gets the FullName of the Type
+ /// </summary>
+ public string FullName
+ {
+ get { return Type.FullName; }
+ }
+
+ /// <summary>
+ /// Gets the assembly in which the type is declared
+ /// </summary>
+ public Assembly Assembly
+ {
+ get { return Type.GetTypeInfo().Assembly; }
+ }
+
+ /// <summary>
+ /// Gets the namespace of the Type
+ /// </summary>
+ public string Namespace
+ {
+ get { return null; } // LUCENENET: Force this type to be the
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is abstract.
+ /// </summary>
+ public bool IsAbstract
+ {
+ get { return Type.GetTypeInfo().IsAbstract; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type
+ /// </summary>
+ public bool IsGenericType
+ {
+ get { return Type.GetTypeInfo().IsGenericType; }
+ }
+
+ /// <summary>
+ /// Returns true if the Type wrapped is T
+ /// </summary>
+ public bool IsType(Type type)
+ {
+ return Type == type;
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types.
+ /// </summary>
+ public bool ContainsGenericParameters
+ {
+ get { return Type.GetTypeInfo().ContainsGenericParameters; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the Type is a generic Type definition
+ /// </summary>
+ public bool IsGenericTypeDefinition
+ {
+ get { return Type.GetTypeInfo().IsGenericTypeDefinition; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the type is sealed.
+ /// </summary>
+ public bool IsSealed
+ {
+ get { return Type.GetTypeInfo().IsSealed; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this type represents a static class.
+ /// </summary>
+ public bool IsStaticClass => Type.IsStatic();
+
+ /// <summary>
+ /// Get the display name for this type
+ /// </summary>
+ public string GetDisplayName()
+ {
+ return TypeHelper.GetDisplayName(Type);
+ }
+
+ /// <summary>
+ /// Get the display name for an object of this type, constructed with the specified args.
+ /// </summary>
+ public string GetDisplayName(object[] args)
+ {
+ return TypeHelper.GetDisplayName(Type, args);
+ }
+
+ /// <summary>
+ /// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments
+ /// </summary>
+ public ITypeInfo MakeGenericType(Type[] typeArgs)
+ {
+ return new TypeWrapper(Type.MakeGenericType(typeArgs));
+ }
+
+ /// <summary>
+ /// Returns a Type representing a generic type definition from which this Type can be constructed.
+ /// </summary>
+ public Type GetGenericTypeDefinition()
+ {
+ return Type.GetGenericTypeDefinition();
+ }
+
+ /// <summary>
+ /// Returns an array of custom attributes of the specified type applied to this type
+ /// </summary>
+ public T[] GetCustomAttributes<T>(bool inherit) where T : class
+ {
+ return Type.GetAttributes<T>(inherit);
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the type has an attribute of the specified type.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="inherit"></param>
+ /// <returns></returns>
+ public bool IsDefined<T>(bool inherit) where T : class
+ {
+ return Type.HasAttribute<T>(inherit);
+ }
+
+ /// <summary>
+ /// Returns a flag indicating whether this type has a method with an attribute of the specified type.
+ /// </summary>
+ /// <param name="attributeType"></param>
+ /// <returns></returns>
+ public bool HasMethodWithAttribute(Type attributeType)
+ {
+ return Reflect.HasMethodWithAttribute(Type, attributeType);
+ }
+
+ /// <summary>
+ /// Returns an array of IMethodInfos for methods of this Type
+ /// that match the specified flags.
+ /// </summary>
+ public IMethodInfo[] GetMethods(BindingFlags flags)
+ {
+ var methods = Type.GetMethods(flags);
+ var result = new MethodWrapper[methods.Length];
+
+ for (int i = 0; i < methods.Length; i++)
+ result[i] = new MethodWrapper(Type, methods[i]);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Gets the public constructor taking the specified argument Types
+ /// </summary>
+ public ConstructorInfo GetConstructor(Type[] argTypes)
+ {
+ return Type.GetConstructor(argTypes);
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether this Type has a public constructor taking the specified argument Types.
+ /// </summary>
+ public bool HasConstructor(Type[] argTypes)
+ {
+ return GetConstructor(argTypes) != null;
+ }
+
+ /// <summary>
+ /// Construct an object of this Type, using the specified arguments.
+ /// </summary>
+ public object Construct(object[] args)
+ {
+ return Reflect.Construct(Type, args);
+ }
+
+ /// <summary>
+ /// Override ToString() so that error messages in NUnit's own tests make sense
+ /// </summary>
+ public override string ToString()
+ {
+ return Type.ToString();
+ }
+
+ /// <summary>
+ /// Returns all methods declared by this type that have the specified attribute, optionally
+ /// including base classes. Methods from a base class are always returned before methods from a class that
+ /// inherits from it.
+ /// </summary>
+ /// <param name="inherit">Specifies whether to search the fixture type inheritance chain.</param>
+ public IMethodInfo[] GetMethodsWithAttribute<T>(bool inherit) where T : class
+ {
+ if (!inherit)
+ {
+ return Type
+ .GetMethods(/*Reflect.*/AllMembers | BindingFlags.DeclaredOnly)
+ .Where(method => method.IsDefined(typeof(T), inherit: false))
+ .Select(method => new MethodWrapper(Type, method))
+ .ToArray();
+ }
+
+ var methodsByDeclaringType = Type
+ .GetMethods(/*Reflect.*/AllMembers | BindingFlags.FlattenHierarchy) // FlattenHierarchy is complex to replicate by looping over base types with DeclaredOnly.
+ .Where(method => method.IsDefined(typeof(T), inherit: true))
+ .ToLookup(method => method.DeclaringType);
+
+ return Type.TypeAndBaseTypes()
+ .Reverse()
+ .SelectMany(declaringType => methodsByDeclaringType[declaringType].Select(method => new MethodWrapper(declaringType, method)))
+ .ToArray();
+ }
+
+ // From NUnit's Reflect class
+
+ internal static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneRandomSeedInitializer.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneRandomSeedInitializer.cs
new file mode 100644
index 0000000..c715aab
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneRandomSeedInitializer.cs
@@ -0,0 +1,159 @@
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using System;
+using System.Linq;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ internal class LuceneRandomSeedInitializer
+ {
+ #region Messages
+
+ const string RANDOM_SEED_PARAMS_MSG =
+ "\"tests:seed\" parameter must be a valid long hexadecimal value or the word \"random\".";
+
+ #endregion
+
+ private J2N.Randomizer random;
+ private long initialSeed;
+
+ /// <summary>
+ /// Tries to get the random seed from either a <see cref="RandomSeedAttribute"/> or the "tests:seed" system property.
+ /// If niether of these exist, a random seed will be generated and this method returns <c>false</c>;
+ /// </summary>
+ /// <param name="test">The test fixture.</param>
+ /// <param name="seed">The random seed for a new <see cref="Random"/> instance.
+ /// Note this is a subclass of <see cref="Random"/>, since the default doesn't produce consistent results across platforms.</param>
+ /// <returns><c>true</c> if the seed was found in context; <c>false</c> if the seed was generated.</returns>
+ private bool TryGetRandomSeedFromContext(Test test, out long seed)
+ {
+ bool generate;
+ seed = 0;
+ var randomSeedAttribute = (RandomSeedAttribute)test.TypeInfo.Assembly
+ .GetCustomAttributes(typeof(RandomSeedAttribute), inherit: false)
+ .FirstOrDefault();
+ if (randomSeedAttribute != null)
+ {
+ seed = randomSeedAttribute.RandomSeed;
+ generate = false;
+ }
+ else
+ {
+ // For now, ignore anything NUnit3TestAdapter does, because it is messing up repeatable runs.
+ var seedAsString = SystemProperties.GetProperty("tests:seed", null);
+ if (seedAsString is null || "random".Equals(seedAsString, StringComparison.OrdinalIgnoreCase))
+ {
+ generate = true;
+ }
+ else if (J2N.Numerics.Int64.TryParse(seedAsString, 16, out seed))
+ {
+ generate = false;
+ }
+ else
+ {
+ generate = true;
+ test.MakeInvalid(RANDOM_SEED_PARAMS_MSG);
+ }
+ }
+
+ if (generate)
+ {
+ seed = new J2N.Randomizer().NextInt64();
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Initializes the randomized context and seed for the test fixture.
+ /// </summary>
+ /// <param name="fixture">The test fixture.</param>
+ /// <param name="seedOffset">Offset that will be added to the initial seed. This should be different for SetUpFixture and TestFixture attributes
+ /// so they have different seeds that are deterministically based on the initial seed.</param>
+ /// <returns>The randomized context.</returns>
+ public RandomizedContext InitializeTestFixture(Test fixture, Assembly testAssembly, int seedOffset = 0)
+ {
+ if (fixture is null)
+ throw new ArgumentNullException(nameof(fixture));
+
+ TryGetRandomSeedFromContext(fixture, out initialSeed); // NOTE: This sets the initialSeed field for this class.
+ random = new J2N.Randomizer(initialSeed + seedOffset);
+
+ int goodFastHashSeed = (int)initialSeed * 31; // LUCENENET: Multiplying 31 to remove the possility of a collision with the test framework while still using a deterministic number.
+ if (StringHelper.goodFastHashSeed != goodFastHashSeed)
+ StringHelper.goodFastHashSeed = goodFastHashSeed;
+
+ // Now we need to generate the first seed for our test fixture
+ // which will be used during OneTimeSetUp and OneTimeTearDown.
+ // Assumption: The passed in fixture doesn't have any tests added.
+ // The tests are added in a later step to prevent differences in the
+ // result when there are filters applied.
+
+ // Generate a new long value that is the seed for this specific test.
+ return InitializeTestFixture(fixture, new RandomizedContext(fixture, testAssembly, initialSeed, random.NextInt64()));
+ }
+
+ /// <summary>
+ /// Initializes the randomized context for the fixture.
+ /// </summary>
+ /// <param name="fixture">The test fixture.</param>
+ /// <param name="randomizedContext">The randomized context to associate with the fixture.</param>
+ /// <returns>The randomized context.</returns>
+ public RandomizedContext InitializeTestFixture(Test fixture, RandomizedContext randomizedContext)
+ {
+ if (fixture is null)
+ throw new ArgumentNullException(nameof(fixture));
+
+ fixture.Properties.Set(RandomizedContext.RandomizedContextPropertyName, randomizedContext);
+ return randomizedContext;
+ }
+
+ /// <summary>
+ /// Generates random seeds for the given test and all of its children that
+ /// can be cast to <see cref="Test"/>.
+ /// </summary>
+ /// <param name="test"></param>
+ public void GenerateRandomSeeds(Test test)
+ {
+ SetRandomSeeds(test);
+ }
+
+ private void SetRandomSeeds(Test test)
+ {
+ if (test is null)
+ return;
+
+ var testAssembly = test is ParameterizedMethodSuite ? test.Tests[0].TypeInfo.Assembly : test.TypeInfo.Assembly;
+
+ test.Properties.Set(
+ RandomizedContext.RandomizedContextPropertyName,
+ // Generate a new long value that is the seed for this specific test.
+ new RandomizedContext(test, testAssembly, initialSeed, random.NextInt64()));
+
+ if (test.HasChildren)
+ {
+ foreach (ITest child in test.Tests)
+ if (child is Test testChild)
+ SetRandomSeeds(testChild);
+ }
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneSetUpFixtureBuilder.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneSetUpFixtureBuilder.cs
new file mode 100644
index 0000000..81eccfa
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneSetUpFixtureBuilder.cs
@@ -0,0 +1,87 @@
+using NUnit.Framework;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using System;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ /// <summary>
+ /// Custom class to build the assembly-wide setup/teardown. NUnit doesn't scan attributes from dependent assemblies,
+ /// so this is a workaround to inject our initializer so we can get a teardown for the assembly.
+ /// </summary>
+ internal class LuceneSetUpFixtureBuilder
+ {
+ public TestSuite BuildFrom(ITypeInfo typeInfo)
+ {
+ var setUpFixtureType = new DefaultNamespaceTypeWrapper(typeof(LuceneTestCase.SetUpFixture));
+ SetUpFixture fixture = new SetUpFixture(setUpFixtureType);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ {
+ string reason = null;
+ if (!IsValidFixtureType(setUpFixtureType, ref reason))
+ fixture.MakeInvalid(reason);
+ }
+
+ fixture.ApplyAttributesToTest(setUpFixtureType.Type.GetTypeInfo());
+
+ return fixture;
+ }
+
+ #region Helper Methods
+
+ private static bool IsValidFixtureType(ITypeInfo typeInfo, ref string reason)
+ {
+ if (!typeInfo.IsStaticClass)
+ {
+ if (typeInfo.IsAbstract)
+ {
+ reason = string.Format("{0} is an abstract class", typeInfo.FullName);
+ return false;
+ }
+
+ if (!typeInfo.HasConstructor(new Type[0]))
+ {
+ reason = string.Format("{0} does not have a default constructor", typeInfo.FullName);
+ return false;
+ }
+ }
+
+ var invalidAttributes = new Type[] {
+ typeof(SetUpAttribute),
+ typeof(TearDownAttribute)
+ };
+
+ foreach (Type invalidType in invalidAttributes)
+ if (typeInfo.HasMethodWithAttribute(invalidType))
+ {
+ reason = invalidType.Name + $" attribute not allowed in a {nameof(LuceneTestCase.SetUpFixture)}.";
+ return false;
+ }
+
+ return true;
+ }
+
+ #endregion
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.SetUpFixture.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.SetUpFixture.cs
new file mode 100644
index 0000000..1f57513
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.SetUpFixture.cs
@@ -0,0 +1,198 @@
+using J2N.Threading.Atomic;
+using NUnit.Framework;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using System;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ public abstract partial class LuceneTestCase
+ {
+ /// <summary>
+ /// Captures all of the OneTimeSetUp and OneTimeTearDown calls from NUnit and uses reference counting to ensure
+ /// a single <see cref="LuceneTestFrameworkInitializer"/> instance is shared between all <see cref="SetUpFixture"/>
+ /// test wrappers and that each of its <see cref="LuceneTestFrameworkInitializer.Initialize()"/>,
+ /// <see cref="LuceneTestFrameworkInitializer.TestFrameworkSetUp()"/>
+ /// <see cref="LuceneTestFrameworkInitializer.TestFrameworkTearDown()"/> methods are only executed once.
+ /// </summary>
+ internal class SetUpFixture
+ {
+ /// <summary>
+ /// The singleton instance of LuceneTestFrameworkInitializer that is called before and after all tests.
+ /// </summary>
+ private static LuceneTestFrameworkInitializer initializer;
+ private readonly static AtomicInt32 stackCount = new AtomicInt32(0);
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="setUpFixture">The setup wrapper fixture for the current context. This is the top level parent class. It is used to report exceptions.</param>
+ /// <param name="testFixture">The setup fixture for the current tests. This is the original NUnit test fixture.
+ /// We use it's assembly to scan for <see cref="LuceneTestFrameworkInitializer"/> subclasses.</param>
+ public static void EnsureInitialized(Test setUpFixture, Test testFixture)
+ {
+ LazyInitializer.EnsureInitialized(ref initializer, () => Initialize(setUpFixture, testFixture));
+ }
+
+ private static LuceneTestFrameworkInitializer Initialize(Test setUpFixture, Test testFixture)
+ {
+ var initializer = CreateInitializer(setUpFixture, testFixture);
+
+ // Allow the factories to be instantiated first. We do this to allow a
+ // dependency injection step, which can only be done once. No random context
+ // is availble here because we need to load the SystemProperties setup here before
+ // we can read them.
+ initializer.DoInitialize();
+
+ return initializer;
+ }
+
+ [OneTimeSetUp]
+ public void OneTimeSetUpWrapper()
+ {
+ //var fixture = TestExecutionContext.CurrentContext.CurrentTest;
+ if (stackCount.GetAndIncrement() == 0)
+ {
+ // Set up for assembly
+
+ // This is where a global application setup can be done that includes a randomized context,
+ // therefore LuceneTestCase.Random calls are allowed here and are repeatable.
+ initializer.DoTestFrameworkSetUp();
+ }
+ }
+
+ [OneTimeTearDown]
+ public void OneTimeTearDownWrapper()
+ {
+ if (stackCount.DecrementAndGet() == 0)
+ {
+ // Tear down for assembly
+ initializer.DoTestFrameworkTearDown();
+ }
+ }
+
+ private static LuceneTestFrameworkInitializer CreateInitializer(Test wrapperSetUpFixture, Test testFixture)
+ {
+ if (TryGetSetUpFixtureType(testFixture.TypeInfo.Assembly, out ITypeInfo setUpFixture, out Type[] candidateTypes))
+ {
+ // No need for Reflection in this case.
+ if (setUpFixture.Type.Equals(typeof(LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer)))
+ return new LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer();
+
+ if (!IsValidFixtureType(new TypeWrapper(setUpFixture.Type), out string reason))
+ {
+ wrapperSetUpFixture.MakeInvalid(reason);
+ return new LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer();
+ }
+
+ try
+ {
+ return (LuceneTestFrameworkInitializer)Reflect.Construct(setUpFixture.Type);
+ }
+ catch (Exception ex)
+ {
+ var exception = ex is TargetInvocationException ? ex.InnerException : ex;
+
+ wrapperSetUpFixture.MakeInvalid("The LuceneTestFrameworkInitializer subclass could not be instantiated.\n\n" + exception.ToString());
+ return new LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer();
+ }
+ }
+ else
+ {
+ wrapperSetUpFixture.MakeInvalid($"Multiple subclasses of {typeof(LuceneTestFrameworkInitializer).FullName} were found in {testFixture.TypeInfo.Assembly.FullName}. " +
+ $"Only 1 non-abstract subclass is allowed per assembly.\n\n" +
+ $"Types Found:\n" +
+ $"{string.Join("\n ", candidateTypes.Select(t => t.FullName))}");
+ return new LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer();
+ }
+ }
+
+ private static bool TryGetSetUpFixtureType(Assembly assembly, out ITypeInfo setUpFixtureType, out Type[] candidateTypes)
+ {
+ candidateTypes = (from assemblyType in assembly.GetTypes()
+ where typeof(LuceneTestFrameworkInitializer).IsAssignableFrom(assemblyType)
+ && !assemblyType.GetTypeInfo().IsAbstract
+ select assemblyType).ToArray();
+
+ bool result;
+ switch (candidateTypes.Length)
+ {
+ case 0: // The user didn't subclass, so use ours
+ candidateTypes = new Type[] { typeof(LuceneTestFrameworkInitializer.DefaultLuceneTestFrameworkInitializer) };
+ result = true;
+ break;
+ case 1: // The user created 1 subclass, so use theirs
+ result = true;
+ break;
+ default: // The user created multiple subclasses - this is invalid. Return the first type so we can mark it invalid.
+ result = false;
+ break;
+ }
+
+ setUpFixtureType = new DefaultNamespaceTypeWrapper(candidateTypes[0]);
+ return result;
+ }
+
+ private static bool IsValidFixtureType(ITypeInfo typeInfo, out string reason)
+ {
+ if (!typeInfo.IsStaticClass)
+ {
+ if (typeInfo.IsAbstract)
+ {
+ reason = string.Format("{0} is an abstract class", typeInfo.FullName);
+ return false;
+ }
+
+ if (!typeInfo.HasConstructor(new Type[0]))
+ {
+ reason = string.Format("{0} does not have a default constructor", typeInfo.FullName);
+ return false;
+ }
+ }
+
+ var invalidAttributes = new Type[] {
+ typeof(OneTimeSetUpAttribute),
+ typeof(OneTimeTearDownAttribute),
+ typeof(SetUpAttribute),
+ typeof(TearDownAttribute)
+ };
+
+ foreach (Type invalidType in invalidAttributes)
+ if (typeInfo.HasMethodWithAttribute(invalidType))
+ {
+ reason = invalidType.Name + $" not allowed in a {nameof(LuceneTestFrameworkInitializer)} subclass.";
+ return false;
+ }
+
+ if (typeInfo.IsDefined<SetUpFixtureAttribute>(inherit: true))
+ {
+ reason = $"{nameof(SetUpFixtureAttribute)} not allowed on a {nameof(LuceneTestFrameworkInitializer)} subclass.";
+ return false;
+ }
+
+ reason = null;
+ return true;
+ }
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.TestFixtureAttribute.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.TestFixtureAttribute.cs
new file mode 100644
index 0000000..89a7b36
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestCase.TestFixtureAttribute.cs
@@ -0,0 +1,265 @@
+using Lucene.Net.Support;
+using NUnit.Framework;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ #region Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License.
+
+ // Copyright (c) 2021 Charlie Poole, Rob Prouse
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
+ // of this software and associated documentation files (the "Software"), to deal
+ // in the Software without restriction, including without limitation the rights
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ // copies of the Software, and to permit persons to whom the Software is
+ // furnished to do so, subject to the following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included in
+ // all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ // THE SOFTWARE.
+
+ #endregion
+
+ public abstract partial class LuceneTestCase
+ {
+ /// <summary>
+ /// Marks the class as a TestFixture.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
+ public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder2, ITestFixtureData
+ {
+ private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
+
+ #region Constructors
+
+ /// <summary>
+ /// Default constructor
+ /// </summary>
+ public TestFixtureAttribute() : this(new object[0]) { }
+
+ /// <summary>
+ /// Construct with a object[] representing a set of arguments.
+ /// The arguments may later be separated into type arguments and constructor arguments.
+ /// </summary>
+ /// <param name="arguments"></param>
+ public TestFixtureAttribute(params object[] arguments)
+ {
+ RunState = RunState.Runnable;
+ Arguments = arguments ?? new object[] { null };
+ TypeArgs = new Type[0];
+ Properties = new PropertyBag();
+ }
+
+ #endregion
+
+ #region ITestData Members
+
+ /// <summary>
+ /// Gets or sets the name of the test.
+ /// </summary>
+ /// <value>The name of the test.</value>
+ public string TestName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the RunState of this test fixture.
+ /// </summary>
+ public RunState RunState { get; private set; }
+
+ /// <summary>
+ /// The arguments originally provided to the attribute
+ /// </summary>
+ [WritableArray]
+ public object[] Arguments { get; }
+
+ /// <summary>
+ /// Properties pertaining to this fixture
+ /// </summary>
+ public IPropertyBag Properties { get; }
+
+ #endregion
+
+ #region ITestFixtureData Members
+
+ /// <summary>
+ /// Get or set the type arguments. If not set
+ /// explicitly, any leading arguments that are
+ /// Types are taken as type arguments.
+ /// </summary>
+ [WritableArray]
+ public Type[] TypeArgs { get; set; }
+
+ #endregion
+
+ #region Other Properties
+
+ /// <summary>
+ /// Descriptive text for this fixture
+ /// </summary>
+ public string Description
+ {
+ get { return Properties.Get(PropertyNames.Description) as string; }
+ set { Properties.Set(PropertyNames.Description, value); }
+ }
+
+ /// <summary>
+ /// The author of this fixture
+ /// </summary>
+ public string Author
+ {
+ get { return Properties.Get(PropertyNames.Author) as string; }
+ set { Properties.Set(PropertyNames.Author, value); }
+ }
+
+ /// <summary>
+ /// The type that this fixture is testing
+ /// </summary>
+ public Type TestOf
+ {
+ get { return _testOf; }
+ set
+ {
+ _testOf = value;
+ Properties.Set(PropertyNames.TestOf, value.FullName);
+ }
+ }
+ private Type _testOf;
+
+ /// <summary>
+ /// Gets or sets the ignore reason. May set RunState as a side effect.
+ /// </summary>
+ /// <value>The ignore reason.</value>
+ public string Ignore
+ {
+ get { return IgnoreReason; }
+ set { IgnoreReason = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the reason for not running the fixture.
+ /// </summary>
+ /// <value>The reason.</value>
+ public string Reason
+ {
+ get { return this.Properties.Get(PropertyNames.SkipReason) as string; }
+ set { this.Properties.Set(PropertyNames.SkipReason, value); }
+ }
+
+ /// <summary>
+ /// Gets or sets the ignore reason. When set to a non-null
+ /// non-empty value, the test is marked as ignored.
+ /// </summary>
+ /// <value>The ignore reason.</value>
+ public string IgnoreReason
+ {
+ get { return Reason; }
+ set
+ {
+ RunState = RunState.Ignored;
+ Reason = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if explicit; otherwise, <c>false</c>.
+ /// </value>
+ public bool Explicit
+ {
+ get { return RunState == RunState.Explicit; }
+ set { RunState = value ? RunState.Explicit : RunState.Runnable; }
+ }
+
+ /// <summary>
+ /// Gets and sets the category for this fixture.
+ /// May be a comma-separated list of categories.
+ /// </summary>
+ public string Category
+ {
+ get
+ {
+ //return Properties.Get(PropertyNames.Category) as string;
+ var catList = Properties[PropertyNames.Category];
+ if (catList == null)
+ return null;
+
+ switch (catList.Count)
+ {
+ case 0:
+ return null;
+ case 1:
+ return catList[0] as string;
+ default:
+ var cats = new string[catList.Count];
+ int index = 0;
+ foreach (string cat in catList)
+ cats[index++] = cat;
+
+ return string.Join(",", cats);
+ }
+ }
+ set
+ {
+ foreach (string cat in value.Split(new char[] { ',' }))
+ Properties.Add(PropertyNames.Category, cat);
+ }
+ }
+
+ #endregion
+
+ #region IFixtureBuilder Members
+
+ /// <summary>
+ /// Builds a single test fixture from the specified type.
+ /// </summary>
+ public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
+ {
+ yield return _builder.BuildFrom(typeInfo, AlwaysMatchPreFilter.Instance, this);
+ }
+
+ #endregion
+
+ #region IFixtureBuilder2 Members
+
+ /// <summary>
+ /// Builds a single test fixture from the specified type.
+ /// </summary>
+ /// <param name="typeInfo">The type info of the fixture to be used.</param>
+ /// <param name="filter">Filter used to select methods as tests.</param>
+ public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
+ {
+ yield return _builder.BuildFrom(typeInfo, filter, this);
+ }
+
+ #endregion
+ }
+ }
+
+ internal class AlwaysMatchPreFilter : IPreFilter
+ {
+ public static IPreFilter Instance { get; } = new AlwaysMatchPreFilter();
+
+ public bool IsMatch(Type type)
+ {
+ return true;
+ }
+
+ public bool IsMatch(Type type, MethodInfo method)
+ {
+ return true;
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
index 2ad8ccd..167d7f5 100644
--- a/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
+++ b/src/Lucene.Net.TestFramework/Support/Util/LuceneTestFrameworkInitializer.cs
@@ -3,7 +3,6 @@ using Lucene.Net.Configuration;
using NUnit.Framework;
using System;
using System.IO;
-using System.Threading;
namespace Lucene.Net.Util
{
@@ -25,10 +24,11 @@ namespace Lucene.Net.Util
*/
/// <summary>
- /// <see cref="LuceneTestFrameworkInitializer"/> may be subclassed by end users in order to
+ /// <see cref="LuceneTestFrameworkInitializer"/> may be subclassed in order to
/// use standard dependency injection techniques for classes under test. A subclass of <see cref="LuceneTestFrameworkInitializer"/>
- /// will be executed automatically by NUnit. To work properly with the Lucene.NET test framework, the subclass
- /// must be placed outside of all namespaces, which ensures it is only executed 1 time per test assembly.
+ /// will be executed automatically.
+ /// <para/>
+ /// Only one subclass per assembly is allowed, and by convention these subclasses are usually named "Startup".
/// <para/>
/// The following abstract factories can be overridden for testing purposes:
/// <list type="table">
@@ -59,51 +59,128 @@ namespace Lucene.Net.Util
/// </item>
/// </list>
/// <para/>
+ /// Methods are executed one time per assembly, and are executed in the following order:
+ /// <list type="table">
+ /// <listheader>
+ /// <term>Method</term>
+ /// <term>Description</term>
+ /// </listheader>
+ /// <item>
+ /// <term><see cref="Initialize()"/></term>
+ /// <term>Used to set the factories in the above table. In general, dependency injection for the test assembly is
+ /// setup in this method. No randomized context is available.</term>
+ /// </item>
+ /// <item>
+ /// <term><see cref="TestFrameworkSetUp()"/></term>
+ /// <term>Used to set assembly-level test setup. Executed before all tests and class-level setup in the assembly.
+ /// Repeatable randomized content can be generated using the <see cref="Random"/> property.</term>
+ /// </item>
+ /// <item>
+ /// <term><see cref="TestFrameworkTearDown()"/></term>
+ /// <term>Used to tear down assembly-level test setup. Executed after all tests and class-level tear down in the assembly.
+ /// Repeatable randomized content can be generated using the <see cref="Random"/> property.</term>
+ /// </item>
+ /// </list>
+ /// <para/>
/// <b>Example:</b>
/// <code>
- /// // IMPORTANT: Do not put the initializer in a namespace
- /// public class MyTestFrameworkInitializer : LuceneTestFrameworkInitializer
+ /// using RandomizedTesting.Generators;
+ ///
+ /// public class Startup : LuceneTestFrameworkInitializer
/// {
- /// protected override IConfigurationFactory LoadConfigurationFactory()
- /// {
- /// // Inject a custom configuration factory
- /// return new MyConfigurationFactory();
- /// }
- ///
- /// protected override void TestFrameworkSetUp()
+ /// // Run first
+ /// protected override void Initialize()
/// {
/// // Inject a custom configuration factory
/// ConfigurationFactory = new MyConfigurationFactory();
///
/// // Do any additional dependency injection setup here
/// }
+ ///
+ /// // Run before all tests in the assembly and before any class-level setup
+ /// protected overide void TestFrameworkSetUp()
+ /// {
+ /// // Get the random instance for the current context
+ /// var random = Random;
+ ///
+ /// // Generate random content
+ /// string content = random.NextSimpleString();
+ ///
+ /// // Use randomization from LuceneTestCase
+ /// int numberOfDocuments = LuceneTestCase.AtLeast(30);
+ /// }
+ ///
+ /// // Run after all tests in the assembly and after any class-level setup
+ /// protected override void TestFrameworkTearDown()
+ /// {
+ /// // Tear down everything here
+ /// }
/// }
/// </code>
/// </summary>
- [SetUpFixture]
public abstract class LuceneTestFrameworkInitializer
{
- // Initialization target must be static to ensure the initializer only fires one
- // time per application run (even when the static EnsureInitialized() method is called).
- private static object initializationTarget;
+ private bool isInitializing = false;
+ private ICodecFactory codecFactory;
+ private IDocValuesFormatFactory docValuesFormatFactory;
+ private IPostingsFormatFactory postingsFormatFactory;
+ private IConfigurationFactory configurationFactory;
+
+ private readonly AbstractBeforeAfterRule useTempLineDocsFileRule;
+ protected LuceneTestFrameworkInitializer()
+ {
+ codecFactory = new TestCodecFactory();
+ docValuesFormatFactory = new TestDocValuesFormatFactory();
+ postingsFormatFactory = new TestPostingsFormatFactory();
+ configurationFactory = new TestConfigurationFactory();
+
+ useTempLineDocsFileRule = new UseTempLineDocsFileRule();
+ }
// LUCENENET specific factory methods to scan the test framework for codecs/docvaluesformats/postingsformats only once
/// <summary>
/// The <see cref="ICodecFactory"/> implementation to use to load codecs during testing.
/// </summary>
- protected static ICodecFactory CodecFactory { get; set; } = new TestCodecFactory();
+ protected ICodecFactory CodecFactory
+ {
+ get => codecFactory;
+ set
+ {
+ if (!isInitializing)
+ throw new InvalidOperationException("CodecFactory must be set in the Initialize() method.");
+ codecFactory = value ?? throw new ArgumentNullException(nameof(CodecFactory));
+ }
+ }
/// <summary>
/// The <see cref="IDocValuesFormatFactory"/> implementation to use to load doc values during testing.
/// </summary>
- protected static IDocValuesFormatFactory DocValuesFormatFactory { get; set; } = new TestDocValuesFormatFactory();
+ protected IDocValuesFormatFactory DocValuesFormatFactory
+ {
+ get => docValuesFormatFactory;
+ set
+ {
+ if (!isInitializing)
+ throw new InvalidOperationException("DocValuesFormatFactory must be set in the Initialize() method.");
+ docValuesFormatFactory = value ?? throw new ArgumentNullException(nameof(DocValuesFormatFactory));
+ }
+ }
/// <summary>
/// The <see cref="IPostingsFormatFactory"/> implementation to use to load postings formats during testing.
/// </summary>
- protected static IPostingsFormatFactory PostingsFormatFactory { get; set; } = new TestPostingsFormatFactory();
+ protected IPostingsFormatFactory PostingsFormatFactory
+ {
+ get => postingsFormatFactory;
+ set
+ {
+ if (!isInitializing)
+ throw new InvalidOperationException("PostingsFormatFactory must be set in the Initialize() method.");
+ postingsFormatFactory = value ?? throw new ArgumentNullException(nameof(PostingsFormatFactory));
+ }
+ }
/// <summary>
/// The <see cref="IConfigurationFactory"/> implementation to use to load configuration settings during testing.
@@ -111,65 +188,60 @@ namespace Lucene.Net.Util
/// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/</a>.
/// </summary>
[CLSCompliant(false)]
- protected static IConfigurationFactory ConfigurationFactory { get; set; } = new TestConfigurationFactory();
-
- /// <summary>
- /// Overridden in a derived class, can be used to initialize factory instances that are
- /// injected into Lucene.NET during test operations, or perform other one-time initialization
- /// of the test framework setup.
- /// <para/>
- /// NOTE: To initialize 1 time for your entire test library, only create a single derived class
- /// and place it outside of any namespace.
- /// </summary>
- protected virtual void TestFrameworkSetUp()
+ protected IConfigurationFactory ConfigurationFactory
{
- // Runs only once per test framework run before all tests
+ get => configurationFactory;
+ set
+ {
+ if (!isInitializing)
+ throw new InvalidOperationException("ConfigurationFactory must be set in the Initialize() method.");
+ configurationFactory = value ?? throw new ArgumentNullException(nameof(ConfigurationFactory));
+ }
}
-
/// <summary>
- /// Overridden in a derived class, can be used to tear down classes one-time
- /// for the test framework.
+ /// Called by <see cref="LuceneTestCase.SetUpFixture"/> to run the initialization phase for the test assembly.
/// </summary>
- protected virtual void TestFrameworkTearDown()
+ internal void DoInitialize()
{
- // Runs only once per test framework run after all tests
+ try
+ {
+ isInitializing = true;
+ Initialize();
+ isInitializing = false;
+ InitializeStaticState();
+ AfterInitialization(); // Hook for our tests to check the result
+ }
+ catch (Exception ex)
+ {
+ // Write the stack trace so we have something to go on if an error occurs here.
+ throw RuntimeException.Create($"An exception occurred during initialization:\n{ex}", ex);
+ }
}
/// <summary>
- /// When this class is derived in a test assembly, this method is automatically called
- /// by NUnit one time before all tests run.
+ /// Called by <see cref="LuceneTestCase.SetUpFixture"/> to run the one time set up phase for the test assembly.
/// </summary>
- [OneTimeSetUp]
- protected void OneTimeSetUpBeforeTests()
+ internal void DoTestFrameworkSetUp()
{
+ useTempLineDocsFileRule.Before();
+
try
{
TestFrameworkSetUp();
-
- // Initialize of the test factories here, so that doesn't happen
- // when EnsureInitialized() is called.
- Initialize();
-
- // If we can cleanup, unzip the LineDocsFile 1 time for the entire test run,
- // which will dramatically improve performance.
- var temp = LineFileDocs.MaybeCreateTempFile(removeAfterClass: false);
- if (null != temp)
- LuceneTestCase.TestLineDocsFile = temp;
}
catch (Exception ex)
{
// Write the stack trace so we have something to go on if an error occurs here.
- throw RuntimeException.Create($"An exception occurred during OneTimeSetUpBeforeTests:\n{ex}", ex);
+ throw RuntimeException.Create($"An exception occurred during TestFrameworkSetUp:\n{ex}", ex);
}
}
+
/// <summary>
- /// When this class is derived in a test assembly, this method is automatically called
- /// by NUnit one time after all tests run.
+ /// Called by <see cref="LuceneTestCase.SetUpFixture"/> to run the one time tear down phase for the test assembly.
/// </summary>
- [OneTimeTearDown]
- protected void OneTimeTearDownAfterTests()
+ internal void DoTestFrameworkTearDown()
{
try
{
@@ -178,80 +250,123 @@ namespace Lucene.Net.Util
catch (Exception ex)
{
// Write the stack trace so we have something to go on if an error occurs here.
- throw RuntimeException.Create($"An exception occurred during OneTimeTearDownAfterTests:\n{ex}", ex);
+ throw RuntimeException.Create($"An exception occurred during TestFrameworkTearDown:\n{ex}", ex);
}
- // Cleanup our LineDocsFile and reset LuceneTestCase back to its original state.
- var originalLineDocsFile = SystemProperties.GetProperty("tests:linedocsfile", LuceneTestCase.DEFAULT_LINE_DOCS_FILE);
- if (!originalLineDocsFile.Equals(LuceneTestCase.TestLineDocsFile))
- {
- try
- {
- if (!string.IsNullOrEmpty(LuceneTestCase.TestLineDocsFile) && File.Exists(LuceneTestCase.TestLineDocsFile))
- File.Delete(LuceneTestCase.TestLineDocsFile);
- }
- catch { }
- LuceneTestCase.TestLineDocsFile = originalLineDocsFile;
- }
+ useTempLineDocsFileRule.After();
}
/// <summary>
- /// The default implementation of the initializer that is simply used to initialize with the
- /// default test factory implementations.
+ /// Access to the current <see cref="System.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 <see cref="System.Random"/> instance will be
+ /// <b>different</b> when this method is called inside a <see cref="LuceneTestCase.BeforeClass()"/> hook (static
+ /// suite scope) and within <see cref="OneTimeSetUpAttribute"/>/ <see cref="OneTimeTearDownAttribute"/> hooks or test methods.
+ ///
+ /// <para/>The returned instance must not be shared with other threads or cross a single scope's
+ /// boundary. For example, a <see cref="System.Random"/> acquired within a test method shouldn't be reused
+ /// for another test case.
+ ///
+ /// <para/>There is an overhead connected with getting the <see cref="System.Random"/> for a particular context
+ /// and thread. It is better to cache the <see cref="System.Random"/> locally if tight loops with multiple
+ /// invocations are present or create a derivative local <see cref="System.Random"/> for millions of calls
+ /// like this:
+ /// <code>
+ /// Random random = new J2N.Randomizer(Random.NextInt64());
+ /// // tight loop with many invocations.
+ /// </code>
+ /// </summary>
+ protected Random Random => LuceneTestCase.Random;
+
+ /// <summary>
+ /// Overridden in a derived class, provides a way to set <see cref="CodecFactory"/>,
+ /// <see cref="PostingsFormatFactory"/>, <see cref="DocValuesFormatFactory"/> and <see cref="ConfigurationFactory"/> as well as
+ /// other dependency injection setup.
+ /// <para/>
+ /// This method is called only one time per assembly.
+ /// <para/>
+ /// Using the <see cref="Random"/> property here will result in a test failure. To build randomized global setup,
+ /// use <see cref="TestFrameworkSetUp()"/> instead.
/// </summary>
- private class DefaultLuceneTestFrameworkInitializer : LuceneTestFrameworkInitializer { }
+ protected virtual void Initialize()
+ {
+ // Runs only once per test framework before OneTimeSetUp on any tests, and before TestFrameworkSetUp
+ }
/// <summary>
- /// Can be called by an external source to ensure that the test framework has been initialized.
- /// <see cref="Initialize()"/> only occurs if it hasn't already been called by NUnit in a subclass
- /// of this class.
+ /// Overridden in a derived class, can be used to perform one-time initialization
+ /// of the test framework setup.
+ /// <para/>
+ /// Repeatable random setup can be done by calling <see cref="Random"/> or by using methods of <see cref="LuceneTestCase"/>.
+ /// <para/>
+ /// It is not possible to set <see cref="CodecFactory"/>, <see cref="PostingsFormatFactory"/>,
+ /// <see cref="DocValuesFormatFactory"/> and <see cref="ConfigurationFactory"/>
+ /// from this method. Those must be called in <see cref="Initialize()"/>.
/// </summary>
- internal static void EnsureInitialized()
+ protected virtual void TestFrameworkSetUp()
{
- new DefaultLuceneTestFrameworkInitializer().Initialize();
+ // Runs only once per test framework run before all tests
}
- private void Initialize()
+ /// <summary>
+ /// Overridden in a derived class, can be used to perform one-time tear down
+ /// of the test framework setup (whether the setup was done in <see cref="Initialize()"/>
+ /// or <see cref="TestFrameworkSetUp()"/> doesn't matter).
+ /// <para/>
+ /// Repeatable random setup can be done by calling <see cref="Random"/> or by using methods of <see cref="LuceneTestCase"/>.
+ /// </summary>
+ protected virtual void TestFrameworkTearDown()
{
- LazyInitializer.EnsureInitialized(ref initializationTarget, () =>
- {
- // Setup the factories
- ConfigurationSettings.SetConfigurationFactory(ConfigurationFactory);
- Codec.SetCodecFactory(CodecFactory);
- DocValuesFormat.SetDocValuesFormatFactory(DocValuesFormatFactory);
- PostingsFormat.SetPostingsFormatFactory(PostingsFormatFactory);
+ // Runs only once per test framework run after all tests
+ }
- // Enable "asserts" for tests. In Java, these were actual asserts,
- // but in .NET we simply mock this as a boolean static setting that can be
- // toggled on and off, even in release mode. Note this must be done after
- // the ConfigurationFactory is set.
- Lucene.Net.Diagnostics.Debugging.AssertsEnabled = SystemProperties.GetPropertyAsBoolean("assert", true);
+ /// <summary>
+ /// The default implementation of the initializer that is simply used to initialize with the
+ /// default test factory implementations.
+ /// </summary>
+ internal class DefaultLuceneTestFrameworkInitializer : LuceneTestFrameworkInitializer { }
- // Identify NUnit exceptions down in Lucene.Net so they can be ignored in catch blocks that
- // catch Java "Exception" types that do subclass Error (for the ExceptionExtensions.IsException() method).
- Lucene.ExceptionExtensions.NUnitResultStateExceptionType = typeof(NUnit.Framework.ResultStateException);
- Lucene.ExceptionExtensions.NUnitAssertionExceptionType = typeof(NUnit.Framework.AssertionException);
- Lucene.ExceptionExtensions.NUnitMultipleAssertExceptionType = typeof(NUnit.Framework.MultipleAssertException);
- Lucene.ExceptionExtensions.NUnitInconclusiveExceptionType = typeof(NUnit.Framework.InconclusiveException);
- Lucene.ExceptionExtensions.NUnitSuccessExceptionType = typeof(NUnit.Framework.SuccessException);
- Lucene.ExceptionExtensions.NUnitInvalidPlatformException = Type.GetType("NUnit.Framework.Internal.InvalidPlatformException, NUnit.Framework");
+ /// <summary>
+ /// Called after the factory properties have been set (possibly by using dependency injection) which allows customization
+ /// of codecs and system properties during testing.
+ /// </summary>
+ internal void InitializeStaticState()
+ {
+ // Setup the factories
+ ConfigurationSettings.SetConfigurationFactory(ConfigurationFactory);
+ Codec.SetCodecFactory(CodecFactory);
+ DocValuesFormat.SetDocValuesFormatFactory(DocValuesFormatFactory);
+ PostingsFormat.SetPostingsFormatFactory(PostingsFormatFactory);
- // Identify the Debug.Assert() exception so it can be excluded from being swallowed by catch blocks.
- // These types are internal, so we can identify them using Reflection.
- Lucene.ExceptionExtensions.DebugAssertExceptionType =
- // .NET 5/.NET Core 3.x
- Type.GetType("System.Diagnostics.DebugProvider+DebugAssertException, System.Private.CoreLib")
- // .NET Core 2.x
- ?? Type.GetType("System.Diagnostics.Debug+DebugAssertException, System.Private.CoreLib");
- // .NET Framework doesn't throw in this case
+ // Enable "asserts" for tests. In Java, these were actual asserts,
+ // but in .NET we simply mock this as a boolean static setting that can be
+ // toggled on and off, even in release mode. Note this must be done after
+ // the ConfigurationFactory is set.
+ Lucene.Net.Diagnostics.Debugging.AssertsEnabled = SystemProperties.GetPropertyAsBoolean("assert", true);
- AfterInitialization();
+ // Identify NUnit exceptions down in Lucene.Net so they can be ignored in catch blocks that
+ // catch Java "Exception" types that do subclass Error (for the ExceptionExtensions.IsException() method).
+ Lucene.ExceptionExtensions.NUnitResultStateExceptionType = typeof(NUnit.Framework.ResultStateException);
+ Lucene.ExceptionExtensions.NUnitAssertionExceptionType = typeof(NUnit.Framework.AssertionException);
+ Lucene.ExceptionExtensions.NUnitMultipleAssertExceptionType = typeof(NUnit.Framework.MultipleAssertException);
+ Lucene.ExceptionExtensions.NUnitInconclusiveExceptionType = typeof(NUnit.Framework.InconclusiveException);
+ Lucene.ExceptionExtensions.NUnitSuccessExceptionType = typeof(NUnit.Framework.SuccessException);
+ Lucene.ExceptionExtensions.NUnitInvalidPlatformException = Type.GetType("NUnit.Framework.Internal.InvalidPlatformException, NUnit.Framework");
- return new object(); // Placeholder to indicate our initializer has been run already
- });
+ // Identify the Debug.Assert() exception so it can be excluded from being swallowed by catch blocks.
+ // These types are internal, so we can identify them using Reflection.
+ Lucene.ExceptionExtensions.DebugAssertExceptionType =
+ // .NET 5/.NET Core 3.x
+ Type.GetType("System.Diagnostics.DebugProvider+DebugAssertException, System.Private.CoreLib")
+ // .NET Core 2.x
+ ?? Type.GetType("System.Diagnostics.Debug+DebugAssertException, System.Private.CoreLib");
+ // .NET Framework doesn't throw in this case
}
- internal virtual void AfterInitialization() // LUCENENET TODO: Consider making this public
+ /// <summary>
+ /// Checkpoint to allow tests to check the results of <see cref="InitializeStaticState()"/>.
+ /// </summary>
+ internal virtual void AfterInitialization() // Called only by tests
{
}
}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/NUnitTestFixtureBuilder.cs b/src/Lucene.Net.TestFramework/Support/Util/NUnitTestFixtureBuilder.cs
new file mode 100644
index 0000000..b3734a0
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/NUnitTestFixtureBuilder.cs
@@ -0,0 +1,474 @@
+using NUnit.Framework;
+using NUnit.Framework.Interfaces;
+using NUnit.Framework.Internal;
+using NUnit.Framework.Internal.Builders;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ #region Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License.
+
+ // Copyright (c) 2021 Charlie Poole, Rob Prouse
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
+ // of this software and associated documentation files (the "Software"), to deal
+ // in the Software without restriction, including without limitation the rights
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ // copies of the Software, and to permit persons to whom the Software is
+ // furnished to do so, subject to the following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included in
+ // all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ // THE SOFTWARE.
+
+ #endregion
+
+ /// <summary>
+ /// NUnitTestFixtureBuilder is able to build a fixture given
+ /// a class marked with a TestFixtureAttribute or an unmarked
+ /// class containing test methods. In the first case, it is
+ /// called by the attribute and in the second directly by
+ /// NUnitSuiteBuilder.
+ /// </summary>
+ internal class NUnitTestFixtureBuilder
+ {
+ const int SETUP_FIXTURE_SEED_OFFSET = 7;
+ const int TEST_FIXTURE_SEED_OFFSET = 3;
+
+ private static RandomizedContext setUpFixtureRandomizedContext = null;
+
+ #region Messages
+
+ const string NO_TYPE_ARGS_MSG =
+ "Fixture type contains generic parameters. You must either provide Type arguments or specify constructor arguments that allow NUnit to deduce the Type arguments.";
+
+ const string PARALLEL_NOT_ALLOWED_MSG =
+ "ParallelizableAttribute is only allowed on test methods and fixtures";
+
+ #endregion
+
+ #region Instance Fields
+
+ private readonly ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder();
+ private readonly LuceneSetUpFixtureBuilder _setUpFixtureBuilder = new LuceneSetUpFixtureBuilder();
+ private readonly LuceneRandomSeedInitializer _randomSeedInitializer = new LuceneRandomSeedInitializer();
+
+ #endregion
+
+ #region Public Methods
+
+ /// <summary>
+ /// Build a TestFixture from type provided. A non-null TestSuite
+ /// must always be returned, since the method is generally called
+ /// because the user has marked the target class as a fixture.
+ /// If something prevents the fixture from being used, it should
+ /// be returned nonetheless, labelled as non-runnable.
+ /// </summary>
+ /// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param>
+ /// <param name="filter">Filter used to select methods as tests.</param>
+ /// <returns>A TestSuite object or one derived from TestSuite.</returns>
+ // TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
+ public TestSuite BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
+ {
+ // Build our custom SetUpFixture to get the NUnit runner to initialize us
+ // even though we don't own the test assembly.
+ var setUpFixture = _setUpFixtureBuilder.BuildFrom(typeInfo);
+ var fixture = new TestFixture(typeInfo);
+
+ SetUpRandomizedContext(setUpFixture, fixture);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ CheckTestFixtureIsValid(fixture);
+
+ fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
+
+ AddTestCasesToFixture(fixture, filter);
+
+ setUpFixture.Add(fixture);
+ return setUpFixture;
+ }
+
+ /// <summary>
+ /// Overload of BuildFrom called by tests that have arguments.
+ /// Builds a fixture using the provided type and information
+ /// in the ITestFixtureData object.
+ /// </summary>
+ /// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param>
+ /// <param name="filter">Filter used to select methods as tests.</param>
+ /// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param>
+ /// <returns></returns>
+ public TestSuite BuildFrom(ITypeInfo typeInfo, IPreFilter filter, ITestFixtureData testFixtureData)
+ {
+ //Guard.ArgumentNotNull(testFixtureData, nameof(testFixtureData));
+ if (testFixtureData is null)
+ throw new ArgumentNullException(nameof(testFixtureData));
+
+ object[] arguments = testFixtureData.Arguments;
+
+ if (typeInfo.ContainsGenericParameters)
+ {
+ Type[] typeArgs = testFixtureData.TypeArgs;
+ if (typeArgs == null || typeArgs.Length == 0)
+ {
+ int cnt = 0;
+ foreach (object o in arguments)
+ if (o is Type) cnt++;
+ else break;
+
+ typeArgs = new Type[cnt];
+ for (int i = 0; i < cnt; i++)
+ typeArgs[i] = (Type)arguments[i];
+
+ if (cnt > 0)
+ {
+ object[] args = new object[arguments.Length - cnt];
+ for (int i = 0; i < args.Length; i++)
+ args[i] = arguments[cnt + i];
+
+ arguments = args;
+ }
+ }
+
+ if (typeArgs.Length > 0 ||
+ TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs))
+ {
+ typeInfo = typeInfo.MakeGenericType(typeArgs);
+ }
+ }
+
+ // Build our custom SetUpFixture to get the NUnit runner to initialize us
+ // even though we don't own the test assembly.
+ var setUpFixture = _setUpFixtureBuilder.BuildFrom(typeInfo);
+ var fixture = new TestFixture(typeInfo, arguments);
+
+ SetUpRandomizedContext(setUpFixture, fixture);
+
+ string name = fixture.Name;
+
+ if (testFixtureData.TestName != null)
+ {
+ fixture.Name = testFixtureData.TestName;
+ }
+ else
+ {
+ //var argDisplayNames = (testFixtureData as NUnit.Framework.Internal.TestParameters)?.ArgDisplayNames;
+ var testParameters = testFixtureData as NUnit.Framework.Internal.TestParameters;
+ string[] argDisplayNames = null;
+ if (testParameters != null)
+ {
+ // Hack so we can call the same internal field that NUnit does
+ BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
+ FieldInfo field = typeof(NUnit.Framework.Internal.TestParameters).GetField("_argDisplayNames", bindFlags);
+ argDisplayNames = (string[])field.GetValue(testFixtureData);
+ }
+ if (argDisplayNames != null)
+ {
+ fixture.Name = typeInfo.GetDisplayName();
+ if (argDisplayNames.Length != 0)
+ fixture.Name += '(' + string.Join(", ", argDisplayNames) + ')';
+ }
+ else if (arguments != null && arguments.Length > 0)
+ {
+ fixture.Name = typeInfo.GetDisplayName(arguments);
+ }
+ }
+
+ if (fixture.Name != name) // name was changed
+ {
+ string nspace = typeInfo.Namespace;
+ fixture.FullName = nspace != null && nspace != ""
+ ? nspace + "." + fixture.Name
+ : fixture.Name;
+ }
+
+ if (fixture.RunState != RunState.NotRunnable)
+ fixture.RunState = testFixtureData.RunState;
+
+ foreach (string key in testFixtureData.Properties.Keys)
+ foreach (object val in testFixtureData.Properties[key])
+ fixture.Properties.Add(key, val);
+
+ if (fixture.RunState != RunState.NotRunnable)
+ CheckTestFixtureIsValid(fixture);
+
+ fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
+
+ AddTestCasesToFixture(fixture, filter);
+
+ setUpFixture.Add(fixture);
+ return setUpFixture;
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ /// <summary>
+ /// Sets up the randomized context for both the set up fixture and the test fixture.
+ /// We use the same instance for every set up fixture in the assembly, but each test
+ /// fixture has its own distinct randomized context instance.
+ /// </summary>
+ /// <param name="setUpFixture">The setup fixture.</param>
+ /// <param name="testFixture">The test fixture.</param>
+ private void SetUpRandomizedContext(Test setUpFixture, Test testFixture)
+ {
+ // Setup the factories so we can read the random seed from the system properties
+ LuceneTestCase.SetUpFixture.EnsureInitialized(setUpFixture, testFixture);
+
+ // Reuse the same randomized context for each setup fixture instance, since these all need to report
+ // the same seed. Note that setUpFixtureRandomizedContext is static, so we do this once per assembly.
+ if (setUpFixtureRandomizedContext is null)
+ setUpFixtureRandomizedContext = _randomSeedInitializer.InitializeTestFixture(setUpFixture, testFixture.TypeInfo.Assembly, SETUP_FIXTURE_SEED_OFFSET);
+ else
+ _randomSeedInitializer.InitializeTestFixture(setUpFixture, setUpFixtureRandomizedContext);
+
+ _randomSeedInitializer.InitializeTestFixture(testFixture, testFixture.TypeInfo.Assembly, TEST_FIXTURE_SEED_OFFSET);
+ }
+
+ /// <summary>
+ /// Method to add test cases to the newly constructed fixture.
+ /// </summary>
+ private void AddTestCasesToFixture(TestFixture fixture, IPreFilter filter)
+ {
+ // TODO: Check this logic added from Neil's build.
+ if (fixture.TypeInfo.ContainsGenericParameters)
+ {
+ fixture.MakeInvalid(NO_TYPE_ARGS_MSG);
+ return;
+ }
+
+ // We sort the methods in a deterministic order, since BuildTestCase() will invoke the
+ // Randomizer to create seeds for each test. We want those seeds to be deterministically repeatable
+ // so we can re-run the same conditions by manually fixing the Randomizer.InitialSeed.
+ var methods = new SortedSet<IMethodInfo>(fixture.TypeInfo.GetMethods(
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static),
+ MethodInfoComparer.Default);
+
+ foreach (IMethodInfo method in methods)
+ {
+ // Generate the seed whether or not we use a filter to ensure we invoke the Randomizer to
+ // move to the next random test seed (a test should always get the same seed in the sequence).
+ Test test = BuildTestCase(method, fixture);
+
+ _randomSeedInitializer.GenerateRandomSeeds(test);
+
+ if (filter.IsMatch(fixture.TypeInfo.Type, method.MethodInfo))
+ {
+ if (test != null)
+ fixture.Add(test);
+ else // it's not a test, check for disallowed attributes
+ if (method.MethodInfo.HasAttribute<ParallelizableAttribute>(false))
+ fixture.MakeInvalid(PARALLEL_NOT_ALLOWED_MSG);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Method to create a test case from a MethodInfo and add
+ /// it to the fixture being built. It first checks to see if
+ /// any global TestCaseBuilder addin wants to build the
+ /// test case. If not, it uses the internal builder
+ /// collection maintained by this fixture builder.
+ ///
+ /// The default implementation has no test case builders.
+ /// Derived classes should add builders to the collection
+ /// in their constructor.
+ /// </summary>
+ /// <param name="method">The method for which a test is to be created</param>
+ /// <param name="suite">The test suite being built.</param>
+ /// <returns>A newly constructed Test</returns>
+ private Test BuildTestCase(IMethodInfo method, TestSuite suite)
+ {
+ return _testBuilder.CanBuildFrom(method, suite)
+ ? _testBuilder.BuildFrom(method, suite)
+ : null;
+ }
+
+ private static void CheckTestFixtureIsValid(TestFixture fixture)
+ {
+ if (fixture.TypeInfo.ContainsGenericParameters)
+ {
+ fixture.MakeInvalid(NO_TYPE_ARGS_MSG);
+ }
+ else if (!fixture.TypeInfo.IsStaticClass)
+ {
+ Type[] argTypes = /*Reflect.*/GetTypeArray(fixture.Arguments);
+
+ if (!/*Reflect.*/GetConstructors(fixture.TypeInfo.Type, argTypes).Any())
+ {
+ fixture.MakeInvalid("No suitable constructor was found");
+ }
+ }
+ }
+
+ /// <summary>
+ /// Returns an array of types from an array of objects.
+ /// Differs from <see cref="M:System.Type.GetTypeArray(System.Object[])"/> by returning <see langword="null"/>
+ /// for null elements rather than throwing <see cref="ArgumentNullException"/>.
+ /// </summary>
+ internal static Type[] GetTypeArray(object[] objects)
+ {
+ Type[] types = new Type[objects.Length];
+ int index = 0;
+ foreach (object o in objects)
+ {
+ types[index++] = o?.GetType();
+ }
+ return types;
+ }
+
+ /// <summary>
+ /// Gets the constructors to which the specified argument types can be coerced.
+ /// </summary>
+ internal static IEnumerable<ConstructorInfo> GetConstructors(Type type, Type[] matchingTypes)
+ {
+ return type
+ .GetConstructors()
+ .Where(c => c.GetParameters().ParametersMatch(matchingTypes));
+ }
+
+ #endregion
+ }
+
+ internal class MethodInfoComparer : IComparer<IMethodInfo>
+ {
+ private MethodInfoComparer() { } // LUCENENT: Made into singleton
+
+ public static IComparer<IMethodInfo> Default { get; } = new MethodInfoComparer();
+
+ public int Compare(IMethodInfo x, IMethodInfo y)
+ {
+ StringComparer stringComparer = StringComparer.Ordinal;
+
+ int nameCompare = stringComparer.Compare(x.Name, y.Name);
+ if (nameCompare != 0)
+ return nameCompare;
+
+ var xParameters = x.GetParameters();
+ var yParameters = y.GetParameters();
+
+ if (xParameters.Length > yParameters.Length)
+ return 1;
+ if (xParameters.Length < yParameters.Length)
+ return -1;
+
+ for (int i = 0; i < xParameters.Length; i++)
+ {
+ var px = xParameters[i];
+ var py = xParameters[i];
+
+ int parameterTypeCompare = stringComparer.Compare(px.ParameterType.FullName, py.ParameterType.FullName);
+ if (parameterTypeCompare != 0)
+ return parameterTypeCompare;
+ }
+
+ return 0;
+ }
+ }
+
+ internal static class Extensions
+ {
+ // From NUnit's Reflect class
+
+ /// <summary>
+ /// Determines if the given types can be coerced to match the given parameters.
+ /// </summary>
+ internal static bool ParametersMatch(this ParameterInfo[] pinfos, Type[] ptypes)
+ {
+ if (pinfos.Length != ptypes.Length)
+ return false;
+
+ for (int i = 0; i < pinfos.Length; i++)
+ {
+ if (!ptypes[i].CanImplicitlyConvertTo(pinfos[i].ParameterType))
+ return false;
+ }
+ return true;
+ }
+
+ // §6.1.2 (Implicit numeric conversions) of the specification
+ private static readonly Dictionary<Type, List<Type>> convertibleValueTypes = new Dictionary<Type, List<Type>>() {
+ { typeof(decimal), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
+ { typeof(double), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
+ { typeof(float), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
+ { typeof(ulong), new List<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
+ { typeof(long), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
+ { typeof(uint), new List<Type> { typeof(byte), typeof(ushort), typeof(char) } },
+ { typeof(int), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
+ { typeof(ushort), new List<Type> { typeof(byte), typeof(char) } },
+ { typeof(short), new List<Type> { typeof(byte) } }
+ };
+
+ /// <summary>
+ /// Determines whether the current type can be implicitly converted to the specified type.
+ /// </summary>
+ internal static bool CanImplicitlyConvertTo(this Type from, Type to)
+ {
+ if (to.IsAssignableFrom(from))
+ return true;
+
+ // Look for the marker that indicates from was null
+ if (from == null && (to.GetTypeInfo().IsClass || to.FullName.StartsWith("System.Nullable")))
+ return true;
+
+ if (convertibleValueTypes.ContainsKey(to) && convertibleValueTypes[to].Contains(from))
+ return true;
+
+ return from
+ .GetMethods(BindingFlags.Public | BindingFlags.Static)
+ .Any(m => m.ReturnType == to && m.Name == "op_Implicit");
+ }
+
+ internal static IEnumerable<Type> TypeAndBaseTypes(this Type type)
+ {
+ for (; type != null; type = type.GetTypeInfo().BaseType)
+ {
+ yield return type;
+ }
+ }
+
+
+ // From NUnit's Extensions class
+
+ public static bool IsStatic(this Type type)
+ {
+ return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
+ }
+
+ public static bool HasAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit)
+ {
+ return attributeProvider.IsDefined(typeof(T), inherit);
+ }
+
+ public static bool HasAttribute<T>(this Type type, bool inherit)
+ {
+ return ((ICustomAttributeProvider)type.GetTypeInfo()).HasAttribute<T>(inherit);
+ }
+
+ public static T[] GetAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
+ {
+ return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
+ }
+
+ public static T[] GetAttributes<T>(this Assembly assembly) where T : class
+ {
+ return assembly.GetAttributes<T>(inherit: false);
+ }
+
+ public static T[] GetAttributes<T>(this Type type, bool inherit) where T : class
+ {
+ return ((ICustomAttributeProvider)type.GetTypeInfo()).GetAttributes<T>(inherit);
+ }
+ }
+
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/RandomSeedAttribute.cs b/src/Lucene.Net.TestFramework/Support/Util/RandomSeedAttribute.cs
new file mode 100644
index 0000000..9b15af1
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/RandomSeedAttribute.cs
@@ -0,0 +1,52 @@
+using System;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ /// <summary>
+ /// Specifies a random seed to use when running tests. This allows specific test conditions to be repeated for debugging purposes.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
+ public sealed class RandomSeedAttribute : System.Attribute
+ {
+ /// <summary>
+ /// Construct a <see cref="RandomSeedAttribute"/> with a specific random seed value.
+ /// </summary>
+ /// <param name="randomSeed">A <see cref="long"/> value that represents the initial random seed to use to run the tests.</param>
+ public RandomSeedAttribute(long randomSeed)
+ {
+ RandomSeed = randomSeed;
+ }
+
+ /// <summary>
+ /// Construct a <see cref="RandomSeedAttribute"/> with a specific random seed value.
+ /// </summary>
+ /// <param name="randomSeed">A <see cref="ulong"/> value that represents the initial random seed to use to run the tests.</param>
+ [CLSCompliant(false)]
+ public RandomSeedAttribute(ulong randomSeed)
+ {
+ RandomSeed = unchecked((long)randomSeed);
+ }
+
+ /// <summary>
+ /// The random seed value.
+ /// </summary>
+ public long RandomSeed { get; private set; }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/RandomizedContext.cs b/src/Lucene.Net.TestFramework/Support/Util/RandomizedContext.cs
new file mode 100644
index 0000000..8e68126
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/RandomizedContext.cs
@@ -0,0 +1,118 @@
+using J2N;
+using NUnit.Framework.Internal;
+using System;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ /// <summary>
+ /// Extensions to NUnit's test context for randomized testing.
+ /// </summary>
+ internal class RandomizedContext
+ {
+ internal const string RandomizedContextPropertyName = "RandomizedContext";
+
+ private Random randomGenerator;
+ private readonly Test currentTest;
+ private readonly Assembly currentTestAssembly;
+ private readonly long randomSeed;
+ private readonly string randomSeedAsHex;
+ private readonly long testSeed;
+
+ /// <summary>
+ /// Initializes the randomized context.
+ /// </summary>
+ /// <param name="currentTest">The test or test fixture for the context.</param>
+ /// <param name="currentTestAssembly">The test assembly. This can be used in <see cref="LuceneTestFrameworkInitializer"/> to scan the test assembly for attributes.</param>
+ /// <param name="randomSeed">The initial random seed that can be used to regenerate this context.</param>
+ /// <param name="testSeed">The individual test's seed to regenerate the test.</param>
+ public RandomizedContext(Test currentTest, Assembly currentTestAssembly, long randomSeed, long testSeed)
+ {
+ this.currentTest = currentTest ?? throw new ArgumentNullException(nameof(currentTest));
+ this.currentTestAssembly = currentTestAssembly ?? throw new ArgumentNullException(nameof(currentTestAssembly));
+ this.randomSeed = randomSeed;
+ this.randomSeedAsHex = "0x" + randomSeed.ToHexString();
+ this.testSeed = testSeed;
+ }
+
+ /// <summary>
+ /// Gets the initial seed that was used to initialize the current context.
+ /// </summary>
+ public long RandomSeed => randomSeed;
+
+ /// <summary>
+ /// Gets the initial seed as a hexadecimal string for display/configuration purposes.
+ /// </summary>
+ public string RandomSeedAsHex => randomSeedAsHex;
+
+ /// <summary>
+ /// The current test for this context.
+ /// </summary>
+ public Test CurrentTest => currentTest;
+
+ /// <summary>
+ /// The current test assembly, which may be used to scan the assembly for custom attributes.
+ /// </summary>
+ public Assembly CurrentTestAssembly => currentTestAssembly;
+
+ /// <summary>
+ /// The random seed for this test's <see cref="RandomGenerator"/>.
+ /// </summary>
+ public long TestSeed => testSeed;
+
+ /// <summary>
+ /// Gets the RandomGenerator specific to this Test. This random generator implementatation
+ /// is not platform specific, so random numbers generated on one operating system will work on another.
+ /// <para/>
+ /// NOTE: NUnit doesn't currently set the <see cref="Test.Seed"/> property for the test fixtures
+ /// when using their built-in <see cref="NUnit.Framework.TestFixtureAttribute"/> or
+ /// <see cref="NUnit.Framework.SetUpFixtureAttribute"/>. This means the seed will always be 0
+ /// when using this property from <see cref="NUnit.Framework.OneTimeSetUpAttribute"/> or
+ /// <see cref="NUnit.Framework.OneTimeTearDownAttribute"/>, so it cannot be relied upon to create
+ /// random test data in these cases. Using the <see cref="LuceneTestCase.TestFixtureAttribute"/>
+ /// will set the seed properly and make it possible to repeat the result.
+ /// </summary>
+ public Random RandomGenerator
+ {
+ get
+ {
+ if (randomGenerator == null)
+ randomGenerator = new J2N.Randomizer(testSeed);
+ return randomGenerator;
+ }
+ }
+
+ /// <summary>
+ /// Gets the randomized context for the current test or test fixture.
+ /// </summary>
+ public static RandomizedContext CurrentContext
+ {
+ get
+ {
+ var currentTest = TestExecutionContext.CurrentContext.CurrentTest;
+
+ if (currentTest.Properties.ContainsKey(RandomizedContextPropertyName))
+ return (RandomizedContext)currentTest.Properties.Get(RandomizedContextPropertyName);
+
+ return null; // We are out of random context and cannot respond with results that are repeatable.
+ }
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs b/src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileAttribute.cs
similarity index 68%
copy from src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs
copy to src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileAttribute.cs
index 5fe37d8..fe805bb 100644
--- a/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs
+++ b/src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileAttribute.cs
@@ -1,3 +1,5 @@
+using System;
+
namespace Lucene.Net.Util
{
/*
@@ -18,17 +20,11 @@ namespace Lucene.Net.Util
*/
/// <summary>
- /// LUCENENET specific for mimicking the JUnit rule functionality.
- /// We simplify things by just running the rules inside LuceneTestCase.
+ /// Specifies to extract the <see cref="LineFileDocs"/> to a temp directory and use the same file for the entire assembly.
+ /// The file path can be obtained from the to <see cref="LuceneTestCase.TestLineDocsFile"/> property.
/// </summary>
- public abstract class AbstractBeforeAfterRule
+ [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+ public class UseTempLineDocsFileAttribute : System.Attribute
{
- public virtual void Before(LuceneTestCase testInstance)
- {
- }
-
- public virtual void After(LuceneTestCase testInstance)
- {
- }
}
}
diff --git a/src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileRule.cs b/src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileRule.cs
new file mode 100644
index 0000000..3f87cb8
--- /dev/null
+++ b/src/Lucene.Net.TestFramework/Support/Util/UseTempLineDocsFileRule.cs
@@ -0,0 +1,84 @@
+using System.IO;
+using System.Reflection;
+
+namespace Lucene.Net.Util
+{
+ /*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+ /// <summary>
+ /// LUCENENET specific rule for extracting the LineFileDocs file (or embedded resource) only once
+ /// per assembly if the <see cref="UseTempLineDocsFileAttribute"/>.
+ /// </summary>
+ internal class UseTempLineDocsFileRule : AbstractBeforeAfterRule
+ {
+ private bool lineFileDocsExtracted;
+
+ private bool IsEnabled()
+ {
+ bool enabled = false;
+ Assembly assembly = RandomizedContext.CurrentContext.CurrentTestAssembly;
+
+ if (assembly.HasAttribute<UseTempLineDocsFileAttribute>(inherit: true))
+ enabled = true;
+ else
+ {
+ foreach (var type in assembly.GetTypes())
+ {
+ if (!type.IsClass || type.IsAbstract)
+ continue;
+ if (type.HasAttribute<UseTempLineDocsFileAttribute>(inherit: true))
+ {
+ enabled = true;
+ break;
+ }
+ }
+ }
+ return enabled;
+ }
+
+ public override void Before()
+ {
+ if (IsEnabled())
+ {
+ // If we can cleanup, unzip the LineDocsFile 1 time for the entire test run,
+ // which will dramatically improve performance.
+ var temp = LineFileDocs.MaybeCreateTempFile(removeAfterClass: false);
+ if (null != temp)
+ {
+ lineFileDocsExtracted = true;
+ LuceneTestCase.TestLineDocsFile = temp;
+ }
+ }
+ }
+
+ public override void After()
+ {
+ if (lineFileDocsExtracted)
+ {
+ // Cleanup our LineDocsFile and reset LuceneTestCase back to its original state.
+ try
+ {
+ if (!string.IsNullOrEmpty(LuceneTestCase.TestLineDocsFile) && File.Exists(LuceneTestCase.TestLineDocsFile))
+ File.Delete(LuceneTestCase.TestLineDocsFile);
+ }
+ catch { }
+ LuceneTestCase.TestLineDocsFile = SystemProperties.GetProperty("tests:linedocsfile", LuceneTestCase.DEFAULT_LINE_DOCS_FILE);
+ }
+ }
+ }
+}
diff --git a/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs b/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs
index 5fe37d8..89348c5 100644
--- a/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs
+++ b/src/Lucene.Net.TestFramework/Util/AbstractBeforeAfterRule.cs
@@ -1,4 +1,4 @@
-namespace Lucene.Net.Util
+namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -23,11 +23,11 @@ namespace Lucene.Net.Util
/// </summary>
public abstract class AbstractBeforeAfterRule
{
- public virtual void Before(LuceneTestCase testInstance)
+ public virtual void Before()
{
}
- public virtual void After(LuceneTestCase testInstance)
+ public virtual void After()
{
}
}
diff --git a/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs b/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
index 79057d3..209cac0 100644
--- a/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
+++ b/src/Lucene.Net.TestFramework/Util/LineFileDocs.cs
@@ -60,12 +60,12 @@ namespace Lucene.Net.Util
}
public LineFileDocs(Random random)
- : this(random, LuceneTestCase.TempLineDocsFile ?? LuceneTestCase.TestLineDocsFile, true)
+ : this(random, LuceneTestCase.TestLineDocsFile, true)
{
}
public LineFileDocs(Random random, bool useDocValues)
- : this(random, LuceneTestCase.TempLineDocsFile ?? LuceneTestCase.TestLineDocsFile, useDocValues)
+ : this(random, LuceneTestCase.TestLineDocsFile, useDocValues)
{
}
diff --git a/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs b/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
index 33f0b37..99b4d81 100644
--- a/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
+++ b/src/Lucene.Net.TestFramework/Util/LuceneTestCase.cs
@@ -48,7 +48,7 @@ using After = NUnit.Framework.TearDownAttribute;
using OneTimeSetUp = NUnit.Framework.OneTimeSetUpAttribute;
using OneTimeTearDown = NUnit.Framework.OneTimeTearDownAttribute;
using Test = NUnit.Framework.TestAttribute;
-using TestFixture = NUnit.Framework.TestFixtureAttribute;
+//using TestFixture = Lucene.Net.Util.LuceneTestCase.TestFixtureAttribute;
using AssumptionViolatedException = NUnit.Framework.InconclusiveException;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
@@ -548,8 +548,6 @@ namespace Lucene.Net.Util
{
public SystemPropertyData()
{
- // LUCENENET: Always ensure the system properties are initailized before any attempt to read them.
- LuceneTestFrameworkInitializer.EnsureInitialized();
Verbose = SystemProperties.GetPropertyAsBoolean("tests:verbose", // LUCENENET specific - reformatted with :
#if DEBUG
true
@@ -696,20 +694,10 @@ namespace Lucene.Net.Util
public static string TestLineDocsFile // LUCENENET specific - changed from field to property, and renamed
{
get => TestProperties.TestLineDocsFile;
- set => TestProperties.TestLineDocsFile = value;
+ internal set => TestProperties.TestLineDocsFile = value;
}
/// <summary>
- /// The line file used by <see cref="LineFileDocs"/> to override <see cref="TestLineDocsFile"/> if it exists (points to an unzipped file).</summary>
- // LUCENENET specific - used to unzip the LineDocsFile at the class level so we don't have to do it in every test.
- internal static string TempLineDocsFile { get; set; }
-
- /// <summary>
- /// Whether to use the temporary line docs file. This should be set to <c>true</c> when a subclass requires <see cref="LineFileDocs"/>.</summary>
- // LUCENENET specific - used to unzip the LineDocsFile at the class level so we don't have to do it in every test.
- internal bool UseTempLineDocsFile { get; set; }
-
- /// <summary>
/// Whether or not <see cref="NightlyAttribute"/> tests should run. </summary>
public static bool TestNightly => TestProperties.TestNightly; // LUCENENET specific - changed from field to property, and renamed
@@ -985,6 +973,9 @@ namespace Lucene.Net.Util
// LUCENENET: Printing out randomized context regardless
// of whether verbose is enabled (since we need it for debugging,
// but the verbose output can crash tests).
+ Console.Write("RandomSeed: ");
+ Console.WriteLine(RandomizedContext.CurrentContext.RandomSeedAsHex);
+
Console.Write("Culture: ");
Console.WriteLine(ClassEnvRule.locale.Name);
@@ -1033,6 +1024,28 @@ namespace Lucene.Net.Util
/* LUCENENET TODO: Not sure how to convert these
ParentChainCallRule.TeardownCalled = true;
*/
+#if TESTFRAMEWORK_NUNIT
+ TestResult result = TestExecutionContext.CurrentContext.CurrentResult;
+ string message;
+ if (result.ResultState == ResultState.Failure || result.ResultState == ResultState.Error)
+ {
+ message = result.Message + $"\n\nTo reproduce this test result:\n\n" +
+ $"Option 1:\n\n" +
+ $" Apply the following assembly-level attributes:\n\n" +
+ $"[assembly: Lucene.Net.Util.RandomSeed({RandomizedContext.CurrentContext.RandomSeedAsHex}L)]\n" +
+ $"[assembly: NUnit.Framework.SetCulture(\"{Thread.CurrentThread.CurrentCulture.Name}\")]\n\n" +
+ $"Option 2:\n\n" +
+ $" Use the following .runsettings file:\n\n" +
+ $"<RunSettings>\n" +
+ $" <TestRunParameters>\n" +
+ $" <Parameter name=\"tests:seed\" value=\"{RandomizedContext.CurrentContext.RandomSeedAsHex}\" />\n" +
+ $" <Parameter name=\"tests:culture\" value=\"{Thread.CurrentThread.CurrentCulture.Name}\" />\n" +
+ $" </TestRunParameters>\n" +
+ $"</RunSettings>\n\n" +
+ $"See the .runsettings documentation at: https://docs.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file.";
+ result.SetResult(result.ResultState, message, result.StackTrace);
+ }
+#endif
}
#if TESTFRAMEWORK_MSTEST
@@ -1080,10 +1093,7 @@ namespace Lucene.Net.Util
try
{
- // Setup the factories
- LuceneTestFrameworkInitializer.EnsureInitialized();
-
- ClassEnvRule.Before(null);
+ ClassEnvRule.Before();
// LUCENENET: Generate the info once so it can be printed out for each test
codecType = ClassEnvRule.codec.GetType().Name;
@@ -1091,11 +1101,6 @@ namespace Lucene.Net.Util
// LUCENENET TODO: Scan for a custom attribute and setup ordering to
// initialize data from this class to the top class
-
- if (UseTempLineDocsFile)
- {
- TempLineDocsFile = LineFileDocs.MaybeCreateTempFile();
- }
}
catch (Exception ex)
{
@@ -1120,19 +1125,11 @@ namespace Lucene.Net.Util
{
try
{
- // Setup the factories
- LuceneTestFrameworkInitializer.EnsureInitialized();
-
- ClassEnvRule.Before(this);
+ ClassEnvRule.Before();
// LUCENENET: Generate the info once so it can be printed out for each test
codecType = ClassEnvRule.codec.GetType().Name;
similarityName = ClassEnvRule.similarity.ToString();
-
- if (UseTempLineDocsFile)
- {
- TempLineDocsFile = LineFileDocs.MaybeCreateTempFile();
- }
}
catch (Exception ex)
{
@@ -1151,12 +1148,8 @@ namespace Lucene.Net.Util
{
try
{
- ClassEnvRule.After(null);
+ ClassEnvRule.After();
CleanupTemporaryFiles();
- if (UseTempLineDocsFile)
- {
- TempLineDocsFile = null;
- }
}
catch (Exception ex)
{
@@ -1180,12 +1173,8 @@ namespace Lucene.Net.Util
{
try
{
- ClassEnvRule.After(this);
+ ClassEnvRule.After();
CleanupTemporaryFiles();
- if (UseTempLineDocsFile)
- {
- TempLineDocsFile = null;
- }
}
catch (Exception ex)
{
@@ -1214,7 +1203,7 @@ namespace Lucene.Net.Util
/// invocations are present or create a derivative local <see cref="System.Random"/> for millions of calls
/// like this:
/// <code>
- /// Random random = new Random(Random.Next());
+ /// Random random = new J2N.Randomizer(Random.NextInt64());
/// // tight loop with many invocations.
/// </code>
/// </summary>
@@ -1224,9 +1213,12 @@ namespace Lucene.Net.Util
get
{
#if TESTFRAMEWORK_NUNIT
- return NUnit.Framework.TestContext.CurrentContext.Random;
+ var context = RandomizedContext.CurrentContext;
+ if (context is null)
+ Assert.Fail("LuceneTestCase.Random may only be used within tests/setup/teardown context in subclasses of LuceneTestCase or LuceneTestFrameworkInitializer.");
+ return context.RandomGenerator;
#else
- return _random ?? (_random = new Random(/* LUCENENET TODO seed */));
+ return random ?? (random = new J2N.Randomizer(/* LUCENENET TODO seed */));
//return RandomizedContext.Current.Random;
#endif
}
@@ -1234,7 +1226,7 @@ namespace Lucene.Net.Util
#if !TESTFRAMEWORK_NUNIT
[ThreadStatic]
- private static Random _random;
+ private static Random random;
#endif
/////// <summary>
@@ -1258,8 +1250,15 @@ namespace Lucene.Net.Util
////}*/
/// <summary>
+ /// Gets the current type being tested.
+ /// </summary>
+ public static Type TestType
+ => TestExecutionContext.CurrentContext.CurrentTest.Fixture?.GetType();
+
+ /// <summary>
/// Return the current type being tested.
/// </summary>
+ [Obsolete("Use TestType instead. This method will be removed in 4.8.0 release candidate.")]
public static Type GetTestClass()
{
#if !TESTFRAMEWORK_XUNIT
@@ -1751,7 +1750,7 @@ namespace Lucene.Net.Util
public static AlcoholicMergePolicy NewAlcoholicMergePolicy(Random random, TimeZoneInfo timeZone)
{
- return new AlcoholicMergePolicy(timeZone, new Random(random.Next()));
+ return new AlcoholicMergePolicy(timeZone, new J2N.Randomizer(random.NextInt64()));
}
public static LogMergePolicy NewLogMergePolicy(Random random)
diff --git a/src/Lucene.Net.TestFramework/Util/TestRuleSetupAndRestoreClassEnv.cs b/src/Lucene.Net.TestFramework/Util/TestRuleSetupAndRestoreClassEnv.cs
index f8c6c52..ac4ea92 100644
--- a/src/Lucene.Net.TestFramework/Util/TestRuleSetupAndRestoreClassEnv.cs
+++ b/src/Lucene.Net.TestFramework/Util/TestRuleSetupAndRestoreClassEnv.cs
@@ -108,7 +108,7 @@ namespace Lucene.Net.Util
}
}
- public override void Before(LuceneTestCase testInstance)
+ public override void Before()
{
// LUCENENET specific - SOLR setup code removed
@@ -150,7 +150,7 @@ namespace Lucene.Net.Util
InfoStream.Default = new NullInfoStream();
}
- Type targetClass = testInstance?.GetType() ?? LuceneTestCase.GetTestClass();
+ Type targetClass = LuceneTestCase.TestType;
avoidCodecs = new JCG.HashSet<string>();
var suppressCodecsAttribute = targetClass.GetCustomAttribute<LuceneTestCase.SuppressCodecsAttribute>();
if (suppressCodecsAttribute != null)
@@ -226,7 +226,7 @@ namespace Lucene.Net.Util
}
else if ("MockRandom".Equals(LuceneTestCase.TestPostingsFormat, StringComparison.Ordinal))
{
- format = new MockRandomPostingsFormat(new Random(random.Next()));
+ format = new MockRandomPostingsFormat(new J2N.Randomizer(random.NextInt64()));
}
else
{
@@ -281,18 +281,35 @@ namespace Lucene.Net.Util
Codec.Default = codec;
// Initialize locale/ timezone.
- string testLocale = SystemProperties.GetProperty("tests:locale", "random"); // LUCENENET specific - reformatted with :
+
string testTimeZone = SystemProperties.GetProperty("tests:timezone", "random"); // LUCENENET specific - reformatted with :
- // Always pick a random one for consistency (whether tests.locale was specified or not).
- savedLocale = CultureInfo.CurrentCulture;
+ // LUCENENET: We need to ensure our random generator stays consistent here so we can repeat the session exactly,
+ // so always call this whether the return value is useful or not.
CultureInfo randomLocale = LuceneTestCase.RandomCulture(random);
- locale = testLocale.Equals("random", StringComparison.Ordinal) ? randomLocale : LuceneTestCase.CultureForName(testLocale);
+
+ // LUCENENET: Allow NUnit properties to set the culture and respect that culture over our random one.
+ // Note that SetCultureAttribute may also be on the test method, but we don't need to deal with that here.
+ if (targetClass.Assembly.HasAttribute<NUnit.Framework.SetCultureAttribute>(inherit: true)
+ || targetClass.HasAttribute<NUnit.Framework.SetCultureAttribute>(inherit: true))
+ {
+ locale = CultureInfo.CurrentCulture;
+ }
+ else
+ {
+ // LUCENENET: Accept either tests:culture or tests:locale (culture preferred).
+ string testLocale = SystemProperties.GetProperty("tests:culture", SystemProperties.GetProperty("tests:locale", "random")); // LUCENENET specific - reformatted with :
+
+ // Always pick a random one for consistency (whether tests.locale was specified or not).
+ savedLocale = CultureInfo.CurrentCulture;
+
+ locale = testLocale.Equals("random", StringComparison.Ordinal) ? randomLocale : LuceneTestCase.CultureForName(testLocale);
#if FEATURE_CULTUREINFO_CURRENTCULTURE_SETTER
- CultureInfo.CurrentCulture = locale;
+ CultureInfo.CurrentCulture = locale;
#else
- Thread.CurrentThread.CurrentCulture = locale;
+ Thread.CurrentThread.CurrentCulture = locale;
#endif
+ }
// TimeZone.getDefault will set user.timezone to the default timezone of the user's locale.
// So store the original property value and restore it at end.
@@ -368,7 +385,7 @@ namespace Lucene.Net.Util
/// <summary>
/// After suite cleanup (always invoked).
/// </summary>
- public override void After(LuceneTestCase testInstance)
+ public override void After()
{
// LUCENENT specific - Not used in .NET
//foreach (KeyValuePair<string, string> e in restoreProperties)
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
index 72d80e6..a0a20b7 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Core/TestRandomChains.cs
@@ -1,5 +1,6 @@
// Lucene version compatibility level 4.8.1
+using J2N;
using J2N.Runtime.CompilerServices;
using J2N.Text;
using Lucene.Net.Analysis.CharFilters;
@@ -25,6 +26,7 @@ using Lucene.Net.TestFramework.Analysis;
using Lucene.Net.Util;
using Lucene.Net.Util.Automaton;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -108,7 +110,7 @@ namespace Lucene.Net.Analysis.Core
typeof(CrankyTokenFilter),
// Not broken: we forcefully add this, so we shouldn't
// also randomly pick it:
- typeof(ValidatingTokenFilter)
+ typeof(ValidatingTokenFilter),
})
{
foreach (ConstructorInfo ctor in c.GetConstructors())
@@ -415,7 +417,7 @@ namespace Lucene.Net.Analysis.Core
{
public object Create(Random random)
{
- return new Random(random.Next());
+ return new J2N.Randomizer(random.NextInt64());
}
}
@@ -692,16 +694,45 @@ namespace Lucene.Net.Analysis.Core
private class SynonymMapArgProducer : IArgProducer
{
+ // LUCENENET specific: Added functionality to export the source code of the builder with all of the escaped text.
+ //
+ // USAGE
+ //
+ // This is intended to be used in conjunction with a fixed random seed after a failure. You should confirm
+ // first that you can reproduce a test failure before exporting.
+ //
+ // 1. Change exportSourceCode to true to export the source code
+ // 2. Update the exportPath to a folder on your local system. Note that it won't automatically create directories.
+ // The {0} token will be replaced with a map number. Normally, you would get the contents of the highest number,
+ // which is the last successful map that occurred before there was a test failure.
+
+ private StringBuilder sb = new StringBuilder();
+ private static bool exportSourceCode = false; // Change to enable source code export.
+ private static string exportPath = @"F:\synonym-map-{0}.txt"; // Change as necessary for your system.
+ private int mapCount = 0;
public object Create(Random random)
{
- SynonymMap.Builder b = new SynonymMap.Builder(random.nextBoolean());
+ if (exportSourceCode) sb.Clear();
+ bool dedup = random.NextBoolean();
+ SynonymMap.Builder b = new SynonymMap.Builder(dedup);
+
+ if (exportSourceCode) sb.AppendLine($"SynonymMap.Builder b = new SynonymMap.Builder({dedup.ToString().ToLowerInvariant()});");
+
int numEntries = AtLeast(10);
for (int j = 0; j < numEntries; j++)
{
- AddSyn(b, RandomNonEmptyString(random), RandomNonEmptyString(random), random.nextBoolean());
+ AddSyn(b, RandomNonEmptyString(random), RandomNonEmptyString(random), random.NextBoolean());
}
try
{
+ if (exportSourceCode)
+ {
+ sb.AppendLine("SynonymMap synonymMap = b.Build();");
+ mapCount++;
+ string path = string.Format(exportPath, mapCount);
+ File.WriteAllText(path, sb.ToString());
+ }
+
return b.Build();
}
catch (Exception ex) when (ex.IsException())
@@ -713,11 +744,24 @@ namespace Lucene.Net.Analysis.Core
}
}
+ private static readonly Regex whiteSpace = new Regex(" +", RegexOptions.Compiled);
+
private void AddSyn(SynonymMap.Builder b, string input, string output, bool keepOrig)
{
- b.Add(new CharsRef(input.Replace(" +", "\u0000")),
- new CharsRef(output.Replace(" +", "\u0000")),
- keepOrig);
+ string inputNoSpaces = whiteSpace.Replace(input, "\u0000");
+ string outputNoSpaces = whiteSpace.Replace(output, "\u0000");
+
+ if (exportSourceCode)
+ {
+ sb.AppendLine($"b.Add(new CharsRef(\"{Escape(inputNoSpaces)}\"),");
+ sb.AppendLine($" new CharsRef(\"{Escape(outputNoSpaces)}\"),");
+ sb.AppendLine($" {keepOrig.ToString().ToLowerInvariant()});");
+ sb.AppendLine();
+ }
+
+ b.Add(new CharsRef(inputNoSpaces),
+ new CharsRef(outputNoSpaces),
+ keepOrig);
}
private string RandomNonEmptyString(Random random)
@@ -814,10 +858,9 @@ namespace Lucene.Net.Analysis.Core
private class MockRandomAnalyzer : Analyzer
{
- internal readonly int seed;
-
+ internal readonly long seed;
- public MockRandomAnalyzer(int seed)
+ public MockRandomAnalyzer(long seed)
{
this.seed = seed;
}
@@ -827,7 +870,7 @@ namespace Lucene.Net.Analysis.Core
get
{
// TODO: can we not do the full chain here!?
- Random random = new Random(seed);
+ Random random = new Randomizer(seed);
TokenizerSpec tokenizerSpec = NewTokenizer(random, new StringReader(""));
TokenFilterSpec filterSpec = NewFilterChain(random, tokenizerSpec.tokenizer, tokenizerSpec.offsetsAreCorrect);
return filterSpec.offsetsAreCorrect;
@@ -836,7 +879,7 @@ namespace Lucene.Net.Analysis.Core
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
- Random random = new Random(seed);
+ Random random = new Randomizer(seed);
TokenizerSpec tokenizerSpec = NewTokenizer(random, reader);
//System.out.println("seed=" + seed + ",create tokenizer=" + tokenizerSpec.toString);
TokenFilterSpec filterSpec = NewFilterChain(random, tokenizerSpec.tokenizer, tokenizerSpec.offsetsAreCorrect);
@@ -846,7 +889,7 @@ namespace Lucene.Net.Analysis.Core
protected internal override TextReader InitReader(string fieldName, TextReader reader)
{
- Random random = new Random(seed);
+ Random random = new Randomizer(seed);
CharFilterSpec charfilterspec = NewCharFilterChain(random, reader);
return charfilterspec.reader;
}
@@ -854,13 +897,13 @@ namespace Lucene.Net.Analysis.Core
public override string ToString()
{
- Random random = new Random(seed);
+ Random random = new Randomizer(seed);
StringBuilder sb = new StringBuilder();
CharFilterSpec charFilterSpec = NewCharFilterChain(random, new StringReader(""));
sb.Append("\ncharfilters=");
sb.Append(charFilterSpec.toString);
// intentional: initReader gets its own separate random
- random = new Random(seed);
+ random = new Randomizer(seed);
TokenizerSpec tokenizerSpec = NewTokenizer(random, charFilterSpec.reader);
sb.Append("\n");
sb.Append("tokenizer=");
@@ -1119,15 +1162,14 @@ namespace Lucene.Net.Analysis.Core
}
[Test]
- [Slow]
- [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/269")] // LUCENENET TODO: this test occasionally fails
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/271#issuecomment-973005744")] // LUCENENET TODO: this test occasionally fails
public void TestRandomChains_()
{
int numIterations = AtLeast(20);
Random random = Random;
for (int i = 0; i < numIterations; i++)
{
- MockRandomAnalyzer a = new MockRandomAnalyzer(random.Next());
+ MockRandomAnalyzer a = new MockRandomAnalyzer(random.NextInt64());
if (Verbose)
{
Console.WriteLine("Creating random analyzer:" + a);
@@ -1139,7 +1181,7 @@ namespace Lucene.Net.Analysis.Core
}
catch (Exception e) when (e.IsThrowable())
{
- Console.WriteLine("Exception from random analyzer: " + a);
+ Console.WriteLine("Exception from random analyzer (iteration {i}): " + a);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
@@ -1147,15 +1189,14 @@ namespace Lucene.Net.Analysis.Core
// we might regret this decision...
[Test]
- [Slow]
- [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/269")] // LUCENENET TODO: this test occasionally fails
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/271#issuecomment-973005744")] // LUCENENET TODO: this test occasionally fails
public void TestRandomChainsWithLargeStrings()
{
int numIterations = AtLeast(20);
Random random = Random;
for (int i = 0; i < numIterations; i++)
{
- MockRandomAnalyzer a = new MockRandomAnalyzer(random.Next());
+ MockRandomAnalyzer a = new MockRandomAnalyzer(random.NextInt64());
if (Verbose)
{
Console.WriteLine("Creating random analyzer:" + a);
@@ -1167,7 +1208,7 @@ namespace Lucene.Net.Analysis.Core
}
catch (Exception e) when (e.IsThrowable())
{
- Console.WriteLine("Exception from random analyzer: " + a);
+ Console.WriteLine($"Exception from random analyzer (iteration {i}): " + a);
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilter.cs b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilter.cs
index aa3dc1c..d940ed3 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilter.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Analysis/Pattern/TestPatternReplaceCharFilter.cs
@@ -2,6 +2,7 @@
using J2N;
using Lucene.Net.Util;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.IO;
using System.Text;
@@ -251,11 +252,11 @@ namespace Lucene.Net.Analysis.Pattern
[Slow]
public virtual void TestRandomStrings()
{
- int numPatterns = 10 + LuceneTestCase.Random.Next(20);
- Random random = new Random(Random.nextInt(int.MaxValue));
+ int numPatterns = 10 + Random.Next(20);
+ Random random = new J2N.Randomizer(Random.NextInt64());
for (int i = 0; i < numPatterns; i++)
{
- Regex p = TestUtil.RandomRegex(LuceneTestCase.Random);
+ Regex p = TestUtil.RandomRegex(Random);
string replacement = TestUtil.RandomSimpleString(random);
Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
diff --git a/src/Lucene.Net.Tests.Analysis.Common/Startup.cs b/src/Lucene.Net.Tests.Analysis.Common/Startup.cs
index 7cdc10d..07033b1 100644
--- a/src/Lucene.Net.Tests.Analysis.Common/Startup.cs
+++ b/src/Lucene.Net.Tests.Analysis.Common/Startup.cs
@@ -18,9 +18,6 @@
using Lucene.Net.Util;
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
public class Startup : LuceneTestFrameworkInitializer
{
protected override void TestFrameworkSetUp()
diff --git a/src/Lucene.Net.Tests.Analysis.Kuromoji/Startup.cs b/src/Lucene.Net.Tests.Analysis.Kuromoji/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.Kuromoji/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Analysis.Morfologik/Startup.cs b/src/Lucene.Net.Tests.Analysis.Morfologik/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.Morfologik/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Analysis.OpenNLP/Startup.cs b/src/Lucene.Net.Tests.Analysis.OpenNLP/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.OpenNLP/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Analysis.Phonetic/Startup.cs b/src/Lucene.Net.Tests.Analysis.Phonetic/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.Phonetic/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Analysis.SmartCn/Startup.cs b/src/Lucene.Net.Tests.Analysis.SmartCn/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.SmartCn/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Analysis.Stempel/Startup.cs b/src/Lucene.Net.Tests.Analysis.Stempel/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests.Analysis.Stempel/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs
index 5be1307..0fc4dfe 100644
--- a/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs
+++ b/src/Lucene.Net.Tests.Benchmark/ByTask/TestPerfTasksParse.cs
@@ -139,7 +139,7 @@ namespace Lucene.Net.Benchmarks.ByTask
if (Type.GetType(contentSource) == null)
throw ClassNotFoundException.Create(contentSource);
}
- config.Set("work.dir", CreateTempDir(LuceneTestCase.GetTestClass().Name).FullName);
+ config.Set("work.dir", CreateTempDir(LuceneTestCase.TestType.Name).FullName);
config.Set("content.source", typeof(MockContentSource).AssemblyQualifiedName);
String dir = config.Get("content.source", null);
if (dir != null)
diff --git a/src/Lucene.Net.Tests.Classification/ClassificationTestBase.cs b/src/Lucene.Net.Tests.Classification/ClassificationTestBase.cs
index 5d0a22f..314c79d 100644
--- a/src/Lucene.Net.Tests.Classification/ClassificationTestBase.cs
+++ b/src/Lucene.Net.Tests.Classification/ClassificationTestBase.cs
@@ -221,7 +221,12 @@ namespace Lucene.Net.Classification
classifier.Train(atomicReader, textFieldName, classFieldName, analyzer);
long trainEnd = J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
long trainTime = trainEnd - trainStart;
+ // LUCENENET: This test is running slow on .NET Framework in CI, so we are giving it a little more time to complete.
+#if NETFRAMEWORK
+ Assert.IsTrue(trainTime < 150000, "training took more than 2.5 mins : " + trainTime / 1000 + "s");
+#else
Assert.IsTrue(trainTime < 120000, "training took more than 2 mins : " + trainTime / 1000 + "s");
+#endif
}
finally
{
@@ -240,7 +245,7 @@ namespace Lucene.Net.Classification
ft.StoreTermVectorOffsets = true;
ft.StoreTermVectorPositions = true;
int docs = 1000;
- Random random = new Random();
+ Random random = Random;
for (int i = 0; i < docs; i++)
{
Boolean b = random.NextBoolean();
diff --git a/src/Lucene.Net.Tests.Classification/KNearestNeighborClassifierTest.cs b/src/Lucene.Net.Tests.Classification/KNearestNeighborClassifierTest.cs
index 87f3f4f..fbfed09 100644
--- a/src/Lucene.Net.Tests.Classification/KNearestNeighborClassifierTest.cs
+++ b/src/Lucene.Net.Tests.Classification/KNearestNeighborClassifierTest.cs
@@ -1,4 +1,4 @@
-/*
+/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
@@ -48,5 +48,6 @@ namespace Lucene.Net.Classification
{
CheckPerformance(new KNearestNeighborClassifier(100), new MockAnalyzer(Random), categoryFieldName);
}
+
}
}
\ No newline at end of file
diff --git a/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs b/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs
index 0600431..25e7ceb 100644
--- a/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs
+++ b/src/Lucene.Net.Tests.Facet/SlowRAMDirectory.cs
@@ -96,7 +96,7 @@ namespace Lucene.Net.Facet
{
return null;
}
- return new Random((int)random.NextInt64());
+ return new J2N.Randomizer(random.NextInt64());
}
/// <summary>
diff --git a/src/Lucene.Net.Tests.Join/Support/TestJoinUtil.cs b/src/Lucene.Net.Tests.Join/Support/TestJoinUtil.cs
index dea1ecf..f4526fe 100644
--- a/src/Lucene.Net.Tests.Join/Support/TestJoinUtil.cs
+++ b/src/Lucene.Net.Tests.Join/Support/TestJoinUtil.cs
@@ -393,6 +393,9 @@ namespace Lucene.Net.Tests.Join
[Test]
// [Slow] // LUCENENET specific - Not slow in .NET
+#if NETFRAMEWORK
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/549")] // LUCENENET TODO: This test fails on x86 .NET Framework in Release mode only
+#endif
public void TestMultiValueRandomJoin()
// this test really takes more time, that is why the number of iterations are smaller.
{
diff --git a/src/Lucene.Net.Tests.Join/TestJoinUtil.cs b/src/Lucene.Net.Tests.Join/TestJoinUtil.cs
index 104bcb5..50d60f2 100644
--- a/src/Lucene.Net.Tests.Join/TestJoinUtil.cs
+++ b/src/Lucene.Net.Tests.Join/TestJoinUtil.cs
@@ -390,6 +390,9 @@ namespace Lucene.Net.Search.Join
[Test]
// [Slow] // LUCENENET specific - Not slow in .NET
+#if NETFRAMEWORK
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/549")] // LUCENENET TODO: This test fails on x86 .NET Framework in Release mode only
+#endif
public void TestMultiValueRandomJoin()
// this test really takes more time, that is why the number of iterations are smaller.
{
diff --git a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestEarlyTermination.cs b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestEarlyTermination.cs
index 9acd9f9..1339cbb 100644
--- a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestEarlyTermination.cs
+++ b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestEarlyTermination.cs
@@ -65,10 +65,10 @@ namespace Lucene.Net.Index.Sorter
randomTerms.add(TestUtil.RandomSimpleString(Random));
}
terms = new JCG.List<string>(randomTerms);
- int seed = Random.Next();
- IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random(seed)));
+ long seed = Random.NextInt64();
+ IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new J2N.Randomizer(seed)));
iwc.SetMergePolicy(TestSortingMergePolicy.NewSortingMergePolicy(sort));
- iw = new RandomIndexWriter(new Random(seed), dir, iwc);
+ iw = new RandomIndexWriter(new J2N.Randomizer(seed), dir, iwc);
for (int i = 0; i < numDocs; ++i)
{
Document doc = RandomDocument();
diff --git a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs
index 97d9648..9b28f31 100644
--- a/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs
+++ b/src/Lucene.Net.Tests.Misc/Index/Sorter/TestSortingMergePolicy.cs
@@ -89,11 +89,11 @@ namespace Lucene.Net.Index.Sorter
}
terms = new JCG.List<string>(randomTerms);
long seed = Random.NextInt64();
- IndexWriterConfig iwc1 = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random((int)seed)));
- IndexWriterConfig iwc2 = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random((int)seed)));
+ IndexWriterConfig iwc1 = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new J2N.Randomizer(seed)));
+ IndexWriterConfig iwc2 = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new J2N.Randomizer(seed)));
iwc2.SetMergePolicy(NewSortingMergePolicy(sort));
- RandomIndexWriter iw1 = new RandomIndexWriter(new Random((int)seed), dir1, iwc1);
- RandomIndexWriter iw2 = new RandomIndexWriter(new Random((int)seed), dir2, iwc2);
+ RandomIndexWriter iw1 = new RandomIndexWriter(new J2N.Randomizer(seed), dir1, iwc1);
+ RandomIndexWriter iw2 = new RandomIndexWriter(new J2N.Randomizer(seed), dir2, iwc2);
for (int i = 0; i < numDocs; ++i)
{
if (Random.nextInt(5) == 0 && i != numDocs - 1)
diff --git a/src/Lucene.Net.Tests.Misc/Util/Fst/TestFSTsMisc.cs b/src/Lucene.Net.Tests.Misc/Util/Fst/TestFSTsMisc.cs
index f1e74c9..b79bdf0 100644
--- a/src/Lucene.Net.Tests.Misc/Util/Fst/TestFSTsMisc.cs
+++ b/src/Lucene.Net.Tests.Misc/Util/Fst/TestFSTsMisc.cs
@@ -1,6 +1,7 @@
-using J2N.Collections.Generic.Extensions;
+using J2N.Collections.Generic.Extensions;
using Lucene.Net.Store;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -53,7 +54,7 @@ namespace Lucene.Net.Util.Fst
private void TestRandomWords(int maxNumWords, int numIter)
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
for (int iter = 0; iter < numIter; iter++)
{
if (Verbose)
diff --git a/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs b/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs
index 6ff07d9..4835728 100644
--- a/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs
+++ b/src/Lucene.Net.Tests.Queries/CommonTermsQueryTest.cs
@@ -131,7 +131,7 @@ namespace Lucene.Net.Tests.Queries
RandomOccur(Random), Random.NextSingle(), Random.NextBoolean()), query);
{
long seed = Random.NextInt64();
- Random r = new Random((int)seed);
+ Random r = new J2N.Randomizer(seed);
CommonTermsQuery left = new CommonTermsQuery(RandomOccur(r),
RandomOccur(r), r.NextSingle(), r.NextBoolean());
int leftTerms = AtLeast(r, 2);
@@ -143,7 +143,7 @@ namespace Lucene.Net.Tests.Queries
left.HighFreqMinimumNumberShouldMatch = r.nextInt(4);
left.LowFreqMinimumNumberShouldMatch = r.nextInt(4);
- r = new Random((int)seed);
+ r = new J2N.Randomizer(seed);
CommonTermsQuery right = new CommonTermsQuery(RandomOccur(r),
RandomOccur(r), r.NextSingle(), r.NextBoolean());
int rightTerms = AtLeast(r, 2);
@@ -593,7 +593,7 @@ namespace Lucene.Net.Tests.Queries
/// </summary>
public static void CreateRandomIndex(int numdocs, RandomIndexWriter writer, long seed)
{
- Random random = new Random((int)seed);
+ Random random = new J2N.Randomizer(seed);
// primary source for our data is from linefiledocs, its realistic.
LineFileDocs lineFileDocs = new LineFileDocs(random, false); // no docvalues in 4x
diff --git a/src/Lucene.Net.Tests.Replicator/IndexInputStreamTest.cs b/src/Lucene.Net.Tests.Replicator/IndexInputStreamTest.cs
index a38c06c..f060eba 100644
--- a/src/Lucene.Net.Tests.Replicator/IndexInputStreamTest.cs
+++ b/src/Lucene.Net.Tests.Replicator/IndexInputStreamTest.cs
@@ -1,12 +1,10 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Lucene.Net.Attributes;
+using Lucene.Net.Attributes;
using Lucene.Net.Index;
using Lucene.Net.Replicator;
-using Lucene.Net.Store;
+using Lucene.Net.Util;
using NUnit.Framework;
+using System;
+using System.Linq;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Tests.Replicator
@@ -30,7 +28,7 @@ namespace Lucene.Net.Tests.Replicator
//Note: LUCENENET specific
[LuceneNetSpecific]
- public class IndexInputStreamTest
+ public class IndexInputStreamTest : LuceneTestCase
{
[Test]
@@ -38,7 +36,7 @@ namespace Lucene.Net.Tests.Replicator
public void Read_RemainingIndexInputLargerThanReadCount_ReturnsReadCount()
{
byte[] buffer = new byte[8.KiloBytes()];
- new Random().NextBytes(buffer);
+ Random.NextBytes(buffer);
IndexInputStream stream = new IndexInputStream(new MockIndexInput(buffer));
int readBytes = 2.KiloBytes();
@@ -51,7 +49,7 @@ namespace Lucene.Net.Tests.Replicator
public void Read_RemainingIndexInputLargerThanReadCount_ReturnsExpectedSection([Range(1,8)]int section)
{
byte[] buffer = new byte[8.KiloBytes()];
- new Random().NextBytes(buffer);
+ Random.NextBytes(buffer);
IndexInputStream stream = new IndexInputStream(new MockIndexInput(buffer));
int readBytes = 1.KiloBytes();
diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/Fst/WFSTCompletionTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/Fst/WFSTCompletionTest.cs
index c7d9f81..3f1b320 100644
--- a/src/Lucene.Net.Tests.Suggest/Suggest/Fst/WFSTCompletionTest.cs
+++ b/src/Lucene.Net.Tests.Suggest/Suggest/Fst/WFSTCompletionTest.cs
@@ -1,6 +1,7 @@
using Lucene.Net.Support;
using Lucene.Net.Util;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
@@ -36,7 +37,7 @@ namespace Lucene.Net.Search.Suggest.Fst
new Input("barbara", 6)
};
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
WFSTCompletionLookup suggester = new WFSTCompletionLookup();
suggester.Build(new InputArrayEnumerator(keys));
@@ -171,7 +172,7 @@ namespace Lucene.Net.Search.Suggest.Fst
suggester.Build(new InputArrayEnumerator(keys));
assertEquals(numWords, suggester.Count);
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
foreach (String prefix in allPrefixes)
{
int topN = TestUtil.NextInt32(random, 1, 10);
diff --git a/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs b/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs
index 17a79eb..9b1442f 100644
--- a/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs
+++ b/src/Lucene.Net.Tests.Suggest/Suggest/LookupBenchmarkTest.cs
@@ -58,7 +58,7 @@ namespace Lucene.Net.Search.Suggest
internal readonly int num = 7;
internal readonly bool onlyMorePopular = false;
- private readonly static Random random = new Random(0xdeadbee); // LUCENENET NOTE: Changed seed so it would fit in an int
+ private readonly static Random random = new J2N.Randomizer(0xdeadbeef);
/**
* Input term/weight pairs.
diff --git a/src/Lucene.Net.Tests.TestFramework.DependencyInjection/Startup.cs b/src/Lucene.Net.Tests.TestFramework.DependencyInjection/Startup.cs
index 437796a..0edb611 100644
--- a/src/Lucene.Net.Tests.TestFramework.DependencyInjection/Startup.cs
+++ b/src/Lucene.Net.Tests.TestFramework.DependencyInjection/Startup.cs
@@ -29,7 +29,7 @@ using System.Collections.Generic;
/// </summary>
public class Startup : LuceneTestFrameworkInitializer
{
- protected override void TestFrameworkSetUp()
+ protected override void Initialize()
{
// Composition root
diff --git a/src/Lucene.Net.Tests.TestFramework/Configuration/TestSystemProperties.cs b/src/Lucene.Net.Tests.TestFramework/Configuration/TestSystemProperties.cs
index 5cb2122..2858b91 100644
--- a/src/Lucene.Net.Tests.TestFramework/Configuration/TestSystemProperties.cs
+++ b/src/Lucene.Net.Tests.TestFramework/Configuration/TestSystemProperties.cs
@@ -151,9 +151,9 @@ namespace Lucene.Net.Configuration
Assert.AreEqual(0xf6a5c420, (uint)StringHelper.Murmurhash3_x86_32(new BytesRef("foo"), 0));
- Assert.AreEqual(16, StringHelper.GOOD_FAST_HASH_SEED);
+ Assert.AreEqual(16, StringHelper.GoodFastHashSeed);
// Hashes computed using murmur3_32 from https://code.google.com/p/pyfasthash
- Assert.AreEqual(0xcd018ef6, (uint)StringHelper.Murmurhash3_x86_32(new BytesRef("foo"), StringHelper.GOOD_FAST_HASH_SEED));
+ Assert.AreEqual(0xcd018ef6, (uint)StringHelper.Murmurhash3_x86_32(new BytesRef("foo"), StringHelper.GoodFastHashSeed));
}
[Test]
diff --git a/src/Lucene.Net.Tests.TestFramework/Startup.cs b/src/Lucene.Net.Tests.TestFramework/Startup.cs
index d53a984..f06f0e8 100644
--- a/src/Lucene.Net.Tests.TestFramework/Startup.cs
+++ b/src/Lucene.Net.Tests.TestFramework/Startup.cs
@@ -39,7 +39,7 @@ public class Startup : LuceneTestFrameworkInitializer
initilizationReset = initializationCount.GetAndSet(0) != 0;
}
- protected override void TestFrameworkSetUp()
+ protected override void Initialize()
{
// Decorate the existing configuration factory with mock settings
// so we don't interfere with the operation of the test framework.
diff --git a/src/Lucene.Net.Tests.TestFramework/Support/TestApiConsistency.cs b/src/Lucene.Net.Tests.TestFramework/Support/TestApiConsistency.cs
index a17e51b..078d665 100644
--- a/src/Lucene.Net.Tests.TestFramework/Support/TestApiConsistency.cs
+++ b/src/Lucene.Net.Tests.TestFramework/Support/TestApiConsistency.cs
@@ -39,7 +39,7 @@ namespace Lucene.Net.Tests.TestFramework
[TestCase(typeof(Lucene.Net.RandomExtensions))]
public override void TestPrivateFieldNames(Type typeFromTargetAssembly)
{
- base.TestPrivateFieldNames(typeFromTargetAssembly, @"ApiScanTestBase|TestUtil.MaxRecursionBound|Assert.FailureFormat");
+ base.TestPrivateFieldNames(typeFromTargetAssembly, @"ApiScanTestBase|TestUtil\.MaxRecursionBound|Assert\.FailureFormat|Lucene\.Net\.Util\.RandomizedContext\.RandomizedContextPropertyName|Lucene\.Net\.Util\.DefaultNamespaceTypeWrapper\.AllMembers");
}
[Test, LuceneNetSpecific]
diff --git a/src/Lucene.Net.Tests._A-D/Startup.cs b/src/Lucene.Net.Tests._A-D/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests._A-D/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests._I-J/Startup.cs b/src/Lucene.Net.Tests._I-J/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests._I-J/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests._J-S/Startup.cs b/src/Lucene.Net.Tests._J-S/Startup.cs
deleted file mode 100644
index 9233cac..0000000
--- a/src/Lucene.Net.Tests._J-S/Startup.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-
-using Lucene.Net.Util;
-
-// LUCENENET: With this class in place, the LineDocsFile is exported to a temp file 1 time per test run,
-// which makes the tests run faster. This class is simply here to facilitate the call from NUnit which
-// would not occur if it were not here.
-public class Startup : LuceneTestFrameworkInitializer
-{
-}
diff --git a/src/Lucene.Net.Tests/Codecs/Lucene40/TestReuseDocsEnum.cs b/src/Lucene.Net.Tests/Codecs/Lucene40/TestReuseDocsEnum.cs
index 9ceac85..78fd27b 100644
--- a/src/Lucene.Net.Tests/Codecs/Lucene40/TestReuseDocsEnum.cs
+++ b/src/Lucene.Net.Tests/Codecs/Lucene40/TestReuseDocsEnum.cs
@@ -1,6 +1,7 @@
using J2N.Runtime.CompilerServices;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
+using Lucene.Net.Util;
using NUnit.Framework;
using RandomizedTesting.Generators;
using System;
@@ -46,13 +47,13 @@ namespace Lucene.Net.Codecs.Lucene40
using TestUtil = Lucene.Net.Util.TestUtil;
// TODO: really this should be in BaseTestPF or somewhere else? useful test!
- [TestFixture]
+ // LUCENENET specific - Specify to unzip the line file docs
+ [UseTempLineDocsFile]
public class TestReuseDocsEnum : LuceneTestCase
{
[OneTimeSetUp]
public override void BeforeClass()
{
- UseTempLineDocsFile = true;
base.BeforeClass();
OldFormatImpersonationIsActive = true; // explicitly instantiates ancient codec
}
diff --git a/src/Lucene.Net.Tests/Codecs/Lucene41/TestBlockPostingsFormat3.cs b/src/Lucene.Net.Tests/Codecs/Lucene41/TestBlockPostingsFormat3.cs
index 98ee4cf..d02e510 100644
--- a/src/Lucene.Net.Tests/Codecs/Lucene41/TestBlockPostingsFormat3.cs
+++ b/src/Lucene.Net.Tests/Codecs/Lucene41/TestBlockPostingsFormat3.cs
@@ -84,12 +84,12 @@ namespace Lucene.Net.Codecs.Lucene41
Tokenizer tokenizer = new MockTokenizer(reader);
if (fieldName.Contains("payloadsFixed"))
{
- TokenFilter filter = new MockFixedLengthPayloadFilter(new Random(0), tokenizer, 1);
+ TokenFilter filter = new MockFixedLengthPayloadFilter(new J2N.Randomizer(0), tokenizer, 1);
return new TokenStreamComponents(tokenizer, filter);
}
else if (fieldName.Contains("payloadsVariable"))
{
- TokenFilter filter = new MockVariableLengthPayloadFilter(new Random(0), tokenizer);
+ TokenFilter filter = new MockVariableLengthPayloadFilter(new J2N.Randomizer(0), tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
else
diff --git a/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldDocValuesFormat.cs b/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldDocValuesFormat.cs
index cf3abc6..25950ab 100644
--- a/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldDocValuesFormat.cs
+++ b/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldDocValuesFormat.cs
@@ -1,9 +1,10 @@
-using Lucene.Net.Diagnostics;
+using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Support;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
@@ -61,7 +62,7 @@ namespace Lucene.Net.Codecs.PerField
[SetUp]
public override void SetUp()
{
- codec = new RandomCodec(new Random(Random.Next()), Collections.EmptySet<string>());
+ codec = new RandomCodec(new J2N.Randomizer(Random.NextInt64()), Collections.EmptySet<string>());
base.SetUp();
}
diff --git a/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldPostingsFormat.cs b/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldPostingsFormat.cs
index 35b39d3..f267f1a 100644
--- a/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldPostingsFormat.cs
+++ b/src/Lucene.Net.Tests/Codecs/PerField/TestPerFieldPostingsFormat.cs
@@ -1,5 +1,6 @@
-using Lucene.Net.Support;
+using Lucene.Net.Support;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
namespace Lucene.Net.Codecs.PerField
@@ -32,7 +33,7 @@ namespace Lucene.Net.Codecs.PerField
{
protected override Codec GetCodec()
{
- return new RandomCodec(new Random(Random.Next()), Collections.EmptySet<string>());
+ return new RandomCodec(new J2N.Randomizer(Random.NextInt64()), Collections.EmptySet<string>());
}
[Test]
diff --git a/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs b/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs
index 19738a6..6719790 100644
--- a/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs
+++ b/src/Lucene.Net.Tests/Index/TestBagOfPositions.cs
@@ -124,7 +124,7 @@ namespace Lucene.Net.Index
for (int threadID = 0; threadID < threadCount; threadID++)
{
- Random threadRandom = new Random(Random.Next());
+ Random threadRandom = new J2N.Randomizer(Random.NextInt64());
Document document = new Document();
Field field = new Field("field", "", fieldType);
document.Add(field);
diff --git a/src/Lucene.Net.Tests/Index/TestCompoundFile.cs b/src/Lucene.Net.Tests/Index/TestCompoundFile.cs
index 50861e0..941248a 100644
--- a/src/Lucene.Net.Tests/Index/TestCompoundFile.cs
+++ b/src/Lucene.Net.Tests/Index/TestCompoundFile.cs
@@ -64,8 +64,8 @@ namespace Lucene.Net.Index
IndexOutput os = dir.CreateOutput(name, NewIOContext(Random));
for (int i = 0; i < size; i++)
{
- var b = unchecked((sbyte)(new Random(1).NextDouble() * 256));
- os.WriteByte((byte)b);
+ var b = (byte)(Random.NextDouble() * 256); // LUCENENET: Using Random, since Math.random() doesn't exist in .NET, and it seems to make sense to make this repeatable.
+ os.WriteByte(b);
}
os.Dispose();
}
@@ -611,11 +611,11 @@ namespace Lucene.Net.Index
public virtual void TestLargeWrites()
{
IndexOutput os = dir.CreateOutput("testBufferStart.txt", NewIOContext(Random));
-
+
var largeBuf = new byte[2048];
for (int i = 0; i < largeBuf.Length; i++)
{
- largeBuf[i] = (byte)(new Random(1).NextDouble() * 256);
+ largeBuf[i] = (byte)(Random.NextDouble() * 256); // LUCENENET: Using Random, since Math.random() doesn't exist in .NET, and it seems to make sense to make this repeatable.
}
long currentPos = os.Position; // LUCENENET specific: Renamed from getFilePointer() to match FileStream
diff --git a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs
index b160376..f1b65ab 100644
--- a/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs
+++ b/src/Lucene.Net.Tests/Index/TestDocValuesWithThreads.cs
@@ -82,7 +82,7 @@ namespace Lucene.Net.Index
CountdownEvent startingGun = new CountdownEvent(1);
for (int t = 0; t < numThreads; t++)
{
- Random threadRandom = new Random(Random.Next());
+ Random threadRandom = new J2N.Randomizer(Random.NextInt64());
ThreadJob thread = new ThreadAnonymousClass(this, numbers, binary, sorted, numDocs, ar, startingGun, threadRandom);
thread.Start();
threads.Add(thread);
diff --git a/src/Lucene.Net.Tests/Index/TestDuelingCodecs.cs b/src/Lucene.Net.Tests/Index/TestDuelingCodecs.cs
index 4710120..8e88943 100644
--- a/src/Lucene.Net.Tests/Index/TestDuelingCodecs.cs
+++ b/src/Lucene.Net.Tests/Index/TestDuelingCodecs.cs
@@ -1,7 +1,8 @@
-using J2N.Text;
+using J2N.Text;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Text.RegularExpressions;
@@ -66,13 +67,13 @@ namespace Lucene.Net.Index
leftDir = NewDirectory();
rightDir = NewDirectory();
- long seed = Random.Next();
+ long seed = Random.NextInt64();
// must use same seed because of random payloads, etc
int maxTermLength = TestUtil.NextInt32(Random, 1, IndexWriter.MAX_TERM_LENGTH);
- MockAnalyzer leftAnalyzer = new MockAnalyzer(new Random((int)seed));
+ MockAnalyzer leftAnalyzer = new MockAnalyzer(new J2N.Randomizer(seed));
leftAnalyzer.MaxTokenLength = maxTermLength;
- MockAnalyzer rightAnalyzer = new MockAnalyzer(new Random((int)seed));
+ MockAnalyzer rightAnalyzer = new MockAnalyzer(new J2N.Randomizer(seed));
rightAnalyzer.MaxTokenLength = maxTermLength;
// but these can be different
@@ -88,8 +89,8 @@ namespace Lucene.Net.Index
rightConfig.SetMergePolicy(NewLogMergePolicy());
// must use same seed because of random docvalues fields, etc
- RandomIndexWriter leftWriter = new RandomIndexWriter(new Random((int)seed), leftDir, leftConfig);
- RandomIndexWriter rightWriter = new RandomIndexWriter(new Random((int)seed), rightDir, rightConfig);
+ RandomIndexWriter leftWriter = new RandomIndexWriter(new J2N.Randomizer(seed), leftDir, leftConfig);
+ RandomIndexWriter rightWriter = new RandomIndexWriter(new J2N.Randomizer(seed), rightDir, rightConfig);
int numdocs = AtLeast(100);
CreateRandomIndex(numdocs, leftWriter, seed);
@@ -136,7 +137,7 @@ namespace Lucene.Net.Index
/// </summary>
public static void CreateRandomIndex(int numdocs, RandomIndexWriter writer, long seed)
{
- Random random = new Random((int)seed);
+ Random random = new J2N.Randomizer(seed);
// primary source for our data is from linefiledocs, its realistic.
LineFileDocs lineFileDocs = new LineFileDocs(random);
@@ -159,7 +160,7 @@ namespace Lucene.Net.Index
document.RemoveFields("sparsenumeric");
if (random.Next(4) == 2)
{
- document.Add(new NumericDocValuesField("sparsenumeric", random.Next()));
+ document.Add(new NumericDocValuesField("sparsenumeric", random.NextInt64()));
}
writer.AddDocument(document);
}
@@ -171,6 +172,7 @@ namespace Lucene.Net.Index
/// checks the two indexes are equivalent
/// </summary>
[Test]
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/545")] // LUCENENET TODO: This test occasionally fails
public virtual void TestEquals()
{
AssertReaderEquals(info, leftReader, rightReader);
diff --git a/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs b/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs
index 9029af1..7340d4f 100644
--- a/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs
+++ b/src/Lucene.Net.Tests/Index/TestFlushByRamOrCountsPolicy.cs
@@ -9,6 +9,7 @@ using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
+using Lucene.Net.Util;
namespace Lucene.Net.Index
{
@@ -37,9 +38,10 @@ namespace Lucene.Net.Index
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using TestUtil = Lucene.Net.Util.TestUtil;
using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState;
-
- [TestFixture]
+
+ // LUCENENET specific - Specify to unzip the line file docs
+ [UseTempLineDocsFile]
[Timeout(900000)]
public class TestFlushByRamOrCountsPolicy : LuceneTestCase
{
@@ -49,7 +51,6 @@ namespace Lucene.Net.Index
[OneTimeSetUp]
public override void BeforeClass()
{
- UseTempLineDocsFile = true; // LUCENENET specific - Specify to unzip the line file docs
base.BeforeClass();
lineDocFile = new LineFileDocs(Random, DefaultCodecSupportsDocValues);
}
diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriter.cs b/src/Lucene.Net.Tests/Index/TestIndexWriter.cs
index b4cda08..7b2f2a2 100644
--- a/src/Lucene.Net.Tests/Index/TestIndexWriter.cs
+++ b/src/Lucene.Net.Tests/Index/TestIndexWriter.cs
@@ -1163,7 +1163,7 @@ namespace Lucene.Net.Index
internal IndexerThreadInterrupt(TestIndexWriter outerInstance)
{
this.outerInstance = outerInstance;
- this.random = new Random(LuceneTestCase.Random.Next());
+ this.random = new J2N.Randomizer(Random.NextInt64());
// make a little directory for addIndexes
// LUCENE-2239: won't work with NIOFS/MMAP
adder = new MockDirectoryWrapper(this.random, new RAMDirectory());
@@ -1476,6 +1476,7 @@ namespace Lucene.Net.Index
[Test]
[Slow]
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/544")] // LUCENENET TODO: This test occasionally fails
public virtual void TestThreadInterruptDeadlock()
{
IndexerThreadInterrupt t = new IndexerThreadInterrupt(this);
@@ -1516,6 +1517,7 @@ namespace Lucene.Net.Index
/// testThreadInterruptDeadlock but with 2 indexer threads </summary>
[Test]
[Slow]
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/544")] // LUCENENET TODO: This test occasionally fails
public virtual void TestTwoThreadsInterruptDeadlock()
{
IndexerThreadInterrupt t1 = new IndexerThreadInterrupt(this);
diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs
index 78712bd..3ca892b 100644
--- a/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs
+++ b/src/Lucene.Net.Tests/Index/TestIndexWriterExceptions.cs
@@ -167,7 +167,7 @@ namespace Lucene.Net.Index
internal IndexWriter writer;
- internal readonly Random r = new Random(Random.Next());
+ internal readonly Random r = new J2N.Randomizer(Random.NextInt64());
internal volatile Exception failure = null;
public IndexerThread(TestIndexWriterExceptions outerInstance, int i, IndexWriter writer)
@@ -294,7 +294,7 @@ namespace Lucene.Net.Index
this.outerInstance = outerInstance;
}
- internal Random r = new Random(Random.Next());
+ internal Random r = new J2N.Randomizer(Random.NextInt64());
public void Apply(string name)
{
diff --git a/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs b/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs
index 463a918..6d3a73f 100644
--- a/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs
+++ b/src/Lucene.Net.Tests/Index/TestIndexWriterReader.cs
@@ -1070,7 +1070,7 @@ namespace Lucene.Net.Index
this.writer = writer;
this.endTime = endTime;
this.excs = excs;
- rand = new Random(Random.Next());
+ rand = new J2N.Randomizer(Random.NextInt64());
}
internal readonly Random rand;
diff --git a/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs b/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs
index 3a48b69..fb6f81c 100644
--- a/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs
+++ b/src/Lucene.Net.Tests/Index/TestNRTReaderWithThreads.cs
@@ -4,6 +4,7 @@ using Lucene.Net.Attributes;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Support.Threading;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Threading;
using Console = Lucene.Net.Util.SystemConsole;
@@ -97,7 +98,7 @@ namespace Lucene.Net.Index
internal int delCount = 0;
internal int addCount = 0;
internal int type;
- internal readonly Random r = new Random(Random.Next());
+ internal readonly Random r = new J2N.Randomizer(Random.NextInt64());
public RunThread(TestNRTReaderWithThreads outerInstance, int type, IndexWriter writer)
{
diff --git a/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs b/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs
index 9f5d8f3..8f9eb2d 100644
--- a/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs
+++ b/src/Lucene.Net.Tests/Index/TestPerSegmentDeletes.cs
@@ -1,6 +1,7 @@
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
@@ -43,7 +44,7 @@ namespace Lucene.Net.Index
public virtual void TestDeletes1()
{
//IndexWriter.debug2 = System.out;
- Directory dir = new MockDirectoryWrapper(new Random(Random.Next()), new RAMDirectory());
+ Directory dir = new MockDirectoryWrapper(new J2N.Randomizer(Random.NextInt64()), new RAMDirectory());
IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
iwc.SetMergeScheduler(new SerialMergeScheduler());
iwc.SetMaxBufferedDocs(5000);
diff --git a/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs b/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs
index 2e5d822..a260d7f 100644
--- a/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs
+++ b/src/Lucene.Net.Tests/Index/TestRollingUpdates.cs
@@ -44,7 +44,7 @@ namespace Lucene.Net.Index
[Test]
public virtual void TestRollingUpdates_Mem()
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
BaseDirectoryWrapper dir = NewDirectory();
LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues);
diff --git a/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs b/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs
index 19d648a..03eecd1 100644
--- a/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs
+++ b/src/Lucene.Net.Tests/Index/TestStressIndexing2.cs
@@ -1030,7 +1030,7 @@ namespace Lucene.Net.Index
{
try
{
- r = new Random(@base + range + seed);
+ r = new J2N.Randomizer(@base + range + seed);
for (int i = 0; i < iterations; i++)
{
int what = NextInt(100);
diff --git a/src/Lucene.Net.Tests/Index/TestStressNRT.cs b/src/Lucene.Net.Tests/Index/TestStressNRT.cs
index 65d7b3e..cd6521c 100644
--- a/src/Lucene.Net.Tests/Index/TestStressNRT.cs
+++ b/src/Lucene.Net.Tests/Index/TestStressNRT.cs
@@ -187,7 +187,7 @@ namespace Lucene.Net.Index
this.storedOnlyType = storedOnlyType;
this.numCommitting = numCommitting;
this.writer = writer;
- rand = new Random(Random.Next());
+ rand = new J2N.Randomizer(Random.NextInt64());
}
internal Random rand;
@@ -439,7 +439,7 @@ namespace Lucene.Net.Index
this.ndocs = ndocs;
this.tombstones = tombstones;
this.operations = operations;
- rand = new Random(Random.Next());
+ rand = new J2N.Randomizer(Random.NextInt64());
}
internal Random rand;
diff --git a/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs b/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs
index 4191393..0ce678a 100644
--- a/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs
+++ b/src/Lucene.Net.Tests/Index/TestTermVectorsReader.cs
@@ -100,7 +100,7 @@ namespace Lucene.Net.Index
for (int j = 0; j < TERM_FREQ; j++)
{
// positions are always sorted in increasing order
- positions[i][j] = (int)(j * 10 + new Random(1).NextDouble() * 10);
+ positions[i][j] = (int)(j * 10 + Random.NextDouble() * 10); // LUCENENET: Using Random because Math.random() doesn't exist in .NET and it seems to make sense to want this repeatable.
TestToken token = tokens[tokenUpto++] = new TestToken(this);
token.text = testTerms[i];
token.pos = positions[i][j];
diff --git a/src/Lucene.Net.Tests/Index/TestTermdocPerf.cs b/src/Lucene.Net.Tests/Index/TestTermdocPerf.cs
index e5d4115..c68fa45 100644
--- a/src/Lucene.Net.Tests/Index/TestTermdocPerf.cs
+++ b/src/Lucene.Net.Tests/Index/TestTermdocPerf.cs
@@ -3,6 +3,7 @@ using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.IO;
using Console = Lucene.Net.Util.SystemConsole;
@@ -143,7 +144,7 @@ namespace Lucene.Net.Index
int ret = 0;
DocsEnum tdocs = null;
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
for (int i = 0; i < iter; i++)
{
tenum.SeekCeil(new BytesRef("val"));
diff --git a/src/Lucene.Net.Tests/Index/TestTermsEnum.cs b/src/Lucene.Net.Tests/Index/TestTermsEnum.cs
index 4cee9cc..7f2712c 100644
--- a/src/Lucene.Net.Tests/Index/TestTermsEnum.cs
+++ b/src/Lucene.Net.Tests/Index/TestTermsEnum.cs
@@ -52,7 +52,7 @@ namespace Lucene.Net.Index
[Test]
public virtual void Test()
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues);
Directory d = NewDirectory();
MockAnalyzer analyzer = new MockAnalyzer(LuceneTestCase.Random);
diff --git a/src/Lucene.Net.Tests/Search/TestBoolean2.cs b/src/Lucene.Net.Tests/Search/TestBoolean2.cs
index e707b1e..edfd6be 100644
--- a/src/Lucene.Net.Tests/Search/TestBoolean2.cs
+++ b/src/Lucene.Net.Tests/Search/TestBoolean2.cs
@@ -308,7 +308,7 @@ namespace Lucene.Net.Search
for (int i = 0; i < num; i++)
{
int level = Random.Next(3);
- q1 = RandBoolQuery(new Random(Random.Next()), Random.NextBoolean(), level, field, vals, null);
+ q1 = RandBoolQuery(new J2N.Randomizer(Random.NextInt64()), Random.NextBoolean(), level, field, vals, null);
// Can't sort by relevance since floating point numbers may not quite
// match up.
diff --git a/src/Lucene.Net.Tests/Search/TestBooleanMinShouldMatch.cs b/src/Lucene.Net.Tests/Search/TestBooleanMinShouldMatch.cs
index b5d3953..0e240c4 100644
--- a/src/Lucene.Net.Tests/Search/TestBooleanMinShouldMatch.cs
+++ b/src/Lucene.Net.Tests/Search/TestBooleanMinShouldMatch.cs
@@ -353,10 +353,10 @@ namespace Lucene.Net.Search
for (int i = 0; i < num; i++)
{
int lev = Random.Next(maxLev);
- int seed = Random.Next();
- BooleanQuery q1 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null);
- // BooleanQuery q2 = TestBoolean2.randBoolQuery(new Random(seed), lev, field, vals, minNrCB);
- BooleanQuery q2 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null);
+ long seed = Random.NextInt64();
+ BooleanQuery q1 = TestBoolean2.RandBoolQuery(new J2N.Randomizer(seed), true, lev, field, vals, null);
+ // BooleanQuery q2 = TestBoolean2.randBoolQuery(new J2N.Randomizer(seed), lev, field, vals, minNrCB);
+ BooleanQuery q2 = TestBoolean2.RandBoolQuery(new J2N.Randomizer(seed), true, lev, field, vals, null);
// only set minimumNumberShouldMatch on the top level query since setting
// at a lower level can change the score.
minNrCB.PostCreate(q2);
diff --git a/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs b/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs
index 9ae5da9..598031c 100644
--- a/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs
+++ b/src/Lucene.Net.Tests/Search/TestLiveFieldValues.cs
@@ -9,6 +9,7 @@ using System.Threading;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
+using RandomizedTesting.Generators;
namespace Lucene.Net.Search
{
@@ -78,7 +79,7 @@ namespace Lucene.Net.Search
for (int t = 0; t < numThreads; t++)
{
int threadID = t;
- Random threadRandom = new Random(Random.Next());
+ Random threadRandom = new J2N.Randomizer(Random.NextInt64());
ThreadJob thread = new ThreadAnonymousClass(w, mgr, missing, rt, startingGun, iters, idCount, reopenChance, deleteChance, addChance, t, threadID, threadRandom);
threads.Add(thread);
thread.Start();
diff --git a/src/Lucene.Net.Tests/Search/TestSimpleExplanations.cs b/src/Lucene.Net.Tests/Search/TestSimpleExplanations.cs
index 0e36eb8..f325a03 100644
--- a/src/Lucene.Net.Tests/Search/TestSimpleExplanations.cs
+++ b/src/Lucene.Net.Tests/Search/TestSimpleExplanations.cs
@@ -1,4 +1,4 @@
-using NUnit.Framework;
+using NUnit.Framework;
namespace Lucene.Net.Search
{
@@ -274,6 +274,9 @@ namespace Lucene.Net.Search
}
[Test]
+#if NETFRAMEWORK
+ [AwaitsFix(BugUrl = "https://github.com/apache/lucenenet/issues/546")] // LUCENENET TODO: This test fails on x86 .NET Framework in Release mode only
+#endif
public virtual void TestDMQ8()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
diff --git a/src/Lucene.Net.Tests/Search/TestSloppyPhraseQuery2.cs b/src/Lucene.Net.Tests/Search/TestSloppyPhraseQuery2.cs
index b2afefb..02529ac 100644
--- a/src/Lucene.Net.Tests/Search/TestSloppyPhraseQuery2.cs
+++ b/src/Lucene.Net.Tests/Search/TestSloppyPhraseQuery2.cs
@@ -1,4 +1,5 @@
-using NUnit.Framework;
+using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
namespace Lucene.Net.Search
@@ -212,7 +213,7 @@ namespace Lucene.Net.Search
[Test]
public virtual void TestRandomIncreasingSloppiness()
{
- int seed = Random.Next();
+ long seed = Random.NextInt64();
MultiPhraseQuery q1 = RandomPhraseQuery(seed);
MultiPhraseQuery q2 = RandomPhraseQuery(seed);
for (int i = 0; i < 10; i++)
@@ -223,9 +224,9 @@ namespace Lucene.Net.Search
}
}
- private MultiPhraseQuery RandomPhraseQuery(int seed)
+ private MultiPhraseQuery RandomPhraseQuery(long seed)
{
- Random random = new Random(seed);
+ Random random = new J2N.Randomizer(seed);
int length = TestUtil.NextInt32(random, 2, 5);
MultiPhraseQuery pq = new MultiPhraseQuery();
int position = 0;
diff --git a/src/Lucene.Net.Tests/Search/TestSortRandom.cs b/src/Lucene.Net.Tests/Search/TestSortRandom.cs
index 2689458..f97a935 100644
--- a/src/Lucene.Net.Tests/Search/TestSortRandom.cs
+++ b/src/Lucene.Net.Tests/Search/TestSortRandom.cs
@@ -51,7 +51,7 @@ namespace Lucene.Net.Search
[Test]
public virtual void TestRandomStringSort()
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
int NUM_DOCS = AtLeast(100);
Directory dir = NewDirectory();
diff --git a/src/Lucene.Net.Tests/Util/Fst/Test2BFST.cs b/src/Lucene.Net.Tests/Util/Fst/Test2BFST.cs
index 348542d..776bae1 100644
--- a/src/Lucene.Net.Tests/Util/Fst/Test2BFST.cs
+++ b/src/Lucene.Net.Tests/Util/Fst/Test2BFST.cs
@@ -1,5 +1,6 @@
-using Lucene.Net.Support;
+using Lucene.Net.Support;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
@@ -42,7 +43,7 @@ namespace Lucene.Net.Util.Fst
{
int[] ints = new int[7];
Int32sRef input = new Int32sRef(ints, 0, ints.Length);
- int seed = Random.Next();
+ long seed = Random.NextInt64();
Directory dir = new MMapDirectory(CreateTempDir("2BFST"));
@@ -59,7 +60,7 @@ namespace Lucene.Net.Util.Fst
Builder<object> b = new Builder<object>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, int.MaxValue, outputs, null, doPack, PackedInt32s.COMPACT, true, 15);
int count = 0;
- Random r = new Random(seed);
+ Random r = new J2N.Randomizer(seed);
int[] ints2 = new int[200];
Int32sRef input2 = new Int32sRef(ints2, 0, ints2.Length);
while (true)
@@ -89,7 +90,7 @@ namespace Lucene.Net.Util.Fst
Console.WriteLine("\nTEST: now verify [fst size=" + fst.GetSizeInBytes() + "; nodeCount=" + fst.NodeCount + "; arcCount=" + fst.ArcCount + "]");
Arrays.Fill(ints2, 0);
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
for (int i = 0; i < count; i++)
{
@@ -109,7 +110,7 @@ namespace Lucene.Net.Util.Fst
Int32sRefFSTEnum<object> fstEnum = new Int32sRefFSTEnum<object>(fst);
Arrays.Fill(ints2, 0);
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
int upto = 0;
while (true)
{
@@ -157,7 +158,7 @@ namespace Lucene.Net.Util.Fst
BytesRef output = new BytesRef(outputBytes);
Arrays.Fill(ints, 0);
int count = 0;
- Random r = new Random(seed);
+ Random r = new J2N.Randomizer(seed);
while (true)
{
r.NextBytes(outputBytes);
@@ -180,7 +181,7 @@ namespace Lucene.Net.Util.Fst
{
Console.WriteLine("\nTEST: now verify [fst size=" + fst.GetSizeInBytes() + "; nodeCount=" + fst.NodeCount + "; arcCount=" + fst.ArcCount + "]");
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
Arrays.Fill(ints, 0);
for (int i = 0; i < count; i++)
@@ -198,7 +199,7 @@ namespace Lucene.Net.Util.Fst
Int32sRefFSTEnum<BytesRef> fstEnum = new Int32sRefFSTEnum<BytesRef>(fst);
Arrays.Fill(ints, 0);
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
int upto = 0;
while (true)
{
@@ -243,7 +244,7 @@ namespace Lucene.Net.Util.Fst
Arrays.Fill(ints, 0);
int count = 0;
- Random r = new Random(seed);
+ Random r = new J2N.Randomizer(seed);
while (true)
{
//System.out.println("add: " + input + " -> " + output);
@@ -270,7 +271,7 @@ namespace Lucene.Net.Util.Fst
Arrays.Fill(ints, 0);
output = 1;
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
for (int i = 0; i < count; i++)
{
if (i % 1000000 == 0)
@@ -290,7 +291,7 @@ namespace Lucene.Net.Util.Fst
Int32sRefFSTEnum<long?> fstEnum = new Int32sRefFSTEnum<long?>(fst);
Arrays.Fill(ints, 0);
- r = new Random(seed);
+ r = new J2N.Randomizer(seed);
int upto = 0;
output = 1;
while (true)
diff --git a/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs b/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs
index 014ec0b..2a189a6 100644
--- a/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs
+++ b/src/Lucene.Net.Tests/Util/Fst/TestFSTs.cs
@@ -291,7 +291,7 @@ namespace Lucene.Net.Util.Fst
private void TestRandomWords(int maxNumWords, int numIter)
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
for (int iter = 0; iter < numIter; iter++)
{
if (Verbose)
@@ -426,7 +426,7 @@ namespace Lucene.Net.Util.Fst
if (ord > 0)
{
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
// Now confirm BytesRefFSTEnum and TermsEnum act the
// same:
BytesRefFSTEnum<long?> fstEnum = new BytesRefFSTEnum<long?>(fst);
@@ -829,7 +829,7 @@ namespace Lucene.Net.Util.Fst
{
if (ord == 0)
{
- rand = new Random(17);
+ rand = new J2N.Randomizer(17);
}
return outputs.NewPair(ord, TestUtil.NextInt32(rand, 1, 5000));
}
@@ -860,7 +860,7 @@ namespace Lucene.Net.Util.Fst
{
if (ord == 0)
{
- rand = new Random(17);
+ rand = new J2N.Randomizer(17);
}
return (long)TestUtil.NextInt32(rand, 1, 5000);
}
diff --git a/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs b/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs
index 7ed4fff..bd60e05 100644
--- a/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs
+++ b/src/Lucene.Net.Tests/Util/Packed/TestPackedInts.cs
@@ -431,7 +431,7 @@ namespace Lucene.Net.Util.Packed
private static void Fill(PackedInt32s.Mutable packedInt, long maxValue, long randomSeed)
{
- Random rnd2 = new Random((int)randomSeed);
+ Random rnd2 = new J2N.Randomizer(randomSeed);
for (int i = 0; i < packedInt.Count; i++)
{
long value = TestUtil.NextInt64(rnd2, 0, maxValue);
diff --git a/src/Lucene.Net.Tests/Util/Test2BPagedBytes.cs b/src/Lucene.Net.Tests/Util/Test2BPagedBytes.cs
index d70d43b..9e0723c 100644
--- a/src/Lucene.Net.Tests/Util/Test2BPagedBytes.cs
+++ b/src/Lucene.Net.Tests/Util/Test2BPagedBytes.cs
@@ -50,7 +50,7 @@ namespace Lucene.Net.Util
long netBytes = 0;
long seed = Random.NextInt64();
long lastFP = 0;
- Random r2 = new Random((int)seed);
+ Random r2 = new J2N.Randomizer(seed);
while (netBytes < 1.1 * int.MaxValue)
{
int numBytes = TestUtil.NextInt32(r2, 1, 32768);
@@ -68,7 +68,7 @@ namespace Lucene.Net.Util
input.Dispose();
PagedBytes.Reader reader = pb.Freeze(true);
- r2 = new Random((int)seed);
+ r2 = new J2N.Randomizer(seed);
netBytes = 0;
while (netBytes < 1.1 * int.MaxValue)
{
diff --git a/src/Lucene.Net.Tests/Util/TestFieldCacheSanityChecker.cs b/src/Lucene.Net.Tests/Util/TestFieldCacheSanityChecker.cs
index 5bd612b..99e9bd4 100644
--- a/src/Lucene.Net.Tests/Util/TestFieldCacheSanityChecker.cs
+++ b/src/Lucene.Net.Tests/Util/TestFieldCacheSanityChecker.cs
@@ -1,4 +1,4 @@
-using Lucene.Net.Documents;
+using Lucene.Net.Documents;
using Lucene.Net.Search;
using NUnit.Framework;
using System;
@@ -139,7 +139,7 @@ namespace Lucene.Net.Util
if (0 < insanity.Length)
{
- DumpArray(GetTestClass().Name + "#" + TestName + " INSANITY", insanity, Console.Error);
+ DumpArray(TestType.Name + "#" + TestName + " INSANITY", insanity, Console.Error);
}
Assert.AreEqual(0, insanity.Length, "shouldn't be any cache insanity");
diff --git a/src/Lucene.Net.Tests/Util/TestFixedBitSet.cs b/src/Lucene.Net.Tests/Util/TestFixedBitSet.cs
index 297b6a5..e622c47 100644
--- a/src/Lucene.Net.Tests/Util/TestFixedBitSet.cs
+++ b/src/Lucene.Net.Tests/Util/TestFixedBitSet.cs
@@ -298,10 +298,10 @@ namespace Lucene.Net.Util
[Test, LuceneNetSpecific]
public void TestClearLarge()
{
+ Random random = Random;
int iters = AtLeast(1000);
for (int it = 0; it < iters; it++)
{
- Random random = new Random();
int sz = AtLeast(1200);
FixedBitSet a = new FixedBitSet(sz);
FixedBitSet b = new FixedBitSet(sz);
diff --git a/src/Lucene.Net.Tests/Util/TestLongBitSet.cs b/src/Lucene.Net.Tests/Util/TestLongBitSet.cs
index 829592e..badd258 100644
--- a/src/Lucene.Net.Tests/Util/TestLongBitSet.cs
+++ b/src/Lucene.Net.Tests/Util/TestLongBitSet.cs
@@ -243,10 +243,10 @@ namespace Lucene.Net.Util
[Test, LuceneNetSpecific]
public void TestClearLarge()
{
+ Random random = Random;
int iters = AtLeast(1000);
for (int it = 0; it < iters; it++)
{
- Random random = new Random();
int sz = AtLeast(1200);
Int64BitSet a = new Int64BitSet(sz);
Int64BitSet b = new Int64BitSet(sz);
diff --git a/src/Lucene.Net.Tests/Util/TestMergedIterator.cs b/src/Lucene.Net.Tests/Util/TestMergedIterator.cs
index a7ef2e9..55e9c06 100644
--- a/src/Lucene.Net.Tests/Util/TestMergedIterator.cs
+++ b/src/Lucene.Net.Tests/Util/TestMergedIterator.cs
@@ -3,6 +3,7 @@ using System;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
+using RandomizedTesting.Generators;
namespace Lucene.Net.Util
{
@@ -123,7 +124,7 @@ namespace Lucene.Net.Util
{
// Build a random number of lists
IList<int?> expected = new JCG.List<int?>();
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
int numLists = itrsWithVal + random.Next(1000 - itrsWithVal);
IList<int>[] lists = new IList<int>[numLists];
for (int i = 0; i < numLists; i++)
@@ -292,7 +293,7 @@ namespace Lucene.Net.Util
{
// Build a random number of lists
IList<int?> expected = new JCG.List<int?>();
- Random random = new Random(Random.Next());
+ Random random = new J2N.Randomizer(Random.NextInt64());
int numLists = itrsWithVal + random.Next(1000 - itrsWithVal);
IList<int>[] lists = new IList<int>[numLists];
for (int i = 0; i < numLists; i++)
diff --git a/src/Lucene.Net.Tests/Util/TestOpenBitSet.cs b/src/Lucene.Net.Tests/Util/TestOpenBitSet.cs
index 2bf549c..cb48bfa 100644
--- a/src/Lucene.Net.Tests/Util/TestOpenBitSet.cs
+++ b/src/Lucene.Net.Tests/Util/TestOpenBitSet.cs
@@ -356,10 +356,10 @@ namespace Lucene.Net.Util
[Test, LuceneNetSpecific]
public void TestClearLarge()
{
+ Random random = Random;
int iters = AtLeast(1000);
for (int it = 0; it < iters; it++)
{
- Random random = new Random();
int sz = AtLeast(1200);
OpenBitSet a = new OpenBitSet(sz);
OpenBitSet b = new OpenBitSet(sz);
diff --git a/src/Lucene.Net.Tests/Util/TestSetOnce.cs b/src/Lucene.Net.Tests/Util/TestSetOnce.cs
index 6ef60bc..2f572eb 100644
--- a/src/Lucene.Net.Tests/Util/TestSetOnce.cs
+++ b/src/Lucene.Net.Tests/Util/TestSetOnce.cs
@@ -1,9 +1,8 @@
using J2N.Threading;
-using Lucene.Net.Support.Threading;
using NUnit.Framework;
+using RandomizedTesting.Generators;
using System;
using System.Globalization;
-using System.Threading;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Util
@@ -46,7 +45,7 @@ namespace Lucene.Net.Util
public SetOnceThread(Random random)
{
- RAND = new Random(random.Next());
+ RAND = new J2N.Randomizer(random.NextInt64());
}
public override void Run()
diff --git a/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs b/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs
index 0fd57a1..10dae67 100644
--- a/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs
+++ b/src/Lucene.Net.Tests/Util/TestWeakIdentityMap.cs
@@ -215,7 +215,7 @@
// {
// for (int t = 0; t < threadCount; t++)
// {
-// Random rnd = new Random(Random.Next());
+// Random rnd = new J2N.Randomizer(Random.NextInt64());
// var worker = new RunnableAnonymousClass(this, keyCount, map, keys, rnd);
// workers[t] = worker;
// worker.Start();
diff --git a/src/Lucene.Net/Util/BytesRef.cs b/src/Lucene.Net/Util/BytesRef.cs
index 23a80f4..87bb54e 100644
--- a/src/Lucene.Net/Util/BytesRef.cs
+++ b/src/Lucene.Net/Util/BytesRef.cs
@@ -204,13 +204,13 @@ namespace Lucene.Net.Util
/// Calculates the hash code as required by <see cref="Index.TermsHash"/> during indexing.
/// <para/> This is currently implemented as MurmurHash3 (32
/// bit), using the seed from
- /// <see cref="StringHelper.GOOD_FAST_HASH_SEED"/>, but is subject to
+ /// <see cref="StringHelper.GoodFastHashSeed"/>, but is subject to
/// change from release to release.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
- return StringHelper.Murmurhash3_x86_32(this, StringHelper.GOOD_FAST_HASH_SEED);
+ return StringHelper.Murmurhash3_x86_32(this, StringHelper.GoodFastHashSeed);
}
public override bool Equals(object other)
diff --git a/src/Lucene.Net/Util/BytesRefHash.cs b/src/Lucene.Net/Util/BytesRefHash.cs
index 4ff425d..19fba5f 100644
--- a/src/Lucene.Net/Util/BytesRefHash.cs
+++ b/src/Lucene.Net/Util/BytesRefHash.cs
@@ -525,7 +525,7 @@ namespace Lucene.Net.Util
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int DoHash(byte[] bytes, int offset, int length)
{
- return StringHelper.Murmurhash3_x86_32(bytes, offset, length, StringHelper.GOOD_FAST_HASH_SEED);
+ return StringHelper.Murmurhash3_x86_32(bytes, offset, length, StringHelper.GoodFastHashSeed);
}
/// <summary>
diff --git a/src/Lucene.Net/Util/StringHelper.cs b/src/Lucene.Net/Util/StringHelper.cs
index 50aff05..8826b3c 100644
--- a/src/Lucene.Net/Util/StringHelper.cs
+++ b/src/Lucene.Net/Util/StringHelper.cs
@@ -31,38 +31,25 @@ namespace Lucene.Net.Util
/// </summary>
public static class StringHelper // LUCENENET specific - marked static and removed private constructor
{
- /// <summary>
- /// Pass this as the seed to <see cref="Murmurhash3_x86_32(byte[], int, int, int)"/>. </summary>
-
- //Singleton-esque member. Only created once
- public static readonly int GOOD_FAST_HASH_SEED = InitializeHashSeed();
-
// Poached from Guava: set a different salt/seed
// for each JVM instance, to frustrate hash key collision
// denial of service attacks, and to catch any places that
// somehow rely on hash function/order across JVM
// instances:
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static int InitializeHashSeed()
- {
- // LUCENENET specific - reformatted with :
- string prop = SystemProperties.GetProperty("tests:seed", null);
- if (prop != null)
- {
- // So if there is a test failure that relied on hash
- // order, we remain reproducible based on the test seed:
- if (prop.Length > 8)
- {
- prop = prop.Substring(prop.Length - 8);
- }
- return Convert.ToInt32(prop, 16);
- }
- else
- {
- return (int)J2N.Time.CurrentTimeMilliseconds();
- }
- }
+ // LUCENENET specific - Since NUnit considers hash seed a per-test setting, we make the
+ // backing field internal and writable so it can be set by the test framework.
+ // The tests:seed system property is only applicable to the test environment, as it has no
+ // useful purpose in production.
+ internal static int goodFastHashSeed = (int)J2N.Time.CurrentTimeMilliseconds();
+
+ /// <summary>
+ /// Pass this as the seed to <see cref="Murmurhash3_x86_32(byte[], int, int, int)"/>. </summary>
+ //Singleton-esque member. Only created once
+ public static int GoodFastHashSeed => goodFastHashSeed;
+
+ [Obsolete("Use GoodFastHashSeed instead. This field will be removed in 4.8.0 release candidate.")]
+ public static int GOOD_FAST_HASH_SEED => goodFastHashSeed;
/// <summary>
/// Compares two <see cref="BytesRef"/>, element by element, and returns the