-
Notifications
You must be signed in to change notification settings - Fork 1
/
test-fix
executable file
·2261 lines (2118 loc) · 72.1 KB
/
test-fix
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 5.10.1;
use lib do {
package Local; # make 'Cwd' local to scope
use Cwd 'realpath';
realpath(__FILE__) =~ m#^(.*)/#; # script's real path
"$1/lib/perl5/site_perl";
};
sub usage {
return <<'END_USAGE';
Options available:
cover run test with code coverage (needs all tests to pass)
END_USAGE
}
# Returns full path of the first command (of a list of commands) that can be
# found in path (similar to shell command 'which'). For commands which can be
# founds in several directories found in $PATH only the fist occurring path is
# reported. Returns empty list or undef if none of the commands could be found
# in path.
sub which {
my (@cmd) = @_;
my @path = split(":", $ENV{PATH});
foreach my $cmd (@cmd) {
foreach (@path) {
my $full = "$_/$cmd";
if (-f $full && -x _) { return $full }
}
}
return ();
}
{
my @cover_command; # set below when using Devel::Cover
BEGIN {
if (@ARGV) {
if ($ARGV[0] eq 'cover') {
shift;
require Devel::Cover;
Devel::Cover->import(
qw/-coverage all -silent 1 +ignore/, qr{/Test/Most|test-fix}
);
my ($version) = $^V =~ /^v(\d+\.\d+)/;
@cover_command = which("cover", "cover-$version")
or die "$0: Cannot find command 'cover' or 'cover-$version'\n"
. " (Are you sure Devel::Cover is installed?)\n"
. " (MacPort: 'p5-devel-cover', apt-package: "
. "'libdevel-cover-perl')";
} else {
warn usage();
# Block around exit is to hide it from 'exit' detector thingy.
{ exit 1 }
}
}
}
END { system @cover_command if @cover_command }
}
my $in_main = 1;
END {
if ($? and $in_main) {
warn
"# #################################\n" .
"# ## THERE WERE FAILING TESTS! ##\n" .
"# #################################\n";
}
}
# load Test::Most module
# (gracefully suggesting missing Debian package on failure)
BEGIN {
my $in_main = undef;
eval { require Test::Most }
or die "Cannot load required perl module Test::Most\n",
"Install module (on Debian/Ubuntu) with:\n\n",
" apt-get install libtest-most-perl\n\n";
Test::Most->import();
}
use File::Path qw( mkpath rmtree );
use Carp 'confess';
$SIG{__DIE__} = \&Carp::confess;
our $Dir;
BEGIN {
package Local;
use Cwd qw/realpath/;
($Dir) = realpath(__FILE__) =~ m#^(.*)/#;
require "$Dir/fix"; # load 'fix' as a module
Local::Modulino->import();
}
# Workarounds for 'Test::More::subtest()'
BEGIN {
sub no_implicit_done_testing_in_subtest { # return true if implicit
open(my $o, ">&STDOUT"); # 'done_testing()' is
open(my $e, ">&STDERR"); # missing in 'subtest()'
open(STDOUT, ">/dev/null");
open(STDERR, ">/dev/null");
my $ok = subtest(_ => sub { pass() });
Test::More->builder->reset();
open(STDOUT, ">&", $o);
open(STDERR, ">&", $e);
return !$ok;
}
if (not exists &subtest) {
*subtest = sub { # subtest() missing in
my ($name, $code) = @_; # Test::More
$code->();
note $name;
};
} elsif (no_implicit_done_testing_in_subtest()) {
no warnings 'redefine';
*subtest = sub($&) { # implicit done_testing()
my ($name, $code) = @_; # missing in subtest()
Test::More::subtest($name, sub {
$code->();
done_testing();
});
};
}
}
our $name = 'fix';
our $keep = ".$name/keep"; # keepstate directory
our $run = ".$name/run"; # runstate directory
our $stats = ".$name/stats";
our $fix = "$Dir/fix";
our $testdir = make_tempdir($name);
###############################################################################
## ##
## Functions ##
## ##
###############################################################################
# Delete file(s). Ignore errors if file is gone in the end.
sub delete_file {
my (@file) = @_;
foreach my $file (@file) {
next unless -e $file;
unlink($file) or die "Failed to delete file '$file': $!,";
}
}
# Write to a temporary file, so that we know the inode number will change when
# a file is rewritten (which guarantees that a newly written file will have a
# different stat fingerprint, even if it have the same content). Thus we know
# don't have to use Time::HiRes to get sub-second resolution in the
# fingerprinting.
sub write_file {
my %arg = @_;
foreach my $file (keys %arg) {
my $outfile = "$file--tmp";
# create full path of file before writing file
if (my ($dir) = $outfile =~ m#^(.*)/#) {
die "Cannot create dir '$dir': File already exists\n"
if -e $dir and not -d $dir;
unless (-d $dir or mkpath($dir)) {
warn "Cannot create dir '$dir'\n";
return undef;
}
}
open(my $out, '>', $outfile)
or die "Cannot open file '$outfile' for writing: $!,";
print $out $arg{$file};
close($out)
or die "Cannot close file '$outfile' after writing: $!,";
rename($outfile, $file)
or die "Cannot rename file '$outfile' -> '$file' after writing: $!,";
}
}
# Write files, then make them executable.
sub write_exe_file {
my %arg = @_;
write_file(%arg);
chmod(0755, $_) or die "Cannot chmod file '$_': $!\n" foreach keys %arg;
}
sub read_file {
my ($file) = @_;
open(my $in, '<', $file)
or return undef;
local $/ = undef;
return <$in>;
}
# Return stat fingerprint (or empty string if file doesn't exist).
#
# Note: We can't use Time::HiRes here, since it only supports lstat() since
# February 2013. [https://rt.cpan.org/Public/Bug/Display.html?id=83356]
sub read_file_fingerprint {
my ($file) = @_;
my @stat = lstat($file);
return join("-", @stat ? @stat[1, 2, 4, 5, 7, 9, 10] : ());
}
# Return hash of filenames (as keys) and stat fingerprints (as values).
sub fingerprints {
my (@file) = @_;
return map {
$_ => read_file_fingerprint($_);
} @file;
}
sub make_tempdir {
my ($name) = @_;
my $tempdir = `mktemp -td $name-XXXXXX`;
chomp($tempdir);
return $tempdir;
}
{
my $count = 1;
my $current = '';
sub enter_dir {
my ($dir) = @_;
$current = "$testdir/" . sprintf("%02d", $count++) . "-$dir";
mkdir($current) or die "Cannot create '$current': $!,";
chdir($current) or die "Cannot cd to '$current': $!,";
$ENV{PWD} = $current;
note "DIR: $ENV{PWD}";
}
sub get_dir { $current }
}
sub nl { join "", map "$_\n", @_ }
sub sha1 {
my ($data) = @_;
use Digest::SHA qw(sha1_base64);
use Encode qw(encode_utf8);
sha1_base64(encode_utf8($data));
}
# Return keys in hash, sorted by first by length, then alphabetically.
sub key(\%) {
sort { length($a) <=> length($b) or $a cmp $b } keys %{ shift() };
}
sub serialize {
my (%x) = @_;
use Data::Dumper;
local $Data::Dumper::Indent = 1;
local $Data::Dumper::Sortkeys = 1;
local $Data::Dumper::Terse = 1;
return Dumper \%x;
}
# for use with keepstate()
sub SOURCE { 'source' }
sub TARGET { 'target' }
sub keepstate {
my ($type, $content, $deps, $source, $result) = @_;
# Add checksum from keepstate to each dependency.
@$deps = map {
[ map {
my $checksum = sha1(
exists $result->{$_}
? $result->{$_}{cont}
: $source->{$_},
);
join(':', $_, $checksum);
} @$_ ];
} @{ $deps // [] };
my %x;
$x{type} = $type;
$x{deps} = [ @$deps ] if @$deps;
$x{checksum} = sha1($content) if defined $content;
return serialize(%x);
}
# for use with run_fix_test() and runstate()
sub NO_RUNSTATE { 'aborted' }
sub UNCHANGED { 'wont_rebuild' }
sub WONT_OVERWR { 'wont_overwrite' }
sub SHELL_FAIL { 'shell_error' }
sub BUILD_FAIL { 'buildscript_error' }
sub NOT_FOUND { 'buildscript_not_found' }
sub KEPT_PREV { 'rebuilt_but_kept_previous' }
sub REPL_ERASED { 'rebuilt_replaced_deleted' }
sub NEW_CONTENT { 'rebuilt_new_content' }
sub SRC_NOT_FOUND { 'source_dep_not_found' }
sub SRC_REGIST { 'source_dep_registered' }
sub runstate {
my ($build_status, $abort_status, $abort_target) = @_;
my %x;
$x{ABORT} = $abort_target if defined($abort_status);
$x{build_status} = $build_status if defined($build_status);
return serialize(%x);
}
sub statsstate {
my (@run_target) = @_;
my %x;
$x{run_count} = scalar(@run_target) if @run_target;
$x{run_targets} = \@run_target if @run_target;
return serialize(%x);
}
sub catch {
my ($code) = @_;
my @result = eval {
local $SIG{__DIE__} = undef;
$code->();
};
return ($!, $@, @result);
}
sub shebang {
my $path = which(shift);
return "#!$path\n";
}
{
sub TRUE { 1 }
sub FALSE { 0 }
my %target_rewritten = (
NO_RUNSTATE ,=> FALSE, # unmodified targets, no runstate generated
UNCHANGED ,=> FALSE,
WONT_OVERWR ,=> FALSE,
SHELL_FAIL ,=> FALSE,
BUILD_FAIL ,=> FALSE,
KEPT_PREV ,=> FALSE,
SRC_REGIST ,=> FALSE,
REPL_ERASED ,=> TRUE,
NEW_CONTENT ,=> TRUE,
);
my @args;
END {
if (@args) {
note '-' x 60;
note "FAILED";
note " Dir: $ENV{PWD}";
note " Cmd: fix @args";
note '-' x 60;
}
}
sub run_fix_test {
my %arg = @_;
$arg{before} //= sub {};
$arg{after} //= sub {};
$arg{name} //= 'NONE';
die "run_fix_test() option 'name' must be string," if ref($arg{name});
die "run_fix_test() option 'exit' must be integer,"
if $arg{exit} !~ /^\d+$/;
die "run_fix_test() option 'before' must be coderef,"
if ref($arg{before}) ne 'CODE';
die "run_fix_test() option 'after' must be coderef,"
if ref($arg{after}) ne 'CODE';
my %result = %{ $arg{result} // {} };
my %source = %{ $arg{source} // {} };
my @stats = @{ $arg{stats} // [] };
@args = @{ $arg{args} // [] };
# write source files
foreach (key %source) {
next unless defined $source{$_};
my $is_buildscript = m#\.fix$#;
$source{$_} = shebang('dash') . $source{$_} if $is_buildscript;
write_exe_file($_ => $source{$_});
}
my @file = do {
my @tempfile = map { "$_--fixing" } keys %result;
delete_file @tempfile;
(keys %source, @tempfile, keys %result);
};
my %pre = fingerprints(@file);
$arg{before}(); # run 'before' hook
unshift(@args, '--stats'); # insert '--stats' option
unshift(@{ $stats[0] }, '--stats') if @stats;
my $exit = system("$fix @args 2> stderr.txt");
if (my $caught = $exit & 127) { # exit on Ctrl-C
my %signame; # (or any other signal)
use Config '%Config';
@signame{ split ' ', $Config{sig_num} }
= split ' ', $Config{sig_name};
warn " *** Killed by SIG" . $signame{ $caught } . "\n";
# Block around exit is to hide it from 'exit' detector thingy.
{ exit }
}
my $stderr = read_file('stderr.txt'); # check stderr output
delete_file('stderr.txt');
subtest $arg{name} => sub {
unlike($stderr, qr/Use of uninitialized value/,
"No Perl warning 'uninitialized value'");
is($exit >> 8, $arg{exit}, # check exit status
"Exit status");
if (defined $arg{errmsg}) { # check any error message
my $info = nl("Try '$name --help' for more information.");
is($stderr, $arg{errmsg} . $info, "Error message");
}
$arg{after}(); # run 'after' hook
my %post = fingerprints(@file);
# check statsfile
if (@stats == 0) {
ok(!-e $stats, "Should not exist: $stats");
} else {
ok( -e $stats, "Should exist: $stats");
my $gotten = read_file($stats);
my $expected = statsstate(@stats);
is($gotten, $expected, "Content: $stats");
}
# check sourcefiles
{
foreach (key %source) {
ok(! -f $_, "Should not exist: $_")
if not defined $source{$_};
}
my @source = grep { defined $source{$_} } key(%source);
ok( -f $_, "Should exist: $_" ) for @source;
is($pre{$_}, $post{$_}, "Should be unchanged: $_") for @source;
}
# check tempfiles
{
my @tempfile = (
key(%source),
grep { not defined $result{$_}{temp} } key(%result),
);
foreach (@tempfile) {
my $file = "$_--fixing";
ok(! -f $file, "Should not exist: $file");
}
@tempfile = grep { defined $result{$_}{temp} } key(%result);
foreach (@tempfile) {
my $file = "$_--fixing";
ok( -f $file, "Should exist: $file");
}
foreach (@tempfile) {
my $file = "$_--fixing";
isnt($pre{$file}, $post{$file}, "Tempfile updated: $file");
}
foreach (@tempfile) {
my $file = "$_--fixing";
my $gotten = read_file($file);
my $expected = $result{$_}{temp};
is($gotten, $expected, "Content: $file");
}
}
# check targets
{
my @target;
@target = grep { not defined $result{$_}{cont} } key(%result);
ok(!-f $_, "Should not exist: $_") for @target;
@target = grep { defined $result{$_}{cont} } key(%result);
ok( -f $_, "Should exist: $_" ) for @target;
foreach (@target) { # rewritten targets
my $state = $result{$_}{state};
isnt($pre{$_}, $post{$_}, "Should be updated: $_")
if $target_rewritten{$state} == TRUE;
}
foreach (@target) { # unmodified targets
my $state = $result{$_}{state};
is($pre{$_}, $post{$_}, "Should be unchanged: $_")
if $target_rewritten{$state} == FALSE;
}
foreach (@target) { # if modified, check content
is(read_file($_), $result{$_}{cont}, "Content: $_")
if $pre{$_} ne $post{$_};
}
}
# check runstate
my @runstate = grep { $result{$_}{state} ne NO_RUNSTATE } key(%result);
if (@runstate == 0) { # no targets generated
ok(!-e $run, "Should not exist: $run/");
} else { # targets were generated
ok( -e $run, "Should exist: $run/");
foreach (key %result) {
ok(!-f "$run/$_", "Should not exist: $run/$_")
if $result{$_}{state} eq NO_RUNSTATE;
}
foreach (@runstate) {
ok( -f "$run/$_", "Should exist: $run/$_");
}
foreach (@runstate) {
my $gotten = read_file("$run/$_");
my $expected = runstate(
$result{$_}{state},
($result{$_}{abort} ? (ABORT => $result{$_}{abort}) : ()),
);
is($gotten, $expected, "Content: $run/$_");
}
}
# check keepstate
my @keepstate = grep { not exists $result{$_}{abort} } key(%result);
if (@keepstate == 0) {
# Source files with defined content which are in the worktree.
my @source = grep {
defined($source{$_}) and not m#^\.\./#;
} key %source;
if (@source) {
ok( -e $keep, "Should exist: $keep/");
} else {
ok(!-e $keep, "Should not exist: $keep/");
}
} else {
ok( -e $keep, "Should exist: $keep/");
foreach (key %source) {
my $gotten = read_file("$keep/$_") // next;
my $expected = keepstate(SOURCE, $source{$_});
is($gotten, $expected, "Content: $keep/$_");
}
foreach (key %result) {
my $keepfile = "$keep/$_";
if (exists $result{$_}{abort}) {
is($pre{$_}, $post{$_}, "Should be unchanged: $_");
} else {
my $gotten = read_file($keepfile);
my $type = $result{$_}{type} // TARGET;
my $expected = keepstate($type,
$result{$_}{cont},
$result{$_}{deps},
\%source, \%result
);
is($gotten, $expected, "Content: $keepfile");
}
}
}
} and @args = ();
}
}
###############################################################################
## ##
## Initialization ##
## ##
###############################################################################
sub help {
$in_main = undef;
print <<EOF;
Usage: test-fix [ --continue | --help ]
Run the fix test suite.
Options:
-h, --help display this help and exit
-a, --all run all tests (don't abort on first failure)
EOF
{ exit }
}
use Getopt::Long qw(:config posix_default gnu_compat no_ignore_case permute);
my $die_level = 'never';
my $die_on_fail = 1;
GetOptions(
'all|a' => sub { $die_on_fail = 0 },
'help|h|?' => \&help,
);
die_on_fail if $die_on_fail;
# check if there is an 'exit' statement in this file
my $exit_statement_in_test_script = read_file(__FILE__) =~ /^\s*exit.*;/m;
###############################################################################
## ##
## White-Box Tests (Testing Functions in the Program) ##
## ##
###############################################################################
note
"======================================\n" .
" White-Box Tests (Internal Functions)\n" .
"======================================";
enter_dir("whitebox-tests");
subtest 'split_path()' => sub {
# FIXME: What *should* split_path('.') return?
my @test = (
[ qw( a/b/c a/b c ) ],
[ qw( a/b/c/ a/b c ) ],
[ qw( a/b/c/// a/b c ) ],
[ qw( a/b//c/ a/b c ) ],
[ qw( a//b/c a//b c ) ],
[ qw( /a/b/c /a/b c ) ],
[ qw( a . a ) ],
[ qw( /a / a ) ],
);
# We run the function twice, because it looks prettier to report basenames and
# dirnames separately in the output.
foreach my $test (@test) {
my ($path, $expect_dir, undef) = @$test;
my ($dir_result, undef) = Local::Modulino::split_path($path);
is ($dir_result, $expect_dir, "Dirname: $path");
}
foreach my $test (@test) {
my ($path, undef, $expect_file) = @$test;
my (undef, $file_result) = Local::Modulino::split_path($path);
is ($file_result, $expect_file, "Basename: $path");
}
};
subtest 'default_buildscripts()' => sub {
my %tests = (
'hej.a.b.c' => [
'default.a.b.c.fix',
'default.a.b.fix',
'default.a.fix',
'default.fix' ],
'a' => [
'default.fix' ],
);
for (key %tests) {
my $expect = $tests{$_};
is_deeply([ Local::Modulino::possible_buildscripts($_) ], $expect,
"Files: $_");
}
};
subtest 'Local::Paths::relpath()' => sub {
my @test = (
[qw( /x/y/z.txt / x/y/z.txt )],
[qw( /x/y/z.txt /x y/z.txt )],
[qw( /x/y/z.txt /x/y z.txt )],
[qw( /x/y/z.txt /x/y/a ../z.txt )],
[qw( /x/y/z.txt /x/y/a/b ../../z.txt )],
[qw( ../z.txt . ../z.txt )],
);
foreach (@test) {
my ($file, $dir, $result) = @$_;
my $got = Local::Paths::relpath($file, $dir);
is($got, $result, "$result");
}
};
subtest 'Local::Paths::clean()' => sub {
my @test = (
'./a' => 'a',
'../a' => '../a',
'../../a' => '../../a',
'.' => '.',
'./.' => '.',
'./..' => '..',
'./' => '.', # odd corner case
'/.' => '/', # odd corner case
'/' => '/',
'/a' => '/a',
'/a/..' => '/',
'/a/../..' => '/',
'/a/b/../..' => '/',
'a' => 'a',
'a/' => 'a',
'a/../..' => '..',
'a/../../..' => '../..',
'a/../b/c' => 'b/c',
'a/../../c' => '../c',
'a/./b' => 'a/b',
'a//b' => 'a/b',
'a/b' => 'a/b',
'a/b/../..' => '.',
'a/b/c/..' => 'a/b',
);
while (@test) {
my ($_, $expect) = splice(@test, 0, 2);
is(Local::Paths::clean($_), $expect, "Path: $_");
}
};
subtest "Local::Store, simple use" => sub {
my $test = new Local::Store(dir => 'storage');
my ($x, $y);
$x = eval { $test->get('file'); 1 };
is ($x, undef, "get() without fields should die");
like($@, qr/Missing arguments: No field names given/,
"get() without fields error message");
$x = $test->get('file', 'foo');
is ($x, undef, "get() on non-existing field");
$x = $test->set('file', foo => 'bar', apa => 'bepa');
ok ($x, "set() return status");
for ('storage/file') {
ok ( -f $_, "set() file existence: $_");
is (read_file($_), serialize(foo => 'bar', apa => 'bepa'),
"set() file content: $_");
}
($x, $y) = $test->get('file', 'foo', 'apa');
is ($x, 'bar', 'get() with two existing fields, 1st field');
is ($y, 'bepa', 'get() with two existing fields, 2nd field');
($x, $y) = $test->get('file', 'apa', 'foo');
is ($x, 'bepa', 'get() with two existing fields in opposite order, 1st field');
is ($y, 'bar', 'get() with two existing fields in opposite order, 2nd field');
my %expected = ( foo => 'bar', apa => 'bepa' );
foreach (qw/foo apa/) {
$x = $test->get('file', $_);
is ($x, $expected{$_}, "get() with one field in scalar context: $_");
}
};
subtest "read_config()" => sub {
my $file;
my $next = sub { $file = sprintf('cfg%02d', state $i ++) };
my $bad = "Neither '[section]' nor 'variable = value'";
my %config = (
$next->() => {
name => 'Invalid line',
cont => nl('@ invalid line'),
error => nl("$bad in line 1"),
},
# comments
$next->() => {
name => 'Two comment lines',
cont => nl('# hash comment', '; semicolor comment'),
return => {},
},
$next->() => {
name => "Comment after '[section]'",
cont => nl('[section]# hash comment',
'[section]; semicolor comment'),
return => {},
},
$next->() => {
name => "Valid section '[test]'",
cont => nl('[test]'),
return => {},
},
$next->() => {
name => "Comment after 'variable = value'",
cont => nl('[section] # hash comment',
'variable = value;semicolon comment'),
return => { section => { variable => 'value' }},
},
# section
$next->() => {
name => 'Missing section name in line 1',
cont => nl('variable = value'),
error => nl("No '[section]' found in line 1")
},
$next->() => {
name => 'Missing section name in line 2',
cont => nl('', 'variable = value'),
error => nl("No '[section]' found in line 2")
},
$next->() => {
name => 'Invalid section name',
cont => nl('[invalid_section_only]'),
error => nl("$bad in line 1"),
},
$next->() => {
name => 'Invalid section name',
cont => nl('[valid-section-only]'),
return => {},
},
$next->() => {
name => 'Invalid section with argument',
cont => nl('[section-with "value"]'),
error => nl("$bad in line 1"),
},
$next->() => {
name => 'Valid values in two sections',
cont => nl('[ section1 ]',
' variable = value1',
'[ section2 ]',
' variable = value2',
''),
return => { section1 => { variable => 'value1' },
section2 => { variable => 'value2' }},
},
# variable/value
$next->() => {
name => 'Invalid single quoted variable',
cont => nl('[section]', "'variable' = value"),
error => nl("$bad in line 2"),
},
$next->() => {
name => 'Invalid double quoted variable',
cont => nl('[section]', '"variable" = value'),
error => nl("$bad in line 2"),
},
$next->() => {
name => 'Valid variable without value',
cont => nl('[section]', 'variable'),
return => { section => { variable => '1' }},
},
$next->() => {
name => 'Valid unquoted value',
cont => nl('[section]', 'variable = value'),
return => { section => { variable => 'value' }},
},
$next->() => {
name => 'Valid unquoted value on section line',
cont => nl('[section]variable = value'),
return => { section => { variable => 'value' }},
},
$next->() => {
name => 'Ignored single quotes in value',
cont => nl('[section]',
"variable = 'value'"),
return => { section =>{ variable => "'value'" }},
},
$next->() => {
name => 'Valid quoted value',
cont => nl('[section]',
'variable = ";-#-\\\\-\\"-\\n-\\t-\\b"'),
return => { section =>{ variable => ";-#-\\-\"-\n-\t-\b" }},
},
$next->() => {
name => 'Valid mixed case variable name',
cont => nl('[section]',
'Variable = "value"'),
return => { section =>{ variable => "value" }},
},
$next->() => {
name => 'Valid unescaped multiple words in value',
cont => nl('[section]',
'variable = value value '),
return => { section =>{ variable => "value value" }},
},
$next->() => {
name => 'Valid unescaped multiple words with 2 spaces between',
cont => nl('[section]',
'variable = value value '),
return => { section =>{ variable => "value value" }},
},
);
my ($err, $msg, %return) = catch sub {
Local::Modulino::read_config('non-existing-file');
};
is($err, "No such file or directory", "Non-existing file: Exit status");
is($msg, "Cannot open config file 'non-existing-file' for reading: " .
"No such file or directory\n", "Non-existing file: Error message");
foreach my $file (key %config) {
my $name = $config{$file}{name};
write_file($file, $config{$file}{cont});
my ($err, $msg, %return) = catch sub {
Local::Modulino::read_config($file);
};
if (exists $config{$file}{error}) {
# Testing of $err in string context return wrong value on MacOS X.
cmp_ok($err, '==', 254, "$file: $name: Exit status");
is($msg, "Bad config '$file': $config{$file}{error}",
"$file: $name: Error message");
} else {
is($err, '', "$file: $name: Exit status");
is(Dumper(\%return), Dumper($config{$file}{return}),
"$file: $name: Return value");
}
}
};
# Abort all tests unless 'fix' can be executed
# FIXME: hide standard output/error
my $exit = system $fix, '--version';
isnt($exit, -1, q|Must be able to execute 'fix' script|);
BAIL_OUT q|Cannot start greybox testing: 'fix' script isn't executable!|
if $exit == -1;
###############################################################################
## ##
## Grey-Box Tests (Testing Build Results & State Storage Content) ##
## ##
###############################################################################
note
"================================================\n" .
" Grey-Box Tests (Build Results + State Storage)\n" .
"================================================";
note '=== Passing Bad Args ===';
enter_dir("greybox-passing-bad-args");
run_fix_test(
name => "No '.fixrc'",
exit => 254,
errmsg => nl("fix: Current dir not in a fix worktree",
"(Use 'touch .fixrc' where you want your worktree root.)"),
args => [qw( 1 )],
);
write_file('.fixrc' => '');
run_fix_test(
name => "Incorrect '.fix/store_version'",
exit => 254,
errmsg => nl("fix: State storage on disk has old format, full rebuild needed",
"(Erase '.fix' directory in worktree root and run again.)"),
args => [qw( 1 )],
before => sub { mkdir(".$name"); write_file('.fix/store_version', '') },
after => sub { rmtree(".$name") },
);
run_fix_test(
name => "No argument given",
exit => 254,
errmsg => nl("fix: No target specified"),
args => [qw()],
);
run_fix_test(
name => "Bad command line option",
exit => 254,
errmsg => nl("fix: Unknown option: '--BAD-OPTION'"),
args => [qw( --BAD-OPTION )],
);
run_fix_test(
name => "Two bad command line options",
exit => 254,
errmsg => nl("fix: Unknown option: '--BAD-OPTION'",
"fix: Unknown option: '--BAD-OPTION-2'"),
args => [qw( --BAD-OPTION --BAD-OPTION-2 )],
);
run_fix_test(
name => "Option '--source' on command line",
exit => 254,
errmsg => nl("fix: Option '--source' can only be used inside buildscript"),
args => [qw( --source NON-EXISTING-TARGET )],
);
# FIXME: Test output on standard error
run_fix_test(
name => "Non-existing buildscript",
exit => 254,
args => [qw( NON-EXISTING-TARGET )],
stats => [[qw( NON-EXISTING-TARGET )]],
source => {
'NON-EXISTING-TARGET.fix' => undef,
},
result => {
'NON-EXISTING-TARGET' => {
abort => 'NON-EXISTING-TARGET',
state => NOT_FOUND,
},
},
);
# FIXME: Test output on standard error
run_fix_test(
name => "Buildscript outside worktree",
exit => 254,
args => [qw( ../outside )],
stats => [[qw( ../outside )]],
source => {
'../outside.fix' => '',
},
result => {
'../outside' => {
# No file given in 'abort', since '../outside.txt'
# cannot be stored in keepstate.
abort => '',
state => NO_RUNSTATE,
},
},
);
# FIXME: Test output on standard error
run_fix_test(
name => "Buildscript with exit status = 1",
exit => 1,
args => [qw( 1 )],
stats => [[qw( 1 )]],
source => {
'1.fix' => nl('echo FIRST',
'exit 1',
'echo SECOND'),
},
result => {
'1' => {
state => BUILD_FAIL,
deps => [[ '1.fix' ]],
temp => nl('FIRST'),
},
},
);
# FIXME: Test output on standard error
run_fix_test(
name => "Buildscript with exit status = 2",
exit => 2,
args => [qw( 1 )],
stats => [[qw( 1 )]],
source => {
'1.fix' => nl('echo FIRST',
'exit 2',
'echo SECOND'),
},