Repository navigation
Expand file tree
/
Copy pathCiMatrixScriptTests.cs
More file actions
995 lines (917 loc) · 47.4 KB
/
Copy pathCiMatrixScriptTests.cs
File metadata and controls
995 lines (917 loc) · 47.4 KB
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
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT
#if NET10_0_OR_GREATER
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Opc.Ua.Tools.Tests
{
/// <summary>
/// Contract tests for .github/scripts/get-ci-matrix.ps1, which decides what
/// every pull request and every manual full-scope run actually executes. A
/// silent regression there would not fail any build: it would quietly stop
/// running part of the suite and still report green, so the properties that
/// make the matrix trustworthy are asserted here instead.
/// </summary>
[TestFixture]
[NonParallelizable]
public sealed class CiMatrixScriptTests
{
/// <summary>
/// GitHub refuses to start a run whose matrices expand past 256 jobs.
/// The script sizes its batches to fit; this proves both scopes do.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task ScopeFitsTheGitHubMatrixLimitAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
Assert.That(matrix.Tests, Is.Not.Empty);
Assert.That(matrix.Builds, Is.Not.Empty);
Assert.That(matrix.Tests.Select(entry => entry.Id), Is.Unique);
Assert.That(matrix.Tests.Select(entry => entry.Name), Is.Unique);
Assert.That(
matrix.Tests.Count + matrix.Builds.Count,
Is.LessThanOrEqualTo(256),
"The expanded matrix must fit GitHub's per-run job ceiling.");
}
/// <summary>
/// The batch target is computed from the whole profile table so that
/// turning macOS off does not reshuffle which projects run together on
/// the remaining runners, which would make two runs incomparable.
/// </summary>
[Test]
public async Task ExcludingMacOsKeepsTheRemainingBatchesIdenticalAsync()
{
MatrixResult withMac = await RunMatrixAsync("pr").ConfigureAwait(false);
MatrixResult withoutMac = await RunMatrixAsync("pr", excludeMacOs: true).ConfigureAwait(false);
Assert.That(withoutMac.BatchTargetMinutes, Is.EqualTo(withMac.BatchTargetMinutes));
Assert.That(
withoutMac.Tests.Any(entry => entry.Os == "macos"),
Is.False,
"-ExcludeMacOS must drop every macOS entry.");
Dictionary<string, string> expected = withMac.Tests
.Where(entry => entry.Os != "macos")
.ToDictionary(entry => entry.Id, entry => entry.Projects);
Dictionary<string, string> actual = withoutMac.Tests
.ToDictionary(entry => entry.Id, entry => entry.Projects);
Assert.That(actual, Is.EqualTo(expected));
}
/// <summary>
/// Every test project on disk has to be claimed by the matrix. The
/// exclusions are the four projects other jobs own; anything else that
/// stopped being scheduled would silently stop being tested.
/// </summary>
[Test]
public async Task EveryTestProjectIsCoveredOrExplicitlyExcludedAsync()
{
MatrixResult matrix = await RunMatrixAsync("full").ConfigureAwait(false);
HashSet<string> scheduled = matrix.Tests
.SelectMany(entry => entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries))
.ToHashSet(StringComparer.Ordinal);
string root = FindRepositoryRoot();
string[] excluded =
[
"Opc.Ua.Aot.Tests.csproj",
"Opc.Ua.Stress.Tests.csproj",
"Opc.Ua.OneFuzz.Validator.Tests.csproj"
];
List<string> missing = [];
var options = new EnumerationOptions
{
RecurseSubdirectories = true,
IgnoreInaccessible = true
};
foreach (string path in Directory.EnumerateFiles(root, "*.Tests.csproj", options))
{
string relative = Path.GetRelativePath(root, path).Replace('\\', '/');
if (relative.Contains("/bin/", StringComparison.Ordinal) ||
relative.Contains("/obj/", StringComparison.Ordinal))
{
continue;
}
if (excluded.Contains(Path.GetFileName(path), StringComparer.Ordinal))
{
continue;
}
if (!scheduled.Contains(relative))
{
missing.Add(relative);
}
}
Assert.That(missing, Is.Empty, "These test projects are on disk but nothing schedules them.");
}
/// <summary>
/// Packing by duration and filter sharding must never drop a project:
/// each profile schedules every project in its tier, with repeated
/// projects limited to their declared, disjoint shards.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task EveryProfileRunsEachOfItsProjectsExactlyOnceAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
HashSet<string> mainline = matrix.Tests
.Where(entry => entry.Tier == "mainline")
.SelectMany(entry => entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries))
.ToHashSet(StringComparer.Ordinal);
foreach (IGrouping<string, MatrixEntry> profile in matrix.Tests.GroupBy(entry => entry.Profile))
{
string[] projects = profile
.SelectMany(entry => entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries))
.ToArray();
if (profile.First().Tier is "mainline" or "long-running")
{
Assert.That(
projects.Distinct(StringComparer.Ordinal),
Is.EquivalentTo(mainline),
$"Profile '{profile.Key}' does not cover the mainline project set.");
}
foreach (IGrouping<string, MatrixEntry> project in profile
.SelectMany(entry => entry.Projects
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.Select(path => (Path: path, Entry: entry)))
.GroupBy(item => item.Path, item => item.Entry, StringComparer.Ordinal))
{
Assert.That(
project.Select(entry => entry.Shard),
Is.Unique,
$"Profile '{profile.Key}' schedules a shard of '{project.Key}' more than once.");
}
}
}
/// <summary>
/// Batches are packed up to the target from the duration table. Only a
/// project that is heavier than the target on its own may exceed it,
/// and then it has to run alone rather than drag others past it.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task BatchesStayWithinTheTargetUnlessOneProjectExceedsItAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
Assert.That(matrix.BatchTargetMinutes, Is.Positive);
string[] overweight = matrix.Tests
.Where(entry => entry.PackedMinutes > matrix.BatchTargetMinutes &&
entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries).Length > 1)
.Select(entry => $"{entry.Id}: {entry.PackedMinutes}min")
.ToArray();
Assert.That(overweight, Is.Empty);
Assert.That(matrix.Tests.All(entry => entry.PackedMinutes > 0), Is.True);
}
/// <summary>
/// The point of packing by duration is to stop paying the per-batch
/// cold build for every second project. Guard against a regression to
/// one or two projects per job, which nearly doubles the pull-request
/// runner minutes without testing anything more.
/// </summary>
[Test]
public async Task PullRequestBatchesAmortizeTheirFixedCostAsync()
{
MatrixResult matrix = await RunMatrixAsync("pr").ConfigureAwait(false);
string[] isolatedProjects =
[
"Opc.Ua.Server.Tests",
"Opc.Ua.Types.Tests",
"Opc.Ua.WotCon.Samples.Tests",
"Opc.Ua.WotCon.Tests"
];
foreach (IGrouping<string, MatrixEntry> profile in matrix.Tests.GroupBy(entry => entry.Profile))
{
MatrixEntry[] packed = profile
.Where(entry => entry.Shard == "all" &&
!isolatedProjects.Any(project => entry.Projects.Contains(project, StringComparison.Ordinal)))
.ToArray();
int projects = packed.Sum(entry =>
entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries).Length);
Assert.That(
packed,
Has.Length.LessThanOrEqualTo(projects / 3),
$"Profile '{profile.Key}' spreads {projects} packable projects over {packed.Length} jobs.");
}
}
/// <summary>
/// A weight for a project that no longer exists is harmless to the
/// matrix but means the table is not being maintained; every weight has
/// to name a test project that is on disk.
/// </summary>
[Test]
public async Task DurationTableNamesOnlyExistingProjectsAsync()
{
string root = FindRepositoryRoot();
string table = await File.ReadAllTextAsync(Path.Combine(root, ".github", "ci-test-durations.json"))
.ConfigureAwait(false);
using JsonDocument document = JsonDocument.Parse(table);
var options = new EnumerationOptions
{
RecurseSubdirectories = true,
IgnoreInaccessible = true
};
HashSet<string> onDisk = Directory.EnumerateFiles(root, "*.Tests.csproj", options)
.Select(Path.GetFileNameWithoutExtension)
.OfType<string>()
.ToHashSet(StringComparer.Ordinal);
Assert.That(document.RootElement.GetProperty("defaultMinutes").GetInt32(), Is.Positive);
string[] stale = document.RootElement.GetProperty("projects").EnumerateObject()
.Where(project => !onDisk.Contains(project.Name))
.Select(project => project.Name)
.ToArray();
Assert.That(stale, Is.Empty, "Remove these from .github/ci-test-durations.json.");
}
/// <summary>
/// The fuzz projects live under fuzzing/, not tests/. An earlier
/// discovery step only swept tests/ and therefore never ran them on
/// GitHub-hosted runners; this pins the fix.
/// </summary>
[Test]
public async Task FuzzProjectsAreScheduledAsync()
{
MatrixResult matrix = await RunMatrixAsync("pr").ConfigureAwait(false);
string[] fuzzProjects = matrix.Tests
.SelectMany(entry => entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries))
.Where(project => project.StartsWith("fuzzing/", StringComparison.Ordinal))
.Distinct(StringComparer.Ordinal)
.ToArray();
Assert.That(fuzzProjects, Is.Not.Empty);
}
/// <summary>
/// The tiers that lift the category filter are the only way the
/// LongRunning and durable-subscription tests ever run. They belong to
/// the full scope and must stay out of the pull-request scope.
/// </summary>
[Test]
public async Task UnfilteredTiersRunOnlyInTheFullScopeAsync()
{
MatrixResult pr = await RunMatrixAsync("pr").ConfigureAwait(false);
MatrixResult full = await RunMatrixAsync("full").ConfigureAwait(false);
Assert.That(pr.Tests.All(entry => entry.Tier == "mainline"), Is.True);
Assert.That(full.Tests.Any(entry => entry.Tier == "long-running"), Is.True);
Assert.That(full.Tests.Any(entry => entry.Tier == "durable"), Is.True);
Assert.That(
full.Tests.Where(entry => entry.Tier != "mainline").All(entry =>
!entry.Filter.Contains("TestCategory!=LongRunning", StringComparison.Ordinal) &&
!entry.Filter.Contains("TestCategory!=Stress", StringComparison.Ordinal)),
Is.True,
"A tier that exists to lift category exclusions must not restore them.");
}
/// <summary>
/// coverlet.collector ships build assets for net8.0 and newer only, so
/// attaching it to a .NET Framework test host produces a warning and no
/// report. Requesting coverage there would make the merged report look
/// complete while silently missing those legs.
/// </summary>
[Test]
public async Task CoverageIsNeverRequestedOnANetFrameworkHostAsync()
{
MatrixResult full = await RunMatrixAsync("full").ConfigureAwait(false);
MatrixEntry[] offenders = full.Tests
.Where(entry => entry.Framework.StartsWith("net4", StringComparison.Ordinal) && entry.Coverage)
.ToArray();
Assert.That(offenders.Select(entry => entry.Id), Is.Empty);
}
/// <summary>
/// The pull-request scope has to be the union of what the two CI systems
/// covered separately, otherwise migrating to Actions loses a leg.
/// </summary>
[Test]
public async Task PullRequestScopeCoversBothFormerCiSystemsAsync()
{
MatrixResult pr = await RunMatrixAsync("pr").ConfigureAwait(false);
string[] profiles = pr.Tests.Select(entry => entry.Profile).Distinct(StringComparer.Ordinal).ToArray();
Assert.That(profiles, Does.Contain("windows-net48"));
Assert.That(profiles, Does.Contain("windows-net11.0"));
Assert.That(profiles, Does.Contain("linux-net11.0"));
Assert.That(profiles, Does.Contain("macos-net11.0"));
}
/// <summary>
/// The private-fuzz-corpus job narrows the same profile table to one
/// project instead of repeating the profile list, so the narrowing has
/// to keep the profiles and drop everything else.
/// </summary>
[Test]
public async Task OnlyProjectNarrowsTheMatrixToThatProjectAsync()
{
const string project = "fuzzing/Opc.Ua.Encoders.Fuzz.Tests/Opc.Ua.Encoders.Fuzz.Tests.csproj";
MatrixResult matrix = await RunMatrixAsync("full", onlyProject: project).ConfigureAwait(false);
Assert.That(matrix.Tests, Is.Not.Empty);
Assert.That(
matrix.Tests.All(entry => entry.Projects == project),
Is.True,
"Narrowing must not leave any other project scheduled.");
Assert.That(
matrix.Tests.All(entry => entry.Tier == "mainline"),
Is.True,
"The named tiers cover named projects and must drop out when narrowing.");
Assert.That(
matrix.Tests.Select(entry => entry.Profile).Distinct(StringComparer.Ordinal).Count(),
Is.EqualTo(matrix.Tests.Count),
"One project produces exactly one batch per profile.");
}
/// <summary>
/// A typo in the narrowing argument must not produce an empty matrix
/// that reports success without replaying anything.
/// </summary>
[Test]
public async Task OnlyProjectFailsWhenNothingMatchesAsync()
{
ScriptResult result = await RunScriptAsync("full", onlyProject: "does/not/Exist.Tests.csproj")
.ConfigureAwait(false);
Assert.That(result.ExitCode, Is.Not.Zero);
Assert.That(result.Output, Does.Contain("would report success without testing anything"));
}
/// <summary>
/// A batch job is cancelled by GitHub the moment it passes
/// timeout-minutes, and a cancelled job produces neither the executor's
/// per-project annotation nor its results. The job budget therefore has
/// to be an upper bound on everything the executor may spend: fixed
/// setup cost plus one per-project ceiling for each project in the
/// batch, never a clamped value.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task JobTimeoutIncludesEveryTestBudgetAndBuildOverheadAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
string[] underBudget = matrix.Tests
.Where(entry =>
entry.TimeoutMinutes <
20 + entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries).Length *
entry.PerProjectTimeout)
.Select(entry => $"{entry.Id} allows {entry.TimeoutMinutes}min for " +
$"20 + {entry.Projects.Split(';', StringSplitOptions.RemoveEmptyEntries).Length} x " +
$"{entry.PerProjectTimeout}min")
.ToArray();
Assert.That(underBudget, Is.Empty);
Assert.That(matrix.Tests.All(entry => entry.PerProjectTimeout > 0), Is.True);
}
/// <summary>
/// Every workload, including formerly extended sample and integration
/// projects, uses the same 45-minute test-execution ceiling.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task EveryProjectUsesTheStandardFortyFiveMinuteCeilingAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
string[] exceptions = matrix.Tests
.Where(entry => entry.PerProjectTimeout != 45)
.Select(entry => $"{entry.Id}: {entry.PerProjectTimeout}min")
.ToArray();
Assert.That(exceptions, Is.Empty);
}
/// <summary>
/// The long sample scenarios run as separate jobs with the standard
/// budget, and the filters cover distinct parts of the suite.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task SampleScenariosAreSplitIntoBoundedWorkloadsAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
MatrixEntry[] samples = matrix.Tests.Where(entry =>
entry.Projects.Contains("Opc.Ua.WotCon.Samples.Tests", StringComparison.Ordinal)).ToArray();
Assert.That(samples, Is.Not.Empty);
foreach (IGrouping<string, MatrixEntry> profile in samples.GroupBy(entry => entry.Profile))
{
string[] expectedShards = profile.First().Framework == "net48"
? ["all"]
: ["sample-core", "sample-generation", "sample-native-comparisons"];
Assert.That(profile.Select(entry => entry.Shard), Is.EquivalentTo(expectedShards));
if (profile.First().Framework != "net48")
{
MatrixEntry generation = profile.Single(entry => entry.Shard == "sample-generation");
MatrixEntry nativeComparisons = profile.Single(entry => entry.Shard == "sample-native-comparisons");
MatrixEntry core = profile.Single(entry => entry.Shard == "sample-core");
Assert.That(
generation.Filter,
Does.Contain("RealSamplesAggregateSubscribeAndReplaceGenerationAsync"));
Assert.That(nativeComparisons.Filter, Does.Contain("WotPumpInstanceMatchesNativePumpSubsetAsync"));
Assert.That(
nativeComparisons.Filter,
Does.Contain("CompanionTypeDefinitionsMatchNativePumpServerAsync"));
Assert.That(core.Filter, Does.Contain("FullyQualifiedName!~"));
}
foreach (MatrixEntry sample in profile)
{
Assert.Multiple(() =>
{
Assert.That(sample.Projects, Does.Not.Contain(";"));
Assert.That(sample.PerProjectTimeout, Is.EqualTo(45));
Assert.That(sample.TimeoutMinutes, Is.EqualTo(65));
if (sample.Framework != "net48")
{
Assert.That(sample.Filter, Does.Contain("FullyQualifiedName"));
}
});
}
}
}
/// <summary>
/// Server shards select representative names once or exclude them
/// according to each profile's category filters.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task ServerFiltersPartitionEligibleTestsExactlyOnceAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
MatrixEntry[] server = matrix.Tests.Where(entry =>
entry.Projects.Contains("Opc.Ua.Server.Tests.csproj", StringComparison.Ordinal)).ToArray();
Assert.That(server, Is.Not.Empty);
string[] serverShards =
[
"server-node-lifecycle",
"server-node-management",
"server-history-subscriptions",
"server-sessions",
"server-configuration",
"server-runtime",
"server-transport",
"server-other"
];
foreach (IGrouping<string, MatrixEntry> profile in server.GroupBy(entry => entry.Profile))
{
string[] expectedShards = profile.First().Framework == "net48"
? serverShards
: profile.First().Os == "macos"
? [
"server-node-lifecycle",
"server-node-management",
"server-history-subscriptions",
"server-sessions-configuration-runtime",
"server-other"
]
: ["all"];
Assert.That(profile.Select(entry => entry.Shard), Is.EquivalentTo(expectedShards));
Assert.That(profile.All(entry => entry.PerProjectTimeout == 45), Is.True);
}
(string TestName, string ExpectedShard, string MacShard)[] testCases =
[
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.PreparedBatchDecisionAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.AddAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.NativeReadAsync(True,False)",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.ObjectReadAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.TestAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.RejectsPreparedBatchAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.nodemanagerlifecycletests.PreparedBatchAsync",
"server-node-management", "server-node-management"),
("Opc.Ua.Server.Tests.Hosting.HostedNodeManagerLifecycleTests.PreparedBatchAsync",
"server-node-management", "server-node-management"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTestsExtra.PreparedBatchAsync",
"server-node-management", "server-node-management"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.PreparedBatchAsync(\"AddAsync\")",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.NodeManager.NodeManagerLifecycleTests.addAsync",
"server-node-lifecycle", "server-node-lifecycle"),
("Opc.Ua.Server.Tests.Fluent.FluentNodeManagerBasePipelineTests.TestAsync",
"server-node-management", "server-node-management"),
("Opc.Ua.Server.Tests.Historian.HistorianDispatcherTests.TestAsync",
"server-history-subscriptions", "server-history-subscriptions"),
("Opc.Ua.Server.Tests.SubscriptionTests.TransferSubscriptionAsync",
"server-history-subscriptions", "server-history-subscriptions"),
("Opc.Ua.Server.Tests.Network.NetworkModelIntegrationTests." +
"LldpOptionalCapabilitiesArePublishedAndRemovedAsync",
"server-history-subscriptions", "server-history-subscriptions"),
("Opc.Ua.Server.Tests.Session.SessionTests.TestAsync",
"server-sessions", "server-sessions-configuration-runtime"),
("Opc.Ua.Server.Tests.Configuration.TrustListTests.TestAsync",
"server-configuration", "server-sessions-configuration-runtime"),
("Opc.Ua.Server.Tests.RuntimeNodeSet.RuntimeNodeSetTests.TestAsync",
"server-runtime", "server-sessions-configuration-runtime"),
("Opc.Ua.Server.Tests.ReverseConnectServerTests.TestAsync", "server-transport", "server-other"),
("Opc.Ua.Server.Tests.RequestTableTests.TestAsync", "server-other", "server-other")
];
string[][] categorySets =
[
[],
["Server", "NodeManagerLifecycle"],
["Integration", "Server", "NodeManagerLifecycle"],
["LongRunning"],
["Stress"],
["longrunning"],
["stress"],
["Server", "NodeManagerLifecycle", "LongRunning"],
["Server", "NodeManagerLifecycle", "Stress"],
["LongRunning", "Stress"]
];
foreach (IGrouping<string, MatrixEntry> profile in server.GroupBy(entry => entry.Profile))
{
foreach ((string testName, string expectedShard, string macShard) in testCases)
{
string shard = profile.First().Framework == "net48"
? expectedShard
: profile.First().Os != "macos"
? "all"
: macShard;
foreach (string[] categories in categorySets)
{
bool allowed = profile.First().Tier != "mainline" ||
(!categories.Contains("LongRunning", StringComparer.Ordinal) &&
!categories.Contains("Stress", StringComparer.Ordinal));
string[] matches = profile
.Where(entry => MatchesServerFilter(entry.Filter, testName, categories))
.Select(entry => entry.Shard)
.ToArray();
Assert.That(
matches,
Is.EqualTo(allowed ? new[] { shard } : Array.Empty<string>()),
$"Profile '{profile.Key}', test '{testName}', " +
$"categories '{string.Join(",", categories)}'.");
}
}
}
}
/// <summary>
/// Each integration project has a standard workload budget. The WoT
/// suite runs whole on Windows and Linux and in two namespace halves
/// on net48 and macOS.
/// </summary>
[TestCase("pr")]
[TestCase("full")]
public async Task IntegrationProjectsUseBoundedWorkloadsAsync(string scope)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
MatrixEntry[] integration = matrix.Tests.Where(entry =>
entry.Projects.Contains("Opc.Ua.Server.Tests", StringComparison.Ordinal) ||
entry.Projects.Contains("Opc.Ua.WotCon.Tests", StringComparison.Ordinal) ||
entry.Projects.Contains("Opc.Ua.Types.Tests", StringComparison.Ordinal)).ToArray();
Assert.That(integration, Is.Not.Empty);
foreach (MatrixEntry entry in integration)
{
Assert.Multiple(() =>
{
Assert.That(entry.Projects, Does.Not.Contain(";"));
Assert.That(entry.PerProjectTimeout, Is.EqualTo(45));
Assert.That(entry.TimeoutMinutes, Is.EqualTo(65));
Assert.That(entry.HangTimeout, Is.EqualTo(
entry.Tier == "mainline" ? "10m" : "30m"));
});
}
foreach (IGrouping<string, MatrixEntry> profile in integration
.Where(entry => entry.Projects.Contains("Opc.Ua.WotCon.Tests", StringComparison.Ordinal))
.GroupBy(entry => entry.Profile))
{
string[] expectedShards =
profile.First().Framework == "net48" || profile.First().Os == "macos"
? ["wot-materialization", "wot-other"]
: ["all"];
Assert.That(
profile.Select(entry => entry.Shard),
Is.EquivalentTo(expectedShards));
}
}
/// <summary>
/// Representative WoT cases are selected exactly once or excluded
/// according to each profile's category filters.
/// </summary>
[TestCase("pr", false, false)]
[TestCase("pr", false, true)]
[TestCase("pr", true, false)]
[TestCase("pr", true, true)]
[TestCase("full", false, false)]
[TestCase("full", false, true)]
[TestCase("full", true, false)]
[TestCase("full", true, true)]
public async Task WotFiltersPartitionEligibleTestsExactlyOnceAsync(
string scope,
bool materialization,
bool integration)
{
MatrixResult matrix = await RunMatrixAsync(scope).ConfigureAwait(false);
MatrixEntry[] wot = matrix.Tests.Where(entry =>
entry.Projects.Contains("Opc.Ua.WotCon.Tests.csproj", StringComparison.Ordinal)).ToArray();
Assert.That(wot.Any(entry => entry.Framework == "net48"), Is.True);
Assert.That(wot.Any(entry => entry.Framework != "net48"), Is.True);
string[] testNames = materialization
? [
"Opc.Ua.WotCon.Tests.Materialization.ExampleTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.Materialization.WotEventModesLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.Materialization.WotRegistryIdentityLiveTests.ExampleAsync"
]
: [
"Opc.Ua.WotCon.Tests.Registry.ExampleTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.materialization.ExampleTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.WotRegistryIdentityLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.WotRegistryIdentityLiveTests(False).ExampleAsync",
"Opc.Ua.WotCon.Tests.WotRegistryIdentityLiveTests(True).ExampleAsync",
"Opc.Ua.WotCon.Tests.WotRegistryIdentityLiveTestsExtra.ExampleAsync",
"Opc.Ua.WotCon.Tests.Registry.WotRegistryIdentityLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.wotregistryidentitylivetests.ExampleAsync",
"Opc.Ua.WotCon.Tests.WotLegacyNativeAdmissionLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.WotLegacyTypeBindingLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.WotLegacyMaterializationLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.Registry.WotLegacyTypeBindingLiveTests.ExampleAsync",
"Opc.Ua.WotCon.Tests.wotlegacytypebindinglivetests.ExampleAsync"
];
string[][] exclusionCategories =
[
[],
["LongRunning"],
["Stress"],
["longrunning"],
["stress"],
["LongRunning", "Stress"]
];
foreach (IGrouping<string, MatrixEntry> profile in wot.GroupBy(entry => entry.Profile))
{
foreach (string testName in testNames)
{
foreach (string[] exclusions in exclusionCategories)
{
string[] categories = integration ? [.. exclusions, "Integration"] : exclusions;
bool allowed = profile.First().Tier != "mainline" ||
(!exclusions.Contains("LongRunning", StringComparer.Ordinal) &&
!exclusions.Contains("Stress", StringComparer.Ordinal));
string[] matches = profile
.Where(entry => MatchesWotFilter(entry.Filter, testName, categories))
.Select(entry => entry.Shard)
.ToArray();
string expectedShard =
profile.First().Framework != "net48" && profile.First().Os != "macos"
? "all"
: materialization ? "wot-materialization" : "wot-other";
Assert.That(
matches,
Is.EqualTo(allowed ? new[] { expectedShard } : Array.Empty<string>()),
$"Profile '{profile.Key}', test '{testName}', " +
$"categories '{string.Join(",", categories)}'.");
}
}
}
}
/// <summary>
/// Each test invocation gets its full budget after the build completes;
/// build time is instead covered by the fixed overhead in the job
/// timeout.
/// </summary>
[Test]
public async Task ExecutorBudgetsTestExecutionSeparatelyFromBuildAsync()
{
string executor = Path.Combine(FindRepositoryRoot(), ".github", "scripts", "run-dotnet-tests.ps1");
string source = await File.ReadAllTextAsync(executor).ConfigureAwait(false);
string[] invocations = source
.Split('\n')
.Select(line => line.Trim())
.Where(line => line.Contains("= Invoke-Dotnet ", StringComparison.Ordinal))
.ToArray();
Assert.That(invocations, Has.Length.EqualTo(2), "The executor builds once and tests once per project.");
Assert.That(
invocations[0],
Does.Contain("$null 0"),
"The build is bounded by the job timeout rather than consuming the test budget.");
Assert.That(
invocations[1],
Does.Contain("$testBudget $PerProjectTimeoutMinutes"),
"The full project ceiling is applied to test execution.");
Assert.That(
source,
Does.Contain("$testBudget = [System.Diagnostics.Stopwatch]::StartNew()"),
"The test stopwatch starts after the build completes.");
Assert.That(
source,
Does.Contain("$buildBudget = [System.Diagnostics.Stopwatch]::StartNew()"),
"Build duration remains available for reporting.");
Assert.That(invocations[1], Does.Contain("$logPath $targetDir"));
Assert.That(source, Does.Contain("$startInfo = New-DotnetStartInfo $arguments $IsLinux"));
Assert.That(source, Does.Contain("$process.StartInfo = $startInfo"));
Assert.That(source, Does.Contain("$process.Kill($true)"));
}
/// <summary>
/// Evaluates the conjunctions emitted for WoT tests; unsupported terms
/// fail rather than silently weakening the partition assertions.
/// </summary>
private static bool MatchesWotFilter(string filter, string testName, string[] categories)
{
// The default NUnit adapter uses case-sensitive engine filters.
// VSTest filter values escape parentheses; the test names do not.
return filter.Split('&').Select(term => term.Replace("\\(", "(", StringComparison.Ordinal)
.Replace("\\)", ")", StringComparison.Ordinal)).All(term => term switch
{
"" => true,
_ when term.StartsWith("FullyQualifiedName!~", StringComparison.Ordinal) =>
!testName.Contains(term["FullyQualifiedName!~".Length..], StringComparison.Ordinal),
_ when term.StartsWith("FullyQualifiedName~", StringComparison.Ordinal) =>
testName.Contains(term["FullyQualifiedName~".Length..], StringComparison.Ordinal),
_ when term.StartsWith("TestCategory!=", StringComparison.Ordinal) =>
!categories.Contains(term["TestCategory!=".Length..], StringComparer.Ordinal),
_ when term.StartsWith("TestCategory=", StringComparison.Ordinal) =>
categories.Contains(term["TestCategory=".Length..], StringComparer.Ordinal),
_ => throw new InvalidOperationException($"Unsupported WoT filter term '{term}'.")
});
}
/// <summary>
/// Evaluates the disjoint name-filter expressions emitted for the
/// oversized server suite.
/// </summary>
private static bool MatchesServerFilter(string filter, string testName, string[] categories)
{
if (string.IsNullOrEmpty(filter))
{
return true;
}
return filter.Split('&').All(term =>
{
string expression = term.Trim('(', ')');
if (expression.Length == 0)
{
return true;
}
if (expression.StartsWith("TestCategory!=", StringComparison.Ordinal))
{
return !categories.Contains(expression["TestCategory!=".Length..], StringComparer.Ordinal);
}
if (expression.StartsWith("TestCategory=", StringComparison.Ordinal))
{
return categories.Contains(expression["TestCategory=".Length..], StringComparer.Ordinal);
}
string[] alternatives = expression.Split('|');
bool matches = alternatives.Any(alternative =>
{
const string includePrefix = "FullyQualifiedName~";
const string excludePrefix = "FullyQualifiedName!~";
bool excluded;
string needle;
if (alternative.StartsWith(excludePrefix, StringComparison.Ordinal))
{
excluded = true;
needle = alternative[excludePrefix.Length..];
}
else if (alternative.StartsWith(includePrefix, StringComparison.Ordinal))
{
excluded = false;
needle = alternative[includePrefix.Length..];
}
else
{
throw new InvalidOperationException($"Unsupported server filter term '{alternative}'.");
}
bool contains = testName.Contains(needle, StringComparison.Ordinal);
return excluded ? !contains : contains;
});
return matches;
});
}
private static async Task<MatrixResult> RunMatrixAsync(
string scope,
bool excludeMacOs = false,
string? onlyProject = null)
{
string outputPath = Path.Combine(Path.GetTempPath(), $"ci-matrix-{Guid.NewGuid():N}.txt");
try
{
ScriptResult result = await RunScriptAsync(scope, excludeMacOs, onlyProject, outputPath)
.ConfigureAwait(false);
Assert.That(result.ExitCode, Is.Zero, result.Output);
string[] lines = await File.ReadAllLinesAsync(outputPath).ConfigureAwait(false);
return new MatrixResult(
Deserialize<MatrixEntry>(lines, "tests="),
Deserialize<BuildEntry>(lines, "builds="),
int.Parse(Value(lines, "batch_target_minutes="), CultureInfo.InvariantCulture));
}
finally
{
File.Delete(outputPath);
}
}
private static List<T> Deserialize<T>(string[] lines, string prefix)
{
return JsonSerializer.Deserialize<List<T>>(Value(lines, prefix), s_json) ??
throw new InvalidOperationException($"'{prefix}' did not carry a JSON array.");
}
private static string Value(string[] lines, string prefix)
{
string? line = lines.FirstOrDefault(candidate => candidate.StartsWith(prefix, StringComparison.Ordinal));
Assert.That(line, Is.Not.Null, $"The script emitted no '{prefix}' line.");
return line![prefix.Length..].Trim();
}
private static async Task<ScriptResult> RunScriptAsync(
string scope,
bool excludeMacOs = false,
string? onlyProject = null,
string? githubOutputPath = null)
{
string root = FindRepositoryRoot();
using var process = new Process();
process.StartInfo.FileName = "pwsh";
process.StartInfo.WorkingDirectory = root;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
PowerShellScriptOutput.ConfigureDeterministicOutput(process.StartInfo);
process.StartInfo.ArgumentList.Add("-NoProfile");
process.StartInfo.ArgumentList.Add("-File");
process.StartInfo.ArgumentList.Add(Path.Combine(root, ".github", "scripts", "get-ci-matrix.ps1"));
process.StartInfo.ArgumentList.Add("-Scope");
process.StartInfo.ArgumentList.Add(scope);
process.StartInfo.ArgumentList.Add("-RepositoryRoot");
process.StartInfo.ArgumentList.Add(root);
if (excludeMacOs)
{
process.StartInfo.ArgumentList.Add("-ExcludeMacOS");
}
if (!string.IsNullOrEmpty(onlyProject))
{
process.StartInfo.ArgumentList.Add("-OnlyProject");
process.StartInfo.ArgumentList.Add(onlyProject);
}
// The matrices only reach GITHUB_OUTPUT, so pointing it at a
// temporary file exercises the same path a workflow run takes.
if (string.IsNullOrEmpty(githubOutputPath))
{
process.StartInfo.Environment.Remove("GITHUB_OUTPUT");
}
else
{
process.StartInfo.Environment["GITHUB_OUTPUT"] = githubOutputPath;
}
Assert.That(process.Start(), Is.True);
Task<string> standardOutput = process.StandardOutput.ReadToEndAsync();
Task<string> standardError = process.StandardError.ReadToEndAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2));
await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false);
string output = await standardOutput.ConfigureAwait(false);
string error = await standardError.ConfigureAwait(false);
return new ScriptResult(process.ExitCode, PowerShellScriptOutput.Normalize(output + error));
}
private static string FindRepositoryRoot()
{
string? configuredRoot = Environment.GetEnvironmentVariable("OPCUA_TEST_REPOSITORY_ROOT");
if (!string.IsNullOrWhiteSpace(configuredRoot))
{
if (!File.Exists(Path.Combine(configuredRoot, ".github", "scripts", "get-ci-matrix.ps1")))
{
throw new DirectoryNotFoundException("The configured root has no CI matrix script.");
}
return configuredRoot;
}
string? current = TestContext.CurrentContext.TestDirectory;
while (!string.IsNullOrWhiteSpace(current))
{
if (File.Exists(Path.Combine(current, ".github", "scripts", "get-ci-matrix.ps1")))
{
return current;
}
current = Directory.GetParent(current)?.FullName;
}
throw new InvalidOperationException("Could not find the repository root.");
}
private sealed record ScriptResult(int ExitCode, string Output);
private sealed record MatrixResult(
IReadOnlyList<MatrixEntry> Tests,
IReadOnlyList<BuildEntry> Builds,
int BatchTargetMinutes);
/// <summary>
/// One expanded test matrix entry. Deserialized by reflection, hence public.
/// </summary>
/// <param name="PerProjectTimeout">The per project timeout.</param>
/// <param name="TimeoutMinutes">The timeout minutes.</param>
/// <param name="PackedMinutes">The packed minutes.</param>
/// <param name="HangTimeout">The hang timeout.</param>
/// <param name="Id">The matrix entry identifier.</param>
/// <param name="Name">The display name of the matrix entry.</param>
/// <param name="Os">The operating system of the runner.</param>
/// <param name="Profile">The test profile of the entry.</param>
/// <param name="Tier">The test tier of the entry.</param>
/// <param name="Framework">The target framework of the entry.</param>
/// <param name="Filter">The test filter expression of the entry.</param>
/// <param name="Coverage">The coverage flag supplied by the caller.</param>
/// <param name="Projects">The test projects run by the entry.</param>
/// <param name="Shard">The workload shard name.</param>
public sealed record MatrixEntry(
string Id,
string Name,
string Os,
string Profile,
string Tier,
string Framework,
string Filter,
bool Coverage,
string Projects,
string Shard,
int PerProjectTimeout,
int TimeoutMinutes,
int PackedMinutes,
string HangTimeout);
/// <summary>
/// One expanded solution build matrix entry.
/// </summary>
public sealed record BuildEntry(string Id, string Os, string Solution, string CustomTestTarget);
private static readonly JsonSerializerOptions s_json = new()
{
PropertyNameCaseInsensitive = true
};
}
}
#endif