-
Notifications
You must be signed in to change notification settings - Fork 641
/
Copy pathLuceneTestCase.cs
3248 lines (2926 loc) · 143 KB
/
LuceneTestCase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Analysis;
using Lucene.Net.Codecs;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Support.IO;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util.Automaton;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;
using RandomizedTesting.Generators;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using static Lucene.Net.Search.FieldCache;
using static Lucene.Net.Util.FieldCacheSanityChecker;
using After = NUnit.Framework.TearDownAttribute;
using Assert = Lucene.Net.TestFramework.Assert;
using AssumptionViolatedException = NUnit.Framework.InconclusiveException;
using Before = NUnit.Framework.SetUpAttribute;
using Console = Lucene.Net.Util.SystemConsole;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using JCG = J2N.Collections.Generic;
using OneTimeSetUp = NUnit.Framework.OneTimeSetUpAttribute;
using OneTimeTearDown = NUnit.Framework.OneTimeTearDownAttribute;
using Test = NUnit.Framework.TestAttribute;
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>
/// Base class for all Lucene.Net unit tests.
///
/// <h3>Class and instance setup.</h3>
///
/// <para>
/// The preferred way to specify class (suite-level) setup/cleanup is to override
/// <see cref="OneTimeSetUp"/> and <see cref="OneTimeTearDown"/>. Be sure
/// to call <c>base.OneTimeSetUp()</c> BEFORE you initialize your class and
/// call <c>base.OneTimeTearDown()</c> AFTER you clean up your class. NUnit
/// will find the <see cref="NUnit.Framework.OneTimeSetUpAttribute"/> and
/// <see cref="NUnit.Framework.OneTimeTearDownAttribute"/> of the base class,
/// so using them on the <see cref="OneTimeSetUp"/> and
/// <see cref="OneTimeTearDown"/> method overrides is not strictly required. Any
/// code in these methods is executed within the test framework's control and
/// ensure proper setup has been made. <b>Try not to use static initializers
/// (including complex readonly field initializers).</b> Static initializers are
/// executed before any setup rules are fired and may cause you (or somebody
/// else) headaches.
/// </para>
///
/// <para>
/// For instance-level setup, use <see cref="Before"/> and <see cref="After"/> annotated
/// methods. If you override either <see cref="SetUp()"/> or <see cref="TearDown()"/> in
/// your subclass, make sure you call <c>base.SetUp()</c> and
/// <c>base.TearDown()</c>. This is detected and enforced.
/// </para>
///
/// <h3>Specifying test cases</h3>
///
/// <para>
/// Any test method annotated with <see cref="Test"/> is considered a test case.
/// </para>
///
/// <h3>Randomized execution and test facilities</h3>
///
/// <para>
/// <see cref="LuceneTestCase"/> uses a custom <see cref="TestFixtureAttribute"/> to execute test cases.
/// The custom <see cref="TestFixtureAttribute"/> has built-in support for test randomization
/// including access to a repeatable <see cref="Random"/> instance. See
/// <see cref="Random"/> property. Any test using <see cref="Random"/> acquired from
/// <see cref="Random"/> should be fully reproducible (assuming no race conditions
/// between threads etc.). The initial seed for a test case is reported in the failure
/// test message.
/// </para>
/// <para>
/// The seed can be configured with a RunSettings file, a <c>lucene.testsettings.json</c> JSON file,
/// an environment variable, or using <see cref="RandomSeedAttribute"/> at the assembly level.
/// It is recommended to configure the culture also, since they are randomly picked from a list
/// of cultures installed on a given machine, so the culture will vary from one machine to the next.
/// </para>
///
/// <h4><i>.runsettings</i> File Configuration Example</h4>
///
/// <code>
/// <RunSettings>
/// <TestRunParameters>
/// <Parameter name="tests:seed" value="0x1ffa1d067056b0e6" />
/// <Parameter name="tests:culture" value="sw-TZ" />
/// </TestRunParameters>
/// </RunSettings>
/// </code>
/// <para>
/// See the <i>.runsettings</i> documentation at: <a href="https://docs.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file">
/// https://docs.microsoft.com/en-us/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file</a>.
/// </para>
///
/// <h4>Attribute Configuration Example</h4>
///
/// <code>
/// [assembly: Lucene.Net.Util.RandomSeed("0x1ffa1d067056b0e6")]
/// [assembly: NUnit.Framework.SetCulture("sw-TZ")]
/// </code>
///
/// <h4><i>lucene.testsettings.json</i> File Configuration Example</h4>
///
/// <para>
/// Add a file named <i>lucene.testsettings.json</i> to the executable directory or
/// any directory between the executable and the root of the drive with the following contents.
/// </para>
///
/// <code>
/// {
/// "tests": {
/// "seed": "0x1ffa1d067056b0e6",
/// "culture": "sw-TZ"
/// }
/// }
/// </code>
///
/// <h4>Environment Variable Configuration Example</h4>
///
/// <list type="table">
/// <listheader>
/// <term>Variable</term>
/// <term>Value</term>
/// </listheader>
/// <item>
/// <term>lucene:tests:seed</term>
/// <term>0x1ffa1d067056b0e6</term>
/// </item>
/// <item>
/// <term>lucene:tests:culture</term>
/// <term>sw-TZ</term>
/// </item>
/// </list>
///
/// </summary>
[TestFixture]
public abstract partial class LuceneTestCase //: Assert // Wait long for leaked threads to complete before failure. zk needs this. - See LUCENE-3995 for rationale.
{
// --------------------------------------------------------------------
// Test groups, system properties and other annotations modifying tests
// --------------------------------------------------------------------
internal const string SYSPROP_NIGHTLY = "tests:nightly";
internal const string SYSPROP_WEEKLY = "tests:weekly";
internal const string SYSPROP_AWAITSFIX = "tests:awaitsfix";
internal const string SYSPROP_SLOW = "tests:slow";
internal const string SYSPROP_BADAPPLES = "tests:badapples"; // LUCENENET specific - made internal, because not fully implemented
///// <seealso cref="IgnoreAfterMaxFailures"/>
internal const string SYSPROP_MAXFAILURES = "tests:maxfailures"; // LUCENENET specific - made internal, because not fully implemented
///// <seealso cref="IgnoreAfterMaxFailures"/>
internal const string SYSPROP_FAILFAST = "tests:failfast"; // LUCENENET specific - made internal, because not fully implemented
private class LuceneDelegatingTestCommand : DelegatingTestCommand
{
private readonly Func<bool> shouldSkip;
public LuceneDelegatingTestCommand(TestCommand command, Func<bool> shouldSkip, string skipReason) : base(command)
{
this.shouldSkip = shouldSkip ?? throw new ArgumentNullException(nameof(shouldSkip));
SkipReason = skipReason ?? throw new ArgumentNullException(nameof(skipReason));
}
public RunState RunState { get; set; } = RunState.Skipped;
public string SkipReason { get; }
public override TestResult Execute(TestExecutionContext context)
{
var test = context.CurrentTest;
// The test framework setting overrides the NUnit category setting, if false
bool skip = shouldSkip();
if (skip)
{
test.RunState = RunState;
test.Properties.Set(PropertyNames.SkipReason, SkipReason);
}
context.CurrentResult = test.MakeTestResult();
if (!skip)
{
try
{
context.CurrentResult = innerCommand.Execute(context);
}
catch (Exception ex)
{
context.CurrentResult.RecordException(ex);
}
}
return context.CurrentResult;
}
}
/// <summary>
/// Attribute for tests that should only be run during nightly builds.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class NightlyAttribute : System.Attribute
, IApplyToTest, IApplyToContext, IWrapTestMethod
{
private const string SKIP_REASON = "This is a nightly test.";
void IApplyToTest.ApplyToTest(NUnit.Framework.Internal.Test test)
{
// This method is called before initialization. The only thing
// we can do here is set the category.
test.Properties.Add(PropertyNames.Category, "Nightly");
}
void IApplyToContext.ApplyToContext(TestExecutionContext context)
{
// Cover the case where this attribute is applied to the whole test fixture
var currentTest = context.CurrentTest;
if (!TestNightly && currentTest is NUnit.Framework.Internal.TestFixture fixture)
{
foreach (var testInterface in fixture.Tests)
{
var test = (NUnit.Framework.Internal.Test)testInterface;
test.RunState = RunState.Skipped;
test.Properties.Set(PropertyNames.SkipReason, SKIP_REASON);
}
}
}
TestCommand ICommandWrapper.Wrap(TestCommand command)
{
// This is to cover the case where the test is decorated with the attribute
// directly.
return new LuceneDelegatingTestCommand(command, () => !TestNightly, SKIP_REASON);
}
}
/// <summary>
/// Attribute for tests that should only be run during weekly builds.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class WeeklyAttribute : System.Attribute
, IApplyToTest, IApplyToContext, IWrapTestMethod
{
private const string SKIP_REASON = "This is a weekly test.";
void IApplyToTest.ApplyToTest(NUnit.Framework.Internal.Test test)
{
// This method is called before initialization. The only thing
// we can do here is set the category.
test.Properties.Add(PropertyNames.Category, "Weekly");
}
void IApplyToContext.ApplyToContext(TestExecutionContext context)
{
// Cover the case where this attribute is applied to the whole test fixture
var currentTest = context.CurrentTest;
if (!TestWeekly && currentTest is NUnit.Framework.Internal.TestFixture fixture)
{
foreach (var testInterface in fixture.Tests)
{
var test = (NUnit.Framework.Internal.Test)testInterface;
test.RunState = RunState.Skipped;
test.Properties.Set(PropertyNames.SkipReason, SKIP_REASON);
}
}
}
TestCommand ICommandWrapper.Wrap(TestCommand command)
{
// This is to cover the case where the test is decorated with the attribute
// directly.
return new LuceneDelegatingTestCommand(command, () => !TestWeekly, SKIP_REASON);
}
}
/// <summary>
/// Attribute for tests which exhibit a known issue and are temporarily disabled.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class AwaitsFixAttribute : System.Attribute
, IApplyToTest, IApplyToContext, IWrapTestMethod
{
void IApplyToTest.ApplyToTest(NUnit.Framework.Internal.Test test)
{
// This method is called before initialization. The only thing
// we can do here is set the category.
test.Properties.Add(PropertyNames.Category, "AwaitsFix");
}
void IApplyToContext.ApplyToContext(TestExecutionContext context)
{
// Cover the case where this attribute is applied to the whole test fixture
var currentTest = context.CurrentTest;
if (!TestAwaitsFix && currentTest is NUnit.Framework.Internal.TestFixture fixture)
{
foreach (var testInterface in fixture.Tests)
{
var test = (NUnit.Framework.Internal.Test)testInterface;
test.RunState = RunState.Skipped;
test.Properties.Set(PropertyNames.SkipReason, BugUrl);
}
}
}
TestCommand ICommandWrapper.Wrap(TestCommand command)
{
// This is to cover the case where the test is decorated with the attribute
// directly.
return new LuceneDelegatingTestCommand(command, () => !TestAwaitsFix, BugUrl) { RunState = RunState.Ignored };
}
/// <summary>
/// Point to issue tracker entry. </summary>
public string BugUrl { get; set; } = "A known bug is being investigated regarding this issue.";
}
/// <summary>
/// Attribute for tests that are slow. Slow tests do run by default but can be
/// disabled if a quick run is needed.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class SlowAttribute : System.Attribute
, IApplyToTest, IApplyToContext, IWrapTestMethod
{
void IApplyToTest.ApplyToTest(NUnit.Framework.Internal.Test test)
{
// This method is called before initialization. The only thing
// we can do here is set the category.
test.Properties.Add(PropertyNames.Category, "Slow");
}
void IApplyToContext.ApplyToContext(TestExecutionContext context)
{
// Cover the case where this attribute is applied to the whole test fixture
var currentTest = context.CurrentTest;
if (!TestSlow && currentTest is NUnit.Framework.Internal.TestFixture fixture)
{
foreach (var testInterface in fixture.Tests)
{
var test = (NUnit.Framework.Internal.Test)testInterface;
test.RunState = RunState.Skipped;
test.Properties.Set(PropertyNames.SkipReason, Message);
}
}
}
TestCommand ICommandWrapper.Wrap(TestCommand command)
{
// This is to cover the case where the test is decorated with the attribute
// directly.
return new LuceneDelegatingTestCommand(command, () => !TestSlow, Message);
}
public string Message { get; set; } = "This test is slow.";
}
/////// <summary>
/////// Attribute for tests that fail frequently and should
/////// be moved to a <a href="https://builds.apache.org/job/Lucene-BadApples-trunk-java7/">"vault" plan in Jenkins</a>.
///////
/////// Tests annotated with this will be turned off by default. If you want to enable
/////// them, set:
/////// <pre>
/////// -Dtests.badapples=true
/////// </pre>
/////// </summary>
////[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
////[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
////public class BadAppleAttribute : System.Attribute
////{
//// /// <summary>
//// /// Point to issue tracker entry. </summary>
//// public virtual string BugUrl { get; set; }
////}
/// <summary>
/// Attribute for test classes that should avoid certain codec types
/// (because they are expensive, for example).
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class SuppressCodecsAttribute : System.Attribute
{
private static readonly Regex WHITESPACE_REMOVAL = new Regex(@"\s*,\s*", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// Constructor for CLS compliance.
/// </summary>
/// <param name="codecs">A comma-deliminated set of codec names.</param>
public SuppressCodecsAttribute(string codecs)
{
this.Value = WHITESPACE_REMOVAL.Split(codecs);
}
[CLSCompliant(false)]
public SuppressCodecsAttribute(params string[] value)
{
this.Value = value;
}
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public string[] Value { get; private set; }
}
/// <summary>
/// Marks any suites which are known not to close all the temporary
/// files. This may prevent temp files and folders from being cleaned
/// up after the suite is completed.
/// </summary>
/// <seealso cref="LuceneTestCase.CreateTempDir()"/>
/// <seealso cref="LuceneTestCase.CreateTempFile(string, string)"/>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
[SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "API looks better with this nested.")]
public sealed class SuppressTempFileChecksAttribute : System.Attribute
{
/// <summary>
/// Point to issue tracker entry. </summary>
public string BugUrl { get; set; } = "None";
}
// -----------------------------------------------------------------
// Truly immutable fields and constants, initialized once and valid
// for all suites ever since.
// -----------------------------------------------------------------
// :Post-Release-Update-Version.LUCENE_XY:
/// <summary>
/// Use this constant when creating Analyzers and any other version-dependent stuff.
/// <para/><b>NOTE:</b> Change this when development starts for new Lucene version:
/// </summary>
public const LuceneVersion TEST_VERSION_CURRENT = LuceneVersion.LUCENE_48;
// LUCENENET specific - need to jump through a few hoops in order to
// ensure the test configuration data is loaded before anything utilizes
// it. We simply isolate this all in a SystemPropertyData class that is
// lazily loaded the first time the SystemPropertyHolder property is called.
private static SystemPropertyData testProperties;
private static SystemPropertyData TestProperties
=> LazyInitializer.EnsureInitialized(ref testProperties, () => new SystemPropertyData());
/// <summary>
/// Used to defer static initialization of system properties
/// until they are called explicitly.
/// </summary>
private class SystemPropertyData // LUCENENET specific
{
public SystemPropertyData()
{
Verbose = SystemProperties.GetPropertyAsBoolean("tests:verbose", // LUCENENET specific - reformatted with :
#if DEBUG
true
#else
false
#endif
);
UseInfoStream = SystemProperties.GetPropertyAsBoolean("tests:infostream", Verbose); // LUCENENET specific - reformatted with :
RandomMultiplier = SystemProperties.GetPropertyAsInt32("tests:multiplier", 1); // LUCENENET specific - reformatted with :
TestCodec = SystemProperties.GetProperty("tests:codec", "random");// LUCENENET specific - reformatted with :
TestPostingsFormat = SystemProperties.GetProperty("tests:postingsformat", "random"); // LUCENENET specific - reformatted with :
TestDocValuesFormat = SystemProperties.GetProperty("tests:docvaluesformat", "random"); // LUCENENET specific - reformatted with :
TestDirectory = SystemProperties.GetProperty("tests:directory", "random"); // LUCENENET specific - reformatted with :
TestLineDocsFile = SystemProperties.GetProperty("tests:linedocsfile", DEFAULT_LINE_DOCS_FILE); // LUCENENET specific - reformatted with :
TestNightly = SystemProperties.GetPropertyAsBoolean(SYSPROP_NIGHTLY, false);
TestWeekly = SystemProperties.GetPropertyAsBoolean(SYSPROP_WEEKLY, false);
TestAwaitsFix = SystemProperties.GetPropertyAsBoolean(SYSPROP_AWAITSFIX, false);
TestSlow = SystemProperties.GetPropertyAsBoolean(SYSPROP_SLOW, true); // LUCENENET specific - made default true, as per the docs
TestThrottling = TestNightly ? Throttling.SOMETIMES : Throttling.NEVER;
LeaveTemporary = LoadLeaveTemorary();
FailOnTestFixtureOneTimeSetUpError = SystemProperties.GetPropertyAsBoolean("tests:failontestfixtureonetimesetuperror", true);
}
/// <summary>
/// True if and only if tests are run in verbose mode. If this flag is false
/// tests are not expected to print any messages.
/// </summary>
public bool Verbose { get; }
/// <summary>
/// TODO: javadoc? </summary>
public bool UseInfoStream { get; }
/// <summary>
/// A random multiplier which you should use when writing random tests:
/// multiply it by the number of iterations to scale your tests (for nightly builds).
/// </summary>
public int RandomMultiplier { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the codec to run tests with. </summary>
public string TestCodec { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the postingsFormat to run tests with. </summary>
public string TestPostingsFormat { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the docValuesFormat to run tests with </summary>
public string TestDocValuesFormat { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the directory to run tests with </summary>
public string TestDirectory { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// The line file used by LineFileDocs </summary>
public string TestLineDocsFile { get; set; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="NightlyAttribute"/> tests should run. </summary>
public bool TestNightly { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="WeeklyAttribute"/> tests should run. </summary>
public bool TestWeekly { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="AwaitsFixAttribute"/> tests should run. </summary>
public bool TestAwaitsFix { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="SlowAttribute"/> tests should run. </summary>
public bool TestSlow { get; } // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Throttling, see <see cref="MockDirectoryWrapper.Throttling"/>. </summary>
public Throttling TestThrottling { get; }
/// <summary>
/// Leave temporary files on disk, even on successful runs. </summary>
public bool LeaveTemporary { get; }
private static bool LoadLeaveTemorary()
{
bool defaultValue = false;
// LUCENENET specific - reformatted with :
foreach (string property in new string[] {
"tests:leaveTemporary" /* ANT tasks's (junit4) flag. */,
"tests:leavetemporary" /* lowercase */,
"tests:leavetmpdir" /* default */,
"solr:test:leavetmpdir" /* Solr's legacy */
})
{
defaultValue |= SystemProperties.GetPropertyAsBoolean(property, false);
}
return defaultValue;
}
/// <summary>
/// Fail when <see cref="OneTimeSetUp()"/> throws an exception for a given test fixture (usually a class).
/// By default, NUnit swallows exceptions when they happen here. We explicitly report these errors
/// to standard error, but enabling this feature will also cause all tests in the fixture and nested
/// tests to fail. Defaults to <c>false</c>.
/// <para/>
/// LUCENENET specific.
/// </summary>
public bool FailOnTestFixtureOneTimeSetUpError { get; }
}
/// <summary>
/// True if and only if tests are run in verbose mode. If this flag is false
/// tests are not expected to print any messages.
/// </summary>
public static bool Verbose => TestProperties.Verbose;
/// <summary>
/// TODO: javadoc? </summary>
public static bool UseInfoStream => TestProperties.UseInfoStream;
/// <summary>
/// A random multiplier which you should use when writing random tests:
/// multiply it by the number of iterations to scale your tests (for nightly builds).
/// </summary>
public static int RandomMultiplier => TestProperties.RandomMultiplier; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// TODO: javadoc? </summary>
public const string DEFAULT_LINE_DOCS_FILE = "europarl.lines.txt.gz";
/// <summary>
/// TODO: javadoc? </summary>
public const string JENKINS_LARGE_LINE_DOCS_FILE = "enwiki.random.lines.txt";
/// <summary>
/// Gets the codec to run tests with. </summary>
public static string TestCodec => TestProperties.TestCodec; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the postingsFormat to run tests with. </summary>
public static string TestPostingsFormat => TestProperties.TestPostingsFormat; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the docValuesFormat to run tests with </summary>
public static string TestDocValuesFormat => TestProperties.TestDocValuesFormat; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Gets the directory to run tests with </summary>
public static string TestDirectory => TestProperties.TestDirectory; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// The line file used by <see cref="LineFileDocs"/> </summary>
public static string TestLineDocsFile // LUCENENET specific - changed from field to property, and renamed
{
get => TestProperties.TestLineDocsFile;
internal set => TestProperties.TestLineDocsFile = value;
}
/// <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
/// <summary>
/// Whether or not <see cref="WeeklyAttribute"/> tests should run. </summary>
public static bool TestWeekly => TestProperties.TestWeekly; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="AwaitsFixAttribute"/> tests should run. </summary>
public static bool TestAwaitsFix => TestProperties.TestAwaitsFix; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Whether or not <see cref="SlowAttribute"/> tests should run. </summary>
public static bool TestSlow => TestProperties.TestSlow; // LUCENENET specific - changed from field to property, and renamed
/// <summary>
/// Throttling, see <see cref="MockDirectoryWrapper.Throttling"/>. </summary>
internal static Throttling TestThrottling => TestProperties.TestThrottling; // LUCENENET specific - made internal, because not fully implemented
/// <summary>
/// Leave temporary files on disk, even on successful runs. </summary>
public static bool LeaveTemporary => TestProperties.LeaveTemporary;
/// <summary>
/// Fail when <see cref="OneTimeSetUp()"/> throws an exception for a given test fixture (usually a class).
/// By default, NUnit swallows exceptions when they happen here. We explicitly report these errors
/// to standard error, but enabling this feature will also cause all tests in the fixture and nested
/// tests to fail. Defaults to <c>false</c>.
/// <para/>
/// LUCENENET specific.
/// </summary>
public static bool FailOnTestFixtureOneTimeSetUpError => TestProperties.FailOnTestFixtureOneTimeSetUpError;
// LUCENENET: Not Implemented
/////// <summary>
/////// These property keys will be ignored in verification of altered properties. </summary>
/////// <seealso> cref= SystemPropertiesInvariantRule </seealso>
/////// <seealso> cref= #ruleChain </seealso>
/////// <seealso> cref= #classRules </seealso>
////private static readonly string[] IGNORED_INVARIANT_PROPERTIES = { "user.timezone", "java.rmi.server.randomIDs" };
/// <summary>
/// Filesystem-based <see cref="Directory"/> implementations. </summary>
private static readonly IList<string> FS_DIRECTORIES = new string[] {
"SimpleFSDirectory",
"NIOFSDirectory",
"MMapDirectory"
};
/// <summary>
/// All <see cref="Directory"/> implementations. </summary>
private static readonly IList<string> CORE_DIRECTORIES = LoadCoreDirectories();
private static IList<string> LoadCoreDirectories()
{
return new JCG.List<string>(FS_DIRECTORIES)
{
"RAMDirectory"
};
}
protected static ICollection<string> DoesntSupportOffsets { get; } = new JCG.HashSet<string>
{
"Lucene3x",
"MockFixedIntBlock",
"MockVariableIntBlock",
"MockSep",
"MockRandom"
};
// -----------------------------------------------------------------
// Fields initialized in class or instance rules.
// -----------------------------------------------------------------
/// <summary>
/// When <c>true</c>, Codecs for old Lucene version will support writing
/// indexes in that format. Defaults to <c>false</c>, can be disabled by
/// specific tests on demand.
/// <para/>
/// @lucene.internal
/// </summary>
public static bool OldFormatImpersonationIsActive { get; set; } = false; // LUCENENET specific - made into a property, since this is intended for end users to set
// -----------------------------------------------------------------
// Class level (suite) rules.
// -----------------------------------------------------------------
///// <summary>
///// Stores the currently class under test.
///// </summary>
//private static TestRuleStoreClassName ClassNameRule;
/// <summary>
/// Class environment setup rule.
/// </summary>
internal static TestRuleSetupAndRestoreClassEnv ClassEnvRule { get; } = new TestRuleSetupAndRestoreClassEnv();
// LUCENENET TODO: Implement these rules
/// <summary>
/// Suite failure marker (any error in the test or suite scope).
/// </summary>
public static /*TestRuleMarkFailure*/ bool SuiteFailureMarker = true; // Means: was successful
///// <summary>
///// Ignore tests after hitting a designated number of initial failures. This
///// is truly a "static" global singleton since it needs to span the lifetime of all
///// test classes running inside this AppDomain (it cannot be part of a class rule).
/////
///// <para/>This poses some problems for the test framework's tests because these sometimes
///// trigger intentional failures which add up to the global count. This field contains
///// a (possibly) changing reference to <see cref="TestRuleIgnoreAfterMaxFailures"/> and we
///// dispatch to its current value from the <see cref="#classRules"/> chain using <see cref="TestRuleDelegate"/>.
///// </summary>
////private static AtomicReference<TestRuleIgnoreAfterMaxFailures> IgnoreAfterMaxFailuresDelegate = LoadMaxFailuresDelegate();
//////private static TestRule IgnoreAfterMaxFailures = LoadIgnoreAfterMaxFailures();
////private static AtomicReference<TestRuleIgnoreAfterMaxFailures> LoadMaxFailuresDelegate()
////{
//// int maxFailures = SystemProperties.GetPropertyAsInt32(SYSPROP_MAXFAILURES, int.MaxValue);
//// bool failFast = SystemProperties.GetPropertyAsBoolean(SYSPROP_FAILFAST, false);
//// if (failFast)
//// {
//// if (maxFailures == int.MaxValue)
//// {
//// maxFailures = 1;
//// }
//// else
//// {
//// Console.Out.Write(nameof(LuceneTestCase) + " WARNING: Property '" + SYSPROP_MAXFAILURES + "'=" + maxFailures + ", 'failfast' is" + " ignored.");
//// }
//// }
//// return new AtomicReference<TestRuleIgnoreAfterMaxFailures>(new TestRuleIgnoreAfterMaxFailures(maxFailures));
////}
////private static TestRule LoadIgnoreAfterMaxFailures()
////{
//// return TestRuleDelegate.Of(IgnoreAfterMaxFailuresDelegate);
////}
/////// <summary>
/////// Temporarily substitute the global <seealso cref="TestRuleIgnoreAfterMaxFailures"/>. See
/////// <seealso cref="#ignoreAfterMaxFailuresDelegate"/> for some explanation why this method
/////// is needed.
/////// </summary>
/////*public static TestRuleIgnoreAfterMaxFailures ReplaceMaxFailureRule(TestRuleIgnoreAfterMaxFailures newValue)
////{
//// return IgnoreAfterMaxFailuresDelegate.GetAndSet(newValue);
////}*/
/////// <summary>
/////// Max 10mb of static data stored in a test suite class after the suite is complete.
/////// Prevents static data structures leaking and causing OOMs in subsequent tests.
/////// </summary>
//////private static readonly long STATIC_LEAK_THRESHOLD = 10 * 1024 * 1024;
/////// <summary>
/////// By-name list of ignored types like loggers etc. </summary>
//////private static ISet<string> STATIC_LEAK_IGNORED_TYPES = new JCG.HashSet<string>(new string[] { "org.slf4j.Logger", "org.apache.solr.SolrLogFormatter", nameof(EnumSet) });
/////// <summary>
/////// this controls how suite-level rules are nested. It is important that _all_ rules declared
/////// in <seealso cref="LuceneTestCase"/> are executed in proper order if they depend on each
/////// other.
/////// </summary>
////public static TestRule classRules = RuleChain
//// .outerRule(new TestRuleIgnoreTestSuites())
//// .around(IgnoreAfterMaxFailures)
//// .around(SuiteFailureMarker = new TestRuleMarkFailure())
//// .around(new TestRuleAssertionsRequired())
//// .around(new TemporaryFilesCleanupRule())
//// .around(new StaticFieldsInvariantRule(STATIC_LEAK_THRESHOLD, true)
//// {
//// @Override
//// protected bool accept(System.Reflection.FieldInfo field)
//// {
//// if (STATIC_LEAK_IGNORED_TYPES.contains(field.Type.Name))
//// {
//// return false;
//// }
//// if (field.DeclaringClass == typeof(LuceneTestCase))
//// {
//// return false;
//// }
//// return base.accept(field);
//// }})
//// .around(new NoClassHooksShadowingRule())
//// .around(new NoInstanceHooksOverridesRule()
//// {
//// @Override
//// protected bool verify(Method key)
//// {
//// string name = key.Name;
//// return !(name.Equals("SetUp", StringComparison.Ordinal) || name.Equals("TearDown", StringComparison.Ordinal));
//// }})
//// .around(new SystemPropertiesInvariantRule(IGNORED_INVARIANT_PROPERTIES))
//// .around(ClassNameRule = new TestRuleStoreClassName())
//// .around(ClassEnvRule = new TestRuleSetupAndRestoreClassEnv());
////*/
// Don't count known classes that consume memory once.
// Don't count references from ourselves, we're top-level.
// -----------------------------------------------------------------
// Test level rules.
// -----------------------------------------------------------------
/////// <summary>
/////// Enforces <seealso cref="#setUp()"/> and <seealso cref="#tearDown()"/> calls are chained. </summary>
/////*private TestRuleSetupTeardownChained parentChainCallRule = new TestRuleSetupTeardownChained();
/////// <summary>
/////// Save test thread and name. </summary>
////private TestRuleThreadAndTestName threadAndTestNameRule = new TestRuleThreadAndTestName();
/////// <summary>
/////// Taint suite result with individual test failures. </summary>
////private TestRuleMarkFailure testFailureMarker = new TestRuleMarkFailure(SuiteFailureMarker);*/
/////// <summary>
/////// this controls how individual test rules are nested. It is important that
/////// _all_ rules declared in <seealso cref="LuceneTestCase"/> are executed in proper order
/////// if they depend on each other.
/////// </summary>
////public TestRule ruleChain = RuleChain
//// .outerRule(TestFailureMarker)
//// .around(IgnoreAfterMaxFailures)
//// .around(ThreadAndTestNameRule)
//// .around(new SystemPropertiesInvariantRule(IGNORED_INVARIANT_PROPERTIES))
//// .around(new TestRuleSetupAndRestoreInstanceEnv()).
//// around(new TestRuleFieldCacheSanity()).
//// around(ParentChainCallRule);
////*/
// -----------------------------------------------------------------
// Suite and test case setup/ cleanup.
// -----------------------------------------------------------------
/// <summary>
/// For subclasses to override. Overrides must call <c>base.SetUp()</c>.
/// </summary>
[Before]
public virtual void SetUp()
{
// LUCENENET TODO: Not sure how to convert these
//ParentChainCallRule.SetupCalled = true;
}
/// <summary>
/// For subclasses to override. Overrides must call <c>base.TearDown()</c>.
/// </summary>
[After]
public virtual void TearDown()
{
/* LUCENENET TODO: Not sure how to convert these
ParentChainCallRule.TeardownCalled = true;
*/
TestResult result = TestExecutionContext.CurrentContext.CurrentResult;
if (result.ResultState == ResultState.Failure || result.ResultState == ResultState.Error)
{
string message =
$$"""
{{result.Message}}
(Test: {{result.FullName}})
To reproduce this test result:
Option 1:
Apply the following assembly-level attributes:
[assembly: Lucene.Net.Util.RandomSeed("{{RandomizedContext.CurrentContext.RandomSeedAsHex}}")]
[assembly: NUnit.Framework.SetCulture("{{Thread.CurrentThread.CurrentCulture.Name}}")]
Option 2:
Use the following .runsettings file:
<RunSettings>
<TestRunParameters>
<Parameter name="tests:seed" value="{{RandomizedContext.CurrentContext.RandomSeedAsHex}}" />
<Parameter name="tests:culture" value="{{Thread.CurrentThread.CurrentCulture.Name}}" />
</TestRunParameters>
</RunSettings>
Option 3:
Create the following lucene.testsettings.json file somewhere between the test assembly and the root of your drive:
{
"tests": {
"seed": "{{RandomizedContext.CurrentContext.RandomSeedAsHex}}",
"culture": "{{Thread.CurrentThread.CurrentCulture.Name}}"
}
}
Fixture Test Values
=================
Random Seed: {{RandomizedContext.CurrentContext.RandomSeedAsHex}}
Culture: {{ClassEnvRule.locale.Name}}
Time Zone: {{ClassEnvRule.timeZone.DisplayName}}
Default Codec: {{ClassEnvRule.codec.Name}} ({{ClassEnvRule.codec.GetType().Name}})
Default Similarity: {{ClassEnvRule.similarity}}
System Properties
=================
Nightly: {{TestNightly}}
Weekly: {{TestWeekly}}
Slow: {{TestSlow}}
Awaits Fix: {{TestAwaitsFix}}
Directory: {{TestDirectory}}
Verbose: {{Verbose}}
Random Multiplier: {{RandomMultiplier}}
""";
result.SetResult(result.ResultState, message, result.StackTrace);
}
}
/// <summary>
/// Sets up dependency injection of codec factories for running the test class,
/// and also picks random defaults for culture, time zone, similarity, and default codec.
/// <para/>
/// If you override this method, be sure to call <c>base.OneTimeSetUp()</c> BEFORE setting
/// up your test fixture.
/// </summary>
// LUCENENET specific method for setting up dependency injection of test classes.
[OneTimeSetUp]
public virtual void OneTimeSetUp()
{
try
{
ClassEnvRule.Before();
}
catch (Exception ex)
{
// This is a bug in the test framework that should be fixed and/or reported if it occurs.
if (FailOnTestFixtureOneTimeSetUpError)
{
// LUCENENET: Patch NUnit so it will report all of the tests in the class as a failure if we got an exception.
TestExecutionContext.CurrentContext.CurrentTest.MakeAllInvalid(ex, $"An exception occurred during OneTimeSetUp:\n{ex}");
}
else
{
NUnit.Framework.TestContext.Error.WriteLine($"[ERROR] An exception occurred during OneTimeSetUp:\n{ex}");
}