-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest-examples.ps1
More file actions
1001 lines (880 loc) · 33.6 KB
/
Copy pathtest-examples.ps1
File metadata and controls
1001 lines (880 loc) · 33.6 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
996
997
998
999
1000
<#
.SYNOPSIS
Tests SharpTS examples in interpreted, compiled DLL, and compiled EXE modes.
.DESCRIPTION
This script tests each example in the Examples directory using three execution modes:
1. Interpreted: dotnet run -- <file>.ts <args>
2. Compiled DLL: dotnet run -- --compile <file>.ts -o <out>.dll then dotnet <out>.dll <args>
3. Compiled EXE: dotnet run -- --compile <file>.ts -t exe -o <out>.exe then .\<out>.exe <args>
.PARAMETER Filter
Filter examples by name pattern (e.g., "file-*" or "system-info")
.PARAMETER Mode
Execution mode(s) to test: all, interpreted, dll, exe (default: all)
.PARAMETER OutputFormat
Output format: json, table, verbose (default: table)
.PARAMETER SkipCleanup
Skip cleanup of temporary files and directories
.EXAMPLE
.\test-examples.ps1
Run all tests with default settings
.EXAMPLE
.\test-examples.ps1 -Filter "system-info" -OutputFormat verbose
Test only system-info example with verbose output
.EXAMPLE
.\test-examples.ps1 -Mode interpreted -OutputFormat json
Test only interpreted mode and output JSON
#>
param(
[string]$Filter = "*",
[ValidateSet("all", "interpreted", "dll", "exe")]
[string]$Mode = "all",
[ValidateSet("json", "table", "verbose")]
[string]$OutputFormat = "table",
[switch]$SkipCleanup
)
$ErrorActionPreference = "Stop"
# ========== Configuration ==========
$Script:ProjectRoot = Split-Path -Parent $PSScriptRoot
$Script:ExamplesDir = $PSScriptRoot
$Script:TempRoot = Join-Path ([System.IO.Path]::GetTempPath()) "SharpTS-Tests-$([guid]::NewGuid().ToString('N').Substring(0, 8))"
$Script:ProcessTimeout = 30000 # 30 seconds
$Script:BuildTimeout = 120000 # 2 minutes for compilation
# ========== Test Case Definitions ==========
$Script:TestCases = @{
"file-hasher" = @{
File = "file-hasher.ts"
Tests = @(
@{
Name = "HashTextFile"
RequiresArgs = $true
Setup = {
$testFile = Join-Path $Script:TempRoot "test-hash.txt"
Set-Content -Path $testFile -Value "Hello, World!" -NoNewline
return @{ TestFile = $testFile }
}
Args = { param($ctx) @($ctx.TestFile) }
Assertions = @(
@{ Type = "Contains"; Value = "File Hasher Results" }
@{ Type = "Contains"; Value = "MD5" }
@{ Type = "Contains"; Value = "SHA1" }
@{ Type = "Contains"; Value = "SHA256" }
@{ Type = "Contains"; Value = "SHA512" }
)
},
@{
Name = "FileNotFound"
RequiresArgs = $true
Args = { @("C:\nonexistent\path\file.txt") }
Assertions = @(
@{ Type = "Contains"; Value = "Error: File not found" }
)
},
@{
Name = "NoArguments"
RequiresArgs = $false
Args = { @() }
Assertions = @(
@{ Type = "Contains"; Value = "Usage:" }
)
}
)
}
"file-organizer" = @{
File = "file-organizer.ts"
Tests = @(
@{
Name = "DryRunMode"
RequiresArgs = $true
Setup = {
$testDir = Join-Path $Script:TempRoot "organize-test"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
Set-Content -Path (Join-Path $testDir "document.txt") -Value "text content"
Set-Content -Path (Join-Path $testDir "photo.jpg") -Value "fake image"
Set-Content -Path (Join-Path $testDir "script.ts") -Value "console.log('test')"
return @{ TestDir = $testDir }
}
Args = { param($ctx) @($ctx.TestDir, "--dry-run") }
Assertions = @(
@{ Type = "Contains"; Value = "DRY RUN" }
@{ Type = "Contains"; Value = "document.txt" }
@{ Type = "Contains"; Value = "photo.jpg" }
)
},
@{
Name = "DirectoryNotFound"
RequiresArgs = $true
Args = { @("C:\nonexistent\directory\path") }
Assertions = @(
@{ Type = "Contains"; Value = "Error: Directory not found" }
)
},
@{
Name = "NoArguments"
RequiresArgs = $false
Args = { @() }
Assertions = @(
@{ Type = "Contains"; Value = "Usage:" }
)
}
)
}
"password-generator" = @{
File = "password-generator.ts"
Tests = @(
@{
Name = "GenerateWithAllChars"
RequiresArgs = $true
Args = { @("16", "--all") }
Assertions = @(
@{ Type = "Contains"; Value = "Password Generator" }
@{ Type = "Contains"; Value = "Generated Passwords:" }
@{ Type = "Contains"; Value = "Charset size: 88 characters" }
@{ Type = "Contains"; Value = "Password length: 16" }
@{ Type = "Contains"; Value = "Entropy:" }
)
},
@{
Name = "GenerateWithLowercaseOnly"
RequiresArgs = $true
Args = { @("12", "--lowercase") }
Assertions = @(
@{ Type = "Contains"; Value = "Generated Passwords:" }
@{ Type = "Contains"; Value = "Charset size: 26 characters" }
@{ Type = "Contains"; Value = "Password length: 12" }
)
},
@{
Name = "GenerateWithMultipleFlags"
RequiresArgs = $true
Args = { @("20", "-l", "-u", "-d") }
Assertions = @(
@{ Type = "Contains"; Value = "Generated Passwords:" }
@{ Type = "Contains"; Value = "Charset size: 62 characters" }
@{ Type = "Contains"; Value = "Password length: 20" }
)
},
@{
Name = "ShowHelp"
RequiresArgs = $true
Args = { @("--help") }
Assertions = @(
@{ Type = "Contains"; Value = "Usage:" }
@{ Type = "Contains"; Value = "--lowercase" }
@{ Type = "Contains"; Value = "--all" }
)
},
@{
Name = "InvalidLengthTooSmall"
RequiresArgs = $true
Args = { @("2", "--all") }
Assertions = @(
@{ Type = "Contains"; Value = "Error: Length must be between 4 and 128" }
)
},
@{
Name = "InvalidLengthTooLarge"
RequiresArgs = $true
Args = { @("500", "--all") }
Assertions = @(
@{ Type = "Contains"; Value = "Error: Length must be between 4 and 128" }
)
}
)
}
"system-info" = @{
File = "system-info.ts"
Tests = @(
@{
Name = "DisplaySystemInfo"
RequiresArgs = $false
Args = { @() }
Assertions = @(
@{ Type = "Contains"; Value = "System Information Report" }
@{ Type = "Contains"; Value = "Platform:" }
@{ Type = "Contains"; Value = "Memory" }
@{ Type = "Contains"; Value = "CPU" }
@{ Type = "Contains"; Value = "Cores:" }
@{ Type = "Contains"; Value = "PID:" }
)
}
)
}
"url-toolkit" = @{
File = "url-toolkit.ts"
Tests = @(
@{
Name = "ParseSimpleURL"
RequiresArgs = $true
Args = { @("https://example.com/path?foo=bar") }
Assertions = @(
@{ Type = "Contains"; Value = "protocol:" }
@{ Type = "Contains"; Value = "https:" }
@{ Type = "Contains"; Value = "hostname:" }
@{ Type = "Contains"; Value = "example.com" }
@{ Type = "Contains"; Value = "pathname:" }
@{ Type = "Contains"; Value = "/path" }
@{ Type = "Contains"; Value = "foo" }
)
},
@{
Name = "ParseURLWithPort"
RequiresArgs = $true
Args = { @("http://localhost:8080/api") }
Assertions = @(
@{ Type = "Contains"; Value = "port:" }
@{ Type = "Contains"; Value = "8080" }
@{ Type = "Contains"; Value = "localhost" }
)
}
)
}
"source-analyzer" = @{
File = "SourceAnalyzer/source-analyzer.ts"
Tests = @(
@{
Name = "AnalyzeTestDirectory"
RequiresArgs = $true
Setup = {
$testDir = Join-Path $Script:TempRoot "analyzer-test"
New-Item -ItemType Directory -Path $testDir -Force | Out-Null
$tsContent = @"
function hello(): void {
console.log('Hello');
}
function goodbye(): void {
console.log('Goodbye');
}
const arrow = () => 42;
"@
Set-Content -Path (Join-Path $testDir "sample.ts") -Value $tsContent
return @{ TestDir = $testDir }
}
Args = { param($ctx) @($ctx.TestDir) }
Assertions = @(
@{ Type = "Contains"; Value = "TOTAL" }
@{ Type = "Contains"; Value = "sample.ts" }
)
},
@{
Name = "HelpFlag"
RequiresArgs = $true
Args = { @("--help") }
Assertions = @(
@{ Type = "Contains"; Value = "Usage:" }
@{ Type = "Contains"; Value = "Supported file extensions" }
)
}
)
}
"web-server" = @{
File = "web-server.ts"
Tests = @(
@{
Name = "ShowHelp"
RequiresArgs = $true
Args = { @("--help") }
Assertions = @(
@{ Type = "Contains"; Value = "SharpTS Web Server Example" }
@{ Type = "Contains"; Value = "Usage:" }
@{ Type = "Contains"; Value = "GET /" }
@{ Type = "Contains"; Value = "/api/time" }
@{ Type = "Contains"; Value = "/api/echo" }
@{ Type = "Contains"; Value = "/api/greet" }
@{ Type = "Contains"; Value = "port" }
)
},
@{
Name = "ShowHelpShortFlag"
RequiresArgs = $true
Args = { @("-h") }
Assertions = @(
@{ Type = "Contains"; Value = "SharpTS Web Server Example" }
@{ Type = "Contains"; Value = "Usage:" }
)
},
@{
Name = "InvalidPortNumber"
RequiresArgs = $true
Args = { @("invalid") }
# Short timeout since server starts quickly; we just need initial output
Timeout = 5000
Assertions = @(
@{ Type = "Contains"; Value = "Invalid port number" }
@{ Type = "Contains"; Value = "Using default port 3000" }
)
},
@{
Name = "PortOutOfRange"
RequiresArgs = $true
Args = { @("99999") }
# Short timeout since server starts quickly; we just need initial output
Timeout = 5000
Assertions = @(
@{ Type = "Contains"; Value = "Invalid port number" }
@{ Type = "Contains"; Value = "Using default port 3000" }
)
}
)
}
"benchmark" = @{
File = "benchmark.ts"
Tests = @(
@{
Name = "RunBenchmarks"
RequiresArgs = $false
Args = { @() }
# Interpreted runs the hot loops ~100x slower; give it room.
Timeout = 60000
Assertions = @(
@{ Type = "Contains"; Value = "SharpTS Benchmark" }
@{ Type = "Contains"; Value = "sum 0..9999" }
@{ Type = "Contains"; Value = "fib(20)" }
@{ Type = "Contains"; Value = "ops/sec" }
@{ Type = "Contains"; Value = "measured: cold-load" }
@{ Type = "Contains"; Value = "timeOrigin" }
)
}
)
}
"dotnet-types" = @{
File = "dotnet-types.ts"
Tests = @(
@{
Name = "DemonstrateDotNetInterop"
RequiresArgs = $false
Args = { @() }
# Runs clean in both modes. Overload dispatch (#51), delegate
# wrapping (#52), and event subscription (#53) all fixed;
# compiled DLLs are fully standalone (no SharpTS.dll needed).
Assertions = @(
@{ Type = "Contains"; Value = ".NET Types from TypeScript" }
@{ Type = "Contains"; Value = "StringBuilder" }
@{ Type = "Contains"; Value = "user=alice" }
@{ Type = "Contains"; Value = "truncates to: 3" }
@{ Type = "Contains"; Value = "delegate body ran on a Task" }
@{ Type = "Contains"; Value = "ProcessExit fired during shutdown" }
)
}
)
}
"npm-uuid" = @{
File = "NpmUuid/npm-uuid.ts"
# Skip entirely if node_modules isn't present — surfaces a clear
# "run npm install first" message rather than an opaque resolve error.
Setup = {
$nm = Join-Path $Script:ExamplesDir "NpmUuid/node_modules"
return @{ NodeModulesPresent = (Test-Path $nm) }
}
SkipIf = { param($ctx) -not $ctx.NodeModulesPresent }
SkipReason = "Run 'cd Examples/NpmUuid && npm install' first"
Tests = @(
@{
Name = "ConsumeUuidPackage"
RequiresArgs = $false
Args = { @() }
Assertions = @(
@{ Type = "Contains"; Value = "npm Package: uuid" }
@{ Type = "Contains"; Value = "Generate UUIDs" }
@{ Type = "Contains"; Value = "validate: true" }
@{ Type = "Contains"; Value = "version: 4" }
@{ Type = "Contains"; Value = "NIL: 00000000-0000-0000-0000-000000000000" }
@{ Type = "Contains"; Value = "matches: true" }
@{ Type = "Contains"; Value = "collisions in 1000: 0" }
)
}
)
}
}
# ========== Fixture Functions ==========
function Initialize-TempDirectory {
if (-not (Test-Path $Script:TempRoot)) {
New-Item -ItemType Directory -Path $Script:TempRoot -Force | Out-Null
}
}
function Remove-TempDirectory {
if ((Test-Path $Script:TempRoot) -and (-not $SkipCleanup)) {
Remove-Item -Path $Script:TempRoot -Recurse -Force -ErrorAction SilentlyContinue
}
}
# ========== Execution Functions ==========
function Invoke-ProcessWithTimeout {
param(
[string]$FilePath,
[string[]]$Arguments,
[int]$Timeout = $Script:ProcessTimeout,
[string]$WorkingDirectory = $Script:ProjectRoot
)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $FilePath
$psi.Arguments = ($Arguments | ForEach-Object {
if ($_ -match '\s') { "`"$_`"" } else { $_ }
}) -join ' '
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.WorkingDirectory = $WorkingDirectory
$psi.CreateNoWindow = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try {
[void]$process.Start()
# Read output asynchronously using tasks
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
$completed = $process.WaitForExit($Timeout)
$sw.Stop()
if (-not $completed) {
$process.Kill()
# Wait for async reads to complete after killing the process
# This captures any output that was written before timeout
[void]$stdoutTask.Wait(5000)
[void]$stderrTask.Wait(5000)
$stdout = if ($stdoutTask.IsCompleted) { $stdoutTask.Result } else { "" }
$stderr = if ($stderrTask.IsCompleted) { $stderrTask.Result } else { "" }
return @{
Success = $false
Output = $stdout
Error = $stderr
ExitCode = -1
Duration = $sw.ElapsedMilliseconds
TimedOut = $true
}
}
# Wait for async reads to complete
[void]$stdoutTask.Wait(5000)
[void]$stderrTask.Wait(5000)
$stdout = if ($stdoutTask.IsCompleted) { $stdoutTask.Result } else { "" }
$stderr = if ($stderrTask.IsCompleted) { $stderrTask.Result } else { "" }
return @{
Success = $process.ExitCode -eq 0
Output = $stdout
Error = $stderr
ExitCode = $process.ExitCode
Duration = $sw.ElapsedMilliseconds
}
}
finally {
$process.Dispose()
}
}
function Invoke-Interpreted {
param(
[string]$TsFile,
[string[]]$Arguments,
[int]$Timeout = $Script:ProcessTimeout
)
$allArgs = @("run", "--", $TsFile) + $Arguments
return Invoke-ProcessWithTimeout -FilePath "dotnet" -Arguments $allArgs -Timeout $Timeout
}
function Invoke-CompiledDll {
param(
[string]$TsFile,
[string[]]$Arguments,
[string]$TestName,
[int]$Timeout = $Script:ProcessTimeout
)
$outputDir = Join-Path $Script:TempRoot "dll-$TestName"
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($TsFile)
$dllPath = Join-Path $outputDir "$baseName.dll"
# Compile to DLL
$compileArgs = @("run", "--", "--compile", $TsFile, "-o", $dllPath)
$compileResult = Invoke-ProcessWithTimeout -FilePath "dotnet" -Arguments $compileArgs -Timeout $Script:BuildTimeout
if (-not $compileResult.Success) {
return @{
Success = $false
Output = $compileResult.Output
Error = "Compilation failed: $($compileResult.Error)"
ExitCode = $compileResult.ExitCode
Duration = $compileResult.Duration
CompileOutput = $compileResult.Output
}
}
# Copy runtimeconfig.json if it exists
$runtimeConfig = Join-Path $Script:ProjectRoot "bin\Debug\net10.0\SharpTS.runtimeconfig.json"
if (Test-Path $runtimeConfig) {
$newConfigPath = Join-Path $outputDir "$baseName.runtimeconfig.json"
Copy-Item -Path $runtimeConfig -Destination $newConfigPath -Force
}
# Run the DLL
$runArgs = @($dllPath) + $Arguments
$runResult = Invoke-ProcessWithTimeout -FilePath "dotnet" -Arguments $runArgs -WorkingDirectory $outputDir -Timeout $Timeout
$runResult.Duration += $compileResult.Duration
$runResult.CompileOutput = $compileResult.Output
return $runResult
}
function Invoke-CompiledExe {
param(
[string]$TsFile,
[string[]]$Arguments,
[string]$TestName,
[int]$Timeout = $Script:ProcessTimeout
)
$outputDir = Join-Path $Script:TempRoot "exe-$TestName"
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($TsFile)
$exePath = Join-Path $outputDir "$baseName.exe"
# Compile to EXE
$compileArgs = @("run", "--", "--compile", $TsFile, "-t", "exe", "-o", $exePath)
$compileResult = Invoke-ProcessWithTimeout -FilePath "dotnet" -Arguments $compileArgs -Timeout $Script:BuildTimeout
if (-not $compileResult.Success) {
return @{
Success = $false
Output = $compileResult.Output
Error = "Compilation failed: $($compileResult.Error)"
ExitCode = $compileResult.ExitCode
Duration = $compileResult.Duration
CompileOutput = $compileResult.Output
}
}
# Run the EXE
$runResult = Invoke-ProcessWithTimeout -FilePath $exePath -Arguments $Arguments -WorkingDirectory $outputDir -Timeout $Timeout
$runResult.Duration += $compileResult.Duration
$runResult.CompileOutput = $compileResult.Output
return $runResult
}
# ========== Assertion Functions ==========
function Test-Assertion {
param(
[string]$Output,
[hashtable]$Assertion
)
switch ($Assertion.Type) {
"Contains" {
return $Output -match [regex]::Escape($Assertion.Value)
}
"Regex" {
return $Output -match $Assertion.Value
}
"NotContains" {
return $Output -notmatch [regex]::Escape($Assertion.Value)
}
default {
return $false
}
}
}
function Test-AllAssertions {
param(
[string]$Output,
[array]$Assertions
)
$results = @()
foreach ($assertion in $Assertions) {
$passed = Test-Assertion -Output $Output -Assertion $assertion
$results += @{
Assertion = $assertion
Passed = $passed
}
}
return $results
}
# ========== Test Runner ==========
function Invoke-TestCase {
param(
[string]$ExampleName,
[hashtable]$Example,
[hashtable]$TestCase,
[string]$ExecutionMode
)
$tsFile = Join-Path $Script:ExamplesDir $Example.File
$testContext = @{}
# Run setup if defined
if ($TestCase.Setup) {
$testContext = & $TestCase.Setup
}
# Get arguments
$args = @()
if ($TestCase.Args) {
$args = & $TestCase.Args $testContext
}
# Get per-test timeout or use default
$runTimeout = if ($TestCase.Timeout) { $TestCase.Timeout } else { $Script:ProcessTimeout }
# Execute based on mode
$result = switch ($ExecutionMode) {
"interpreted" { Invoke-Interpreted -TsFile $tsFile -Arguments $args -Timeout $runTimeout }
"dll" { Invoke-CompiledDll -TsFile $tsFile -Arguments $args -TestName "$ExampleName-$($TestCase.Name)" -Timeout $runTimeout }
"exe" { Invoke-CompiledExe -TsFile $tsFile -Arguments $args -TestName "$ExampleName-$($TestCase.Name)" -Timeout $runTimeout }
}
# Combine stdout and stderr for assertion testing
$combinedOutput = "$($result.Output)`n$($result.Error)"
# Run assertions
$assertionResults = Test-AllAssertions -Output $combinedOutput -Assertions $TestCase.Assertions
$allPassed = ($assertionResults | Where-Object { -not $_.Passed }).Count -eq 0
return @{
TestName = $TestCase.Name
Mode = $ExecutionMode
Passed = $allPassed
Duration = $result.Duration
Output = $result.Output
Error = $result.Error
ExitCode = $result.ExitCode
AssertionResults = $assertionResults
}
}
function Invoke-AllTests {
$startTime = Get-Date
$results = @{
StartTime = $startTime.ToString("o")
Examples = @()
}
$totalTests = 0
$passedTests = 0
$failedTests = 0
$skippedTests = 0
$modesToTest = switch ($Mode) {
"all" { @("interpreted", "dll", "exe") }
default { @($Mode) }
}
# Count total tests for progress
$plannedTests = 0
foreach ($exampleName in $Script:TestCases.Keys) {
if ($exampleName -like $Filter) {
$example = $Script:TestCases[$exampleName]
$plannedTests += $example.Tests.Count * $modesToTest.Count
}
}
# Show progress header for table mode
if ($OutputFormat -eq "table" -and $plannedTests -gt 0) {
Write-Host "Running $plannedTests tests..." -ForegroundColor Cyan
Write-Host ""
}
foreach ($exampleName in $Script:TestCases.Keys | Sort-Object) {
# Apply filter
if ($exampleName -notlike $Filter) {
continue
}
$example = $Script:TestCases[$exampleName]
$exampleResults = @{
Name = $exampleName
File = $example.File
TestCases = @()
}
# Example-level skip check (e.g., "npm install not run yet")
$exampleSkip = $false
$exampleSkipReason = $null
if ($example.Setup -and $example.SkipIf) {
$setupCtx = & $example.Setup
if (& $example.SkipIf $setupCtx) {
$exampleSkip = $true
$exampleSkipReason = if ($example.SkipReason) { $example.SkipReason } else { "SkipIf returned true" }
}
}
# Show example name in table mode
if ($OutputFormat -eq "table") {
Write-Host " $exampleName " -NoNewline
}
foreach ($testCase in $example.Tests) {
$testCaseResult = @{
Name = $testCase.Name
Modes = @()
}
foreach ($mode in $modesToTest) {
$totalTests++
# Per-test-case mode skip (e.g., dotnet-types skips compiled modes)
$caseSkip = $exampleSkip
$caseSkipReason = $exampleSkipReason
if (-not $caseSkip -and $testCase.SkipModes -and ($testCase.SkipModes -contains $mode)) {
$caseSkip = $true
$caseSkipReason = "mode '$mode' in SkipModes"
}
if ($caseSkip) {
$skippedTests++
$testCaseResult.Modes += @{
Mode = $mode
Passed = $true
Skipped = $true
SkipReason = $caseSkipReason
Duration = 0
}
if ($OutputFormat -eq "verbose") {
Write-Host "Testing $exampleName/$($testCase.Name) [$mode]... SKIPPED ($caseSkipReason)" -ForegroundColor Yellow
} elseif ($OutputFormat -eq "table") {
Write-Host "-" -NoNewline -ForegroundColor Yellow
}
continue
}
if ($OutputFormat -eq "verbose") {
Write-Host "Testing $exampleName/$($testCase.Name) [$mode]... " -NoNewline
}
try {
$result = Invoke-TestCase -ExampleName $exampleName -Example $example -TestCase $testCase -ExecutionMode $mode
$testCaseResult.Modes += @{
Mode = $mode
Passed = $result.Passed
Skipped = $false
Duration = $result.Duration
Output = $result.Output
Error = $result.Error
AssertionResults = $result.AssertionResults
}
if ($result.Passed) {
$passedTests++
if ($OutputFormat -eq "verbose") {
Write-Host "PASSED" -ForegroundColor Green
} elseif ($OutputFormat -eq "table") {
Write-Host "." -NoNewline -ForegroundColor Green
}
} else {
$failedTests++
if ($OutputFormat -eq "verbose") {
Write-Host "FAILED" -ForegroundColor Red
$failedAssertions = $result.AssertionResults | Where-Object { -not $_.Passed }
foreach ($failed in $failedAssertions) {
Write-Host " - Failed: $($failed.Assertion.Type) '$($failed.Assertion.Value)'" -ForegroundColor Yellow
}
if ($result.Error) {
Write-Host " - Error: $($result.Error)" -ForegroundColor Yellow
}
} elseif ($OutputFormat -eq "table") {
Write-Host "X" -NoNewline -ForegroundColor Red
}
}
}
catch {
$failedTests++
$testCaseResult.Modes += @{
Mode = $mode
Passed = $false
Skipped = $false
Duration = 0
Error = $_.Exception.Message
}
if ($OutputFormat -eq "verbose") {
Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
} elseif ($OutputFormat -eq "table") {
Write-Host "E" -NoNewline -ForegroundColor Red
}
}
}
$exampleResults.TestCases += $testCaseResult
}
# End line for example in table mode
if ($OutputFormat -eq "table") {
Write-Host ""
}
$results.Examples += $exampleResults
}
$endTime = Get-Date
$results.Duration = ($endTime - $startTime).TotalSeconds
$results.TotalTests = $totalTests
$results.PassedTests = $passedTests
$results.FailedTests = $failedTests
$results.SkippedTests = $skippedTests
return $results
}
# ========== Output Formatters ==========
function Format-TableOutput {
param($Results)
Write-Host ""
Write-Host "SharpTS Examples Test Results" -ForegroundColor Cyan
Write-Host "==============================" -ForegroundColor Cyan
Write-Host ""
$tableData = @()
foreach ($example in $Results.Examples) {
foreach ($testCase in $example.TestCases) {
$row = [PSCustomObject]@{
Example = $example.Name
Test = $testCase.Name
}
foreach ($modeResult in $testCase.Modes) {
$status = if ($modeResult.Skipped) { "SKIP" }
elseif ($modeResult.Passed) { "PASS" }
else { "FAIL" }
$row | Add-Member -NotePropertyName $modeResult.Mode -NotePropertyValue $status
}
$tableData += $row
}
}
$tableData | Format-Table -AutoSize
Write-Host ""
Write-Host "Summary" -ForegroundColor Cyan
Write-Host "-------" -ForegroundColor Cyan
Write-Host "Total: $($Results.TotalTests)"
Write-Host "Passed: $($Results.PassedTests)" -ForegroundColor Green
Write-Host "Failed: $($Results.FailedTests)" -ForegroundColor $(if ($Results.FailedTests -gt 0) { "Red" } else { "Green" })
Write-Host "Skipped: $($Results.SkippedTests)" -ForegroundColor Yellow
Write-Host "Duration: $([math]::Round($Results.Duration, 2))s"
Write-Host ""
}
function Format-JsonOutput {
param($Results)
# Convert to cleaner JSON structure
$jsonResults = @{
StartTime = $Results.StartTime
Duration = $Results.Duration
TotalTests = $Results.TotalTests
PassedTests = $Results.PassedTests
FailedTests = $Results.FailedTests
SkippedTests = $Results.SkippedTests
Examples = @()
}
foreach ($example in $Results.Examples) {
$exJson = @{
Name = $example.Name
TestCases = @()
}
foreach ($tc in $example.TestCases) {
$tcJson = @{
Name = $tc.Name
Modes = @()
}
foreach ($m in $tc.Modes) {
$modeJson = @{
Mode = $m.Mode
Duration = $m.Duration
}
if ($m.Skipped) {
$modeJson.Skipped = $true
$modeJson.SkipReason = $m.SkipReason
} else {
$modeJson.Passed = $m.Passed
}
$tcJson.Modes += $modeJson
}
$exJson.TestCases += $tcJson
}
$jsonResults.Examples += $exJson
}
$jsonResults | ConvertTo-Json -Depth 10
}
# ========== Main Entry Point ==========
try {
# Ensure project is built
Write-Host "Building SharpTS..." -ForegroundColor Cyan
$buildResult = Invoke-ProcessWithTimeout -FilePath "dotnet" -Arguments @("build", "-c", "Debug") -Timeout $Script:BuildTimeout
if (-not $buildResult.Success) {
Write-Host "Build failed:" -ForegroundColor Red
Write-Host $buildResult.Error
exit 1
}
Write-Host "Build completed." -ForegroundColor Green
Write-Host ""
# Initialize temp directory
Initialize-TempDirectory
# Run tests
$results = Invoke-AllTests
# Output results
switch ($OutputFormat) {
"json" { Format-JsonOutput -Results $results }
"table" { Format-TableOutput -Results $results }
"verbose" {
Write-Host ""
Format-TableOutput -Results $results
}
}
# Exit with appropriate code
if ($results.FailedTests -gt 0) {
exit 1
}
exit 0
}
finally {
# Cleanup
Remove-TempDirectory