-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-examples.pl
More file actions
executable file
·3121 lines (2641 loc) · 110 KB
/
test-examples.pl
File metadata and controls
executable file
·3121 lines (2641 loc) · 110 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
#!/usr/bin/env perl
use strict;
use warnings;
use v5.30;
use FindBin qw($RealBin);
use Cwd qw(abs_path cwd);
# Force STDOUT flush on every write (needed when output is piped/redirected)
$| = 1;
# Core modules
use File::Spec;
use File::Basename;
use Getopt::Long;
use Time::HiRes qw(time sleep);
use List::Util qw(sum all);
# Required modules
use IPC::Run qw(start finish timeout kill_kill);
# Try to load optional modules, fall back to basic functionality if not available
my $has_yaml = eval { require YAML::XS; 1; } || 0;
my $has_http_tiny = eval { require HTTP::Tiny; 1; } || 0;
my $has_net_emptyport = eval { require Net::EmptyPort; 1; } || 0;
my $has_term_color = eval { require Term::ANSIColor; 1; } || 0;
# Colored output helper
sub colored {
my ($text, $color) = @_;
return $text unless $has_term_color;
return Term::ANSIColor::colored($text, $color);
}
# Platform detection
my $is_windows = ($^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys');
my $is_linux = ($^O eq 'linux');
my $is_macos = ($^O eq 'darwin');
# Get binary path with proper extension for the platform
# On Windows, executables have .exe extension
sub get_binary_path {
my ($dir, $basename) = @_;
my $binary_name = $is_windows ? "$basename.exe" : $basename;
return File::Spec->catfile($dir, $binary_name);
}
# Check if a file is executable (cross-platform)
# On Windows, -x doesn't work reliably, so we check for .exe extension
sub is_executable {
my ($path) = @_;
if ($is_windows) {
# On Windows, check if the file exists and has .exe extension
return (-e $path && $path =~ /\.exe$/i);
} else {
return -x $path;
}
}
# Configuration
my %options = (
generate => 0,
verbose => 0,
timeout => 60, # Increased for Linux CI linker (default was 10)
filter => '',
help => 0,
);
GetOptions(
'generate' => \$options{generate},
'verbose|v' => \$options{verbose},
'timeout=i' => \$options{timeout},
'filter=s' => \$options{filter},
'help|h' => \$options{help},
) or die "Invalid options. Use --help for usage.\n";
if ($options{help}) {
print_usage();
exit 0;
}
sub print_usage {
print <<'USAGE';
ARO Examples Test Harness
Usage:
./test-examples.pl [OPTIONS] [EXAMPLE]
Options:
--generate Generate expected.txt files for all examples
-v, --verbose Show detailed output
--timeout=N Timeout in seconds for long-running examples (default: 60)
--filter=PATTERN Test only examples matching pattern
-h, --help Show this help
Examples:
# Generate all expected outputs
./test-examples.pl --generate
# Run all tests
./test-examples.pl
# Test only HTTP examples
./test-examples.pl --filter=HTTP
# Test single example
./test-examples.pl HelloWorld
# Verbose mode
./test-examples.pl --verbose
Required Perl Modules:
IPC::Run - Process management (recommended)
YAML::XS - OpenAPI parsing (for HTTP tests)
HTTP::Tiny - HTTP client (for HTTP tests)
Net::EmptyPort - Port detection (for HTTP/socket tests)
Term::ANSIColor - Colored output (optional)
Install with: cpan -i IPC::Run YAML::XS HTTP::Tiny Net::EmptyPort Term::ANSIColor
USAGE
}
# Globals
my $examples_dir = File::Spec->catdir($RealBin, 'Examples');
my %results;
my @cleanup_handlers;
# Signal handling for cleanup
$SIG{INT} = $SIG{TERM} = sub {
warn "\nCaught signal, cleaning up...\n";
$_->() for @cleanup_handlers;
exit 1;
};
# Write to testrun.log in example directory
sub write_testrun_log {
my ($example_name, $mode, $error_type, $message, $cmd, $exit_code) = @_;
my $log_file = File::Spec->catfile($examples_dir, $example_name, 'testrun.log');
# Open in append mode to preserve multiple test runs
if (open my $fh, '>>', $log_file) {
my $timestamp = localtime();
print $fh "=" x 80 . "\n";
print $fh "Timestamp: $timestamp\n";
print $fh "Mode: $mode\n";
print $fh "Error Type: $error_type\n";
if ($cmd) {
print $fh "Command: $cmd\n";
}
if (defined $exit_code) {
print $fh "Exit Code: $exit_code\n";
}
print $fh "Message:\n$message\n";
print $fh "=" x 80 . "\n\n";
close $fh;
} else {
warn "Warning: Could not write to $log_file: $!\n" if $options{verbose};
}
}
# Main execution
sub main {
unless (-d $examples_dir) {
die "Examples directory not found: $examples_dir\n";
}
my @examples;
if (@ARGV) {
# Test specific examples provided as arguments
@examples = @ARGV;
} else {
# Discover all examples
@examples = discover_examples();
}
# Apply filter
if ($options{filter}) {
@examples = grep { /$options{filter}/i } @examples;
}
unless (@examples) {
die "No examples found matching criteria.\n";
}
if ($options{generate}) {
generate_all_expected(\@examples);
} else {
run_all_tests(\@examples);
}
}
# Discover all example directories
sub discover_examples {
opendir my $dh, $examples_dir or die "Cannot open $examples_dir: $!";
# Directories to exclude from testing
my %excluded = (
'template' => 1, # Template directory
'data' => 1, # Test output directory
'output' => 1, # Test output directory
'demo-output' => 1, # Test output directory
);
my @examples = grep {
-d File::Spec->catdir($examples_dir, $_) &&
!/^\./ &&
!$excluded{$_}
} readdir $dh;
closedir $dh;
return sort @examples;
}
# Read test.hint file for an example if it exists
# Returns hash reference with parsed directives
sub read_test_hint {
my ($example_name) = @_;
my $hint_file = File::Spec->catfile($examples_dir, $example_name, 'test.hint');
my %hints = (
workdir => undef,
timeout => undef,
type => undef,
mode => undef,
skip => undef,
'skip-on-windows' => undef,
'skip-on-linux' => undef,
'skip-on-macos' => undef,
'pre-script' => undef,
'test-script' => undef,
'occurrence-check' => undef,
'keep-alive' => undef,
'allow-error' => undef,
'skip-build' => undef,
'normalize-dict' => undef,
'strip-prefix' => undef,
'random-output' => undef,
'include-server-output' => undef,
'request-delay' => undef,
);
# Return empty hints if file doesn't exist (backward compatible)
return \%hints unless -f $hint_file;
open my $fh, '<', $hint_file or do {
warn "Warning: Cannot read $hint_file: $!\n" if $options{verbose};
return \%hints;
};
my $line_no = 0;
while (my $line = <$fh>) {
$line_no++;
# Strip whitespace
chomp $line;
$line =~ s/^\s+|\s+$//g;
# Skip comments and blank lines
next if !$line || $line =~ /^#/;
# Parse key: value
if ($line =~ /^([^:]+):\s*(.*)$/) {
my $key = lc $1;
my $value = $2;
# Strip value whitespace
$value =~ s/^\s+|\s+$//g;
# Validate and store
if (exists $hints{$key}) {
if (defined $hints{$key} && $options{verbose}) {
warn "Warning: $hint_file:$line_no duplicate key '$key' (overriding)\n";
}
$hints{$key} = $value;
} elsif ($options{verbose}) {
warn "Warning: $hint_file:$line_no unknown directive '$key'\n";
}
} elsif ($options{verbose}) {
warn "Warning: $hint_file:$line_no malformed line (expected 'key: value'): $line\n";
}
}
close $fh;
# Validate values
if (defined $hints{timeout} && $hints{timeout} !~ /^\d+$/) {
warn "Warning: Invalid timeout value '$hints{timeout}' (must be integer), ignoring\n";
$hints{timeout} = undef;
}
if (defined $hints{type} && $hints{type} !~ /^(console|http|socket|socket-client|file|multi-context|multiservice)$/) {
warn "Warning: Invalid type '$hints{type}' (must be console|http|socket|socket-client|file|multi-context|multiservice), ignoring\n";
$hints{type} = undef;
}
if (defined $hints{mode} && $hints{mode} !~ /^(both|interpreter|compiled|test)$/) {
warn "Warning: Invalid mode '$hints{mode}' (must be both|interpreter|compiled|test), defaulting to 'both'\n";
$hints{mode} = 'both';
}
return \%hints;
}
# Find the aro binary - checks environment variable, then local build, then installed versions
sub find_aro_binary {
my $exe_ext = $is_windows ? '.exe' : '';
# 1. Check if ARO_BIN environment variable is set
if ($ENV{ARO_BIN} && is_executable($ENV{ARO_BIN})) {
return $ENV{ARO_BIN};
}
# 2. Check local release build first (most up-to-date during development)
my $local_release = File::Spec->catfile($RealBin, '.build', 'release', "aro$exe_ext");
if (is_executable($local_release)) {
return $local_release;
}
if (!$is_windows) {
# 3. Check /usr/bin/aro (system install) - Unix only
if (-x '/usr/bin/aro') {
return '/usr/bin/aro';
}
# 4. Check /opt/homebrew/bin/aro (Homebrew on Apple Silicon)
if (-x '/opt/homebrew/bin/aro') {
return '/opt/homebrew/bin/aro';
}
}
# 5. Check ./aro-bin/aro (local binary directory - used in CI)
my $local_bin = File::Spec->catfile($RealBin, 'aro-bin', "aro$exe_ext");
if (is_executable($local_bin)) {
return $local_bin;
}
# 6. Last resort: try 'aro' in PATH and let shell find it
my $which_cmd = $is_windows ? "where aro$exe_ext 2>nul" : "which aro 2>/dev/null";
my $which_aro = `$which_cmd`;
chomp $which_aro;
# On Windows, 'where' can return multiple lines; take the first
($which_aro) = split /\n/, $which_aro if $which_aro;
if ($which_aro && is_executable($which_aro)) {
return $which_aro;
}
# Fallback: return 'aro' and hope for the best
return 'aro';
}
# Build an example using 'aro build'
# Returns hash with success status, binary path, error message, and build duration
sub build_example {
my ($example_name, $timeout, $workdir) = @_;
# Use workdir if specified, otherwise use example_name
my $dir;
if (defined $workdir) {
# Convert relative workdir to absolute path
if (File::Spec->file_name_is_absolute($workdir)) {
$dir = $workdir;
} else {
$dir = File::Spec->catdir($RealBin, $workdir);
}
} else {
$dir = File::Spec->catdir($examples_dir, $example_name);
}
my $aro_bin = find_aro_binary();
my $start_time = time;
# Execute: aro build <dir>
# Use --keep-intermediate to preserve LLVM IR for debugging failures
my ($in, $out, $err) = ('', '', '');
my $handle = eval {
start(
[$aro_bin, 'build', $dir, '--keep-intermediate'],
\$in, \$out, \$err,
timeout($timeout)
);
};
if ($@) {
my $error_msg = "Build failed to start: $@";
write_testrun_log($example_name, 'compiled', 'BUILD_START_FAILURE', $error_msg, "$aro_bin build $dir", undef);
return {
success => 0,
error => $error_msg,
duration => 0,
};
}
eval { finish($handle) };
my $build_duration = time - $start_time;
if ($? != 0) {
my $combined_err = $err || $out;
my $exit_code = $? >> 8;
my $error_msg = "Build failed: $combined_err";
write_testrun_log($example_name, 'compiled', 'BUILD_FAILURE', $error_msg, "$aro_bin build $dir", $exit_code);
return {
success => 0,
error => $error_msg,
duration => $build_duration,
};
}
# Check if binary exists
my $basename = basename($dir);
my $binary_path = get_binary_path($dir, $basename);
unless (is_executable($binary_path)) {
# Include build output in error message for debugging
my $build_output = $out || $err || "(no output)";
my $error_msg = "Binary not found at: $binary_path\n\nBuild output:\n$build_output";
write_testrun_log($example_name, 'compiled', 'BINARY_NOT_FOUND', $error_msg, "$aro_bin build $dir", 0);
return {
success => 0,
error => $error_msg,
duration => $build_duration,
};
}
return {
success => 1,
binary_path => $binary_path,
duration => $build_duration,
};
}
# Run test with specified working directory
# Handles chdir, executes appropriate test runner, restores original directory
sub run_test_in_workdir {
my ($example_name, $workdir, $timeout, $type, $pre_script, $mode, $hints) = @_;
$mode //= 'interpreter'; # Default to interpreter mode
my $orig_cwd = cwd();
my $output;
my $error;
my $run_dir = $example_name; # Default: use example name as-is
my $binary_name; # For compiled mode when using workdir
# Change directory if specified
if (defined $workdir) {
# Convert relative path to absolute (relative to project root)
my $abs_workdir = $workdir;
unless (File::Spec->file_name_is_absolute($workdir)) {
$abs_workdir = File::Spec->catdir($RealBin, $workdir);
}
unless (-d $abs_workdir) {
return (undef, "ERROR: workdir does not exist: $abs_workdir");
}
unless (chdir $abs_workdir) {
return (undef, "ERROR: Cannot change to workdir $abs_workdir: $!");
}
say " Changed to workdir: $abs_workdir" if $options{verbose};
# When running from workdir, use current directory
$run_dir = '.';
# Use workdir's directory name for finding compiled binary (e.g., Combined from Examples/ModulesExample/Combined)
$binary_name = basename($abs_workdir);
}
# Execute pre-script if specified
if (defined $pre_script) {
say " Running pre-script: $pre_script" if $options{verbose};
my ($out, $err, $exit_code) = run_script($pre_script, $timeout, "pre-script");
if ($exit_code != 0) {
unless (chdir $orig_cwd) {
warn "WARNING: Cannot restore directory $orig_cwd: $!\n";
}
return (undef, "Pre-script failed (exit $exit_code): $err");
}
say " Pre-script output: $out" if $options{verbose} && $out;
}
# Execute with current timeout based on type
# Pass $run_dir instead of $example_name to the internal functions
# Pass $binary_name for compiled mode when using workdir
if ($type eq 'console') {
($output, $error) = run_console_example_internal($run_dir, $timeout, $mode, $binary_name, $hints);
} elsif ($type eq 'http') {
($output, $error) = run_http_example_internal($run_dir, $timeout, $mode, $binary_name, $hints);
} elsif ($type eq 'socket') {
($output, $error) = run_socket_example_internal($run_dir, $timeout, $mode, $binary_name);
} elsif ($type eq 'socket-client') {
($output, $error) = run_socket_client_example_internal($run_dir, $timeout, $mode, $binary_name);
} elsif ($type eq 'file') {
($output, $error) = run_file_watcher_example_internal($run_dir, $timeout, $mode, $binary_name);
} elsif ($type eq 'multiservice') {
($output, $error) = run_multiservice_example_internal($run_dir, $timeout, $mode, $binary_name);
}
# Restore original directory
unless (chdir $orig_cwd) {
warn "WARNING: Cannot restore directory $orig_cwd: $!\n";
}
return ($output, $error);
}
# Run a shell script with timeout support
sub run_script {
my ($script, $timeout, $context) = @_;
# Use IPC::Run for timeout support
my ($in, $out, $err) = ('', '', '');
my $handle = eval {
start(['sh', '-c', $script], \$in, \$out, \$err,
timeout($timeout));
};
if ($@) {
return (undef, "Failed to start $context: $@", -1);
}
# Wait for completion
eval { $handle->finish; };
my $exit_code = $? >> 8;
return ($out, $err, $exit_code);
}
# Detect example type
sub detect_example_type {
my ($example_name) = @_;
my $dir = File::Spec->catdir($examples_dir, $example_name);
# Check for OpenAPI contract with non-empty paths
if (-f File::Spec->catfile($dir, 'openapi.yaml')) {
# Only treat as HTTP if the spec has actual paths defined
if ($has_yaml) {
my $has_paths = 0;
eval {
my $spec = YAML::XS::LoadFile(File::Spec->catfile($dir, 'openapi.yaml'));
$has_paths = 1 if $spec->{paths} && keys %{$spec->{paths}} > 0;
};
# Return 'http' if we found actual paths
return 'http' if $has_paths;
# Otherwise fall through to console detection
} else {
# If YAML::XS not available, assume HTTP (conservative)
return 'http';
}
}
# Check ARO source for specific patterns
my @aro_files = glob File::Spec->catfile($dir, '*.aro');
for my $file (@aro_files) {
open my $fh, '<', $file or next;
my $content = do { local $/; <$fh> };
close $fh;
return 'socket' if $content =~ /Start\s+the\s+<socket-server>/;
return 'file' if $content =~ /Start\s+the\s+<file-monitor>/;
}
return 'console';
}
# Normalize dictionary literals by sorting keys
# Handles Swift/ARO dictionary format: ["key1": "val1", "key2": "val2"]
sub normalize_dict_literals {
my ($output) = @_;
# Process line by line to find dictionary literals
my @lines = split /\n/, $output;
my @result_lines;
for my $line (@lines) {
# Look for dictionary literals starting with [ and containing "key": patterns
if ($line =~ /\[("[^"]+"\s*:.*)\]/) {
# Extract the content between brackets
my $before_bracket = $`;
my $after_bracket = $';
# Parse key-value pairs more carefully
my $dict_content = $1;
my @pairs;
# Match "key": followed by either a quoted string or non-comma/bracket content
# This regex handles: "key": "value with, comma" or "key": value
while ($dict_content =~ /"([^"]+)"\s*:\s*("(?:[^"\\]|\\.)*"|[^,\]]+)/g) {
my $key = $1;
my $value = $2;
$value =~ s/\s+$//; # Trim trailing whitespace
push @pairs, [$key, $value];
}
if (@pairs) {
# Sort by key
@pairs = sort { $a->[0] cmp $b->[0] } @pairs;
# Rebuild the dictionary literal with sorted keys
my $sorted = '[' . join(', ', map { qq{"$_->[0]": $_->[1]} } @pairs) . ']';
$line = $before_bracket . $sorted . $after_bracket;
}
}
push @result_lines, $line;
}
return join("\n", @result_lines);
}
# Normalize output for comparison
sub normalize_output {
my ($output, $type) = @_;
# Remove ANSI escape codes (colors, bold, etc.)
$output =~ s/\e\[[0-9;]*m//g;
# Remove Objective-C duplicate class warnings (macOS Swift runtime conflicts)
# These occur when both system Swift and toolchain Swift runtimes are loaded
# Example: objc[12345]: Class _TtCs27_KeyedEncodingContainerBase is implemented in both ...
$output =~ s/^objc\[\d+\]: Class .* is implemented in both .* One of the duplicates must be removed or renamed\.\n//gm;
# Remove timing values from test output (e.g., "(1ms)", "(<1ms)")
$output =~ s/\s*\([<]?\d+m?s\)//g;
# Remove leading whitespace from lines (test output has indentation)
$output =~ s/^[ \t]+//gm;
# Remove bracketed prefixes at start of lines (e.g., [Application-Start], [OK], etc.)
# Binary applications don't output these, only the interpreter does
# Pattern: [LetterFollowedByAlphanumericSpacesHyphens] at line start
# This avoids matching JSON-like brackets in content (e.g., ["data": "value"])
# Use [ \t]* instead of \s* to preserve newlines (blank lines from empty Log statements)
$output =~ s/^\[[A-Za-z][A-Za-z0-9 -]*\][ \t]*//gm;
# Remove ISO timestamps
$output =~ s/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?/__TIMESTAMP__/g;
# Normalize ls -la timestamps (month day time/year before filename)
# Matches: "Jan 3 12:26" or "Dec 31 2025" in ls output
$output =~ s/^([\-dlrwxs@+]+\s+\d+\s+\w+\s+\w+\s+\d+\s+)\w+\s+\d+\s+[\d:]+/$1__DATE__/gm;
# Normalize ls -la total blocks count
$output =~ s/listing\.output: total \d+/listing.output: total __TOTAL__/g;
# Normalize API response times (generationtime_ms from weather API)
$output =~ s/generationtime_ms: \d+\.\d+/generationtime_ms: __TIME__/g;
# Normalize paths (absolute -> relative)
my $base_dir = $RealBin;
$output =~ s/\Q$base_dir\E/./g;
# Normalize line endings
$output =~ s/\r\n/\n/g;
# Remove trailing whitespace
$output =~ s/ +$//gm;
# Normalize hash values (for HashTest example)
$output =~ s/\b[a-f0-9]{32,64}\b/__HASH__/g if $type && $type eq 'hash';
# Normalize floating point numbers with excessive precision in JSON (for HTTP tests)
# E.g., 249.99000000000001 -> 249.99
if ($type && $type eq 'http') {
$output =~ s/(\d+\.\d{1,2})0{6,}\d+/$1/g;
}
return $output;
}
# Convert expected output with placeholders to regex pattern
# Supports: __ID__, __UUID__, __TIMESTAMP__, __DATE__, __NUMBER__, __STRING__
# Each pattern also matches the literal placeholder (for normalized output comparison)
sub expected_to_pattern {
my ($expected) = @_;
# Escape regex metacharacters in the expected string
my $pattern = quotemeta($expected);
# Replace escaped placeholders with actual regex patterns
# Each pattern matches either the dynamic value OR the literal placeholder
# (since normalize_output may have replaced values with placeholders)
# __ID__ - matches hex IDs like 19b8607cf80ae931b1f (timestamp + random)
$pattern =~ s/__ID__/(?:[a-f0-9]{15,20}|__ID__)/g;
# __UUID__ - matches UUIDs like 550e8400-e29b-41d4-a716-446655440000 (case-insensitive)
$pattern =~ s/__UUID__/(?:[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}|__UUID__)/g;
# __TIMESTAMP__ - matches ISO timestamps like 2025-01-03T23:43:37.478982169+01:00 or 2026-01-03T22:45
$pattern =~ s/__TIMESTAMP__/(?:\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})?|__TIMESTAMP__)/g;
# __DATE__ - matches dates like Jan 3 23:43 or 2025-01-03 (already used in DirectoryLister)
$pattern =~ s/__DATE__/(?:\\w{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}|\\d{4}-\\d{2}-\\d{2}|__DATE__)/g;
# __NUMBER__ - matches any number (integer or decimal)
$pattern =~ s/__NUMBER__/(?:-?\\d+(?:\\.\\d+)?|__NUMBER__)/g;
# __STRING__ - matches any non-empty string (non-greedy, no quotes)
$pattern =~ s/__STRING__/(?:.+?|__STRING__)/g;
# __HASH__ - matches hash values (32-64 hex chars) - already used in HashTest
$pattern =~ s/__HASH__/(?:[a-f0-9]{32,64}|__HASH__)/g;
# __TOTAL__ - matches total blocks count in ls output
$pattern =~ s/__TOTAL__/(?:\\d+|__TOTAL__)/g;
# __TIME__ - matches decimal time values like generationtime_ms (0.08, 1.23)
$pattern =~ s/__TIME__/(?:\\d+\\.\\d+|__TIME__)/g;
return $pattern;
}
# Automatically replace dynamic values with placeholders for --generate
sub auto_placeholderize {
my ($output, $type) = @_;
# For HTTP tests, replace hex IDs with __ID__
if ($type && $type eq 'http') {
# Replace hex IDs (15-20 chars) in JSON id fields
$output =~ s/"id":"[a-f0-9]{15,20}"/"id":"__ID__"/g;
# Replace UUIDs (e.g. in observer output after ---server--- separator)
$output =~ s/[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}/__UUID__/g;
# Normalize floating point numbers with excessive precision (e.g., 249.99000000000001 -> 249.99)
# Match numbers like: 123.45000000000001
$output =~ s/(\d+\.\d{1,2})0{6,}\d+/$1/g;
}
# Replace ISO timestamps (with or without seconds, timezone)
$output =~ s/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?/__TIMESTAMP__/g;
# For console tests with weather/API data, replace numbers in specific contexts
if ($type && $type eq 'console') {
# Replace generationtime_ms with __TIME__ (special case)
$output =~ s/generationtime_ms:\s*\d+\.\d+/generationtime_ms: __TIME__/g;
# Replace numbers after "temperature:", "windspeed:", etc. (weather data)
$output =~ s/(temperature|windspeed|winddirection|elevation|latitude|longitude|is_day|weathercode):\s*-?\d+(?:\.\d+)?/$1: __NUMBER__/g;
}
return $output;
}
# Check if actual output matches expected pattern (with placeholder support)
sub matches_pattern {
my ($actual, $expected) = @_;
# Split into lines for line-by-line comparison
my @actual_lines = split /\n/, $actual;
my @expected_lines = split /\n/, $expected;
# Must have same number of lines
return 0 if scalar(@actual_lines) != scalar(@expected_lines);
# Check each line
for (my $i = 0; $i < scalar(@expected_lines); $i++) {
my $expected_line = $expected_lines[$i];
my $actual_line = $actual_lines[$i];
# Convert expected line to pattern
my $pattern = expected_to_pattern($expected_line);
# Check if actual line matches pattern
unless ($actual_line =~ /^$pattern$/) {
return 0;
}
}
# All lines matched
return 1;
}
# Check if all expected lines occur in output (order-independent)
sub check_output_occurrences {
my ($actual, $expected) = @_;
# Split into lines
my @expected_lines = split /\n/, $expected;
my @missing = ();
# Check each expected line appears in actual output
for my $expected_line (@expected_lines) {
# Skip empty lines
next if $expected_line =~ /^\s*$/;
# Use expected_to_pattern to convert placeholders like __NUMBER__, __TIMESTAMP__, etc.
my $pattern = expected_to_pattern($expected_line);
# Check if line appears anywhere in actual output
unless ($actual =~ /$pattern/m) {
push @missing, $expected_line;
}
}
# If no missing lines, test passes
return (scalar(@missing) == 0, \@missing);
}
# Run console example (public interface)
sub run_console_example {
my ($example_name) = @_;
return run_console_example_internal($example_name, $options{timeout});
}
# Run console example (internal with timeout parameter)
sub run_console_example_internal {
my ($example_name, $timeout, $mode, $binary_name, $hints) = @_;
$mode //= 'interpreter'; # Default to interpreter mode
my $keep_alive = $hints && $hints->{'keep-alive'};
my $allow_error = $hints && $hints->{'allow-error'};
# Handle '.' or absolute paths directly, otherwise prepend examples_dir
my $dir;
if ($example_name eq '.' || File::Spec->file_name_is_absolute($example_name)) {
$dir = $example_name;
} else {
$dir = File::Spec->catdir($examples_dir, $example_name);
}
# Determine command based on mode
my @cmd;
if ($mode eq 'compiled') {
# Execute compiled binary directly
# Use provided binary_name (for workdir cases) or derive from dir
my $basename = defined $binary_name ? $binary_name : basename($dir);
my $binary_path = get_binary_path($dir, $basename);
unless (is_executable($binary_path)) {
return (undef, "ERROR: Compiled binary not found at $binary_path");
}
@cmd = ($binary_path);
# Add --keep-alive flag for long-running apps that need SIGINT shutdown
push @cmd, '--keep-alive' if $keep_alive;
} elsif ($mode eq 'test') {
# Use 'aro test' command
my $aro_bin = find_aro_binary();
@cmd = ($aro_bin, 'test', $dir);
} else {
# Interpreter mode (default)
my $aro_bin = find_aro_binary();
@cmd = ($aro_bin, 'run', $dir);
# Add --keep-alive flag for long-running apps that need SIGINT shutdown
push @cmd, '--keep-alive' if $keep_alive;
}
# Inject free-port env vars so examples that self-host HTTP/socket servers
# don't conflict with other processes (e.g. kubectl port-forward on 8080).
# Harmless for examples that don't start servers (env vars are simply ignored).
local $ENV{ARO_HTTP_PORT} = $ENV{ARO_HTTP_PORT} // ($has_net_emptyport ? Net::EmptyPort::empty_port(8080) : 8080);
local $ENV{ARO_SOCKET_PORT} = $ENV{ARO_SOCKET_PORT} // ($has_net_emptyport ? Net::EmptyPort::empty_port(9000) : 9000);
# Use IPC::Run for better control
my ($in, $out, $err) = ('', '', '');
my $handle = eval {
start(\@cmd, \$in, \$out, \$err, timeout($timeout));
};
if ($@) {
return (undef, "Failed to start: $@");
}
if ($keep_alive) {
# Wait for the application to start, then send SIGINT for graceful shutdown
sleep 1;
# Drain stdout/stderr pipe before sending SIGINT
eval { pump $handle while $handle->pumpable && length($out) == 0 };
say " Sending SIGINT for graceful shutdown" if $options{verbose};
eval { $handle->signal('INT'); };
# Allow time for Application-End handler to execute and flush output
sleep 1;
# Drain remaining output after SIGINT
eval { pump $handle while $handle->pumpable };
}
eval {
finish($handle);
};
if ($@) {
if ($@ =~ /timeout/) {
kill_kill($handle);
# If allow-error is set, return captured output even on timeout
if ($allow_error) {
my $combined = $out;
$combined .= $err if $err;
return ($combined, undef);
}
return (undef, "TIMEOUT after ${timeout}s");
}
return (undef, "ERROR: $@") unless $allow_error;
}
# Combine stdout and stderr
my $combined = $out;
$combined .= $err if $err;
return ($combined, undef);
}
# Run debug example (internal with timeout parameter)
# Runs example with --debug flag for developer context output
sub run_debug_example {
my ($example_name, $timeout, $mode, $binary_name, $hints) = @_;
$mode //= 'interpreter'; # Default to interpreter mode
my $keep_alive = $hints && $hints->{'keep-alive'};
# Handle '.' or absolute paths directly, otherwise prepend examples_dir
my $dir;
if ($example_name eq '.' || File::Spec->file_name_is_absolute($example_name)) {
$dir = $example_name;
} else {
$dir = File::Spec->catdir($examples_dir, $example_name);
}
# Determine command based on mode
my @cmd;
if ($mode eq 'compiled') {
# Execute compiled binary with --debug
my $basename = defined $binary_name ? $binary_name : basename($dir);
my $binary_path = get_binary_path($dir, $basename);
unless (is_executable($binary_path)) {
return (undef, "ERROR: Compiled binary not found at $binary_path");
}
@cmd = ($binary_path, '--debug');
# Add --keep-alive flag for long-running apps that need SIGINT shutdown
push @cmd, '--keep-alive' if $keep_alive;
} else {
# Interpreter mode with --debug flag
my $aro_bin = find_aro_binary();
@cmd = ($aro_bin, 'run', '--debug', $dir);
# Add --keep-alive flag for long-running apps that need SIGINT shutdown
push @cmd, '--keep-alive' if $keep_alive;
}
# Inject free ports so the debug server doesn't collide with kubectl or other processes
local $ENV{ARO_HTTP_PORT} = $ENV{ARO_HTTP_PORT} // ($has_net_emptyport ? Net::EmptyPort::empty_port(8080) : 8080);
local $ENV{ARO_SOCKET_PORT} = $ENV{ARO_SOCKET_PORT} // ($has_net_emptyport ? Net::EmptyPort::empty_port(9000) : 9000);
# Use IPC::Run for better control
my ($in, $out, $err) = ('', '', '');
my $handle = eval {
start(\@cmd, \$in, \$out, \$err, timeout($timeout));
};
if ($@) {
return (undef, "Failed to start: $@");
}
if ($keep_alive) {
# Wait for the application to start, then send SIGINT for graceful shutdown
sleep 1;
# Drain stdout/stderr pipe before sending SIGINT
eval { pump $handle while $handle->pumpable && length($out) == 0 };
say " Sending SIGINT for graceful shutdown" if $options{verbose};
eval { $handle->signal('INT'); };
# Allow time for Application-End handler to execute and flush output
sleep 1;
# Drain remaining output after SIGINT
eval { pump $handle while $handle->pumpable };
}
eval {
finish($handle);
};
if ($@) {
if ($@ =~ /timeout/) {
kill_kill($handle);
return (undef, "TIMEOUT after ${timeout}s");
}
return (undef, "ERROR: $@");
}
# Combine stdout and stderr
my $combined = $out;
$combined .= $err if $err;
return ($combined, undef);
}
# Determine execution order for an operation (lower = earlier)
sub get_operation_order {
my ($operation_id, $path) = @_;
# Handle empty or undefined operation IDs
$operation_id //= '';
$path //= '';
# Order groups (0-9 = setup, 10-19 = read, 20-29 = create, 30-89 = updates, 90-99 = cleanup)
return 10 if $operation_id =~ /^list/i; # List operations first
return 15 if $operation_id =~ /^get/i && $path =~ /\{/; # Get by ID after list
return 20 if $operation_id =~ /^create/i; # Create operations next
# State transition order for common workflows
return 31 if $operation_id =~ /place/i; # place (draft -> placed)