Skip to content

Commit 8abd20f

Browse files
author
Branislav Zahradník
committed
[tests] New assert function assume with test message first
* Motivation Introduce single assert function which can: - use emulated named arguments - evaluate code to build "got" value - detect eval success/failure - detect expected eval success/failure `assume` function enforces most important part of test case, assumed behaviour description (test message), first.
1 parent 1bf4f3b commit 8abd20f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

t/test.pl

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@
4141
our $NO_ENDING = 0;
4242
our $Tests_Are_Passing = 1;
4343

44+
sub diag;
45+
sub fail;
46+
sub is;
47+
sub like;
48+
4449
# Use this instead of print to avoid interference while testing globals.
4550
sub _print {
4651
local($\, $", $,) = (undef, ' ', '');
@@ -52,6 +57,68 @@ sub _print_stderr {
5257
print STDERR @_;
5358
}
5459

60+
sub assume {
61+
my ($message, %args) = @_;
62+
63+
# Single assert function which:
64+
# - detects whether code should successed or faile
65+
# - detect comparison method: `is` / `like`
66+
67+
# Accept named arguments:
68+
#
69+
# eval => code
70+
# - code to evaluate
71+
# - code is evaluated with known and initialized variable: `my $result = q ()`
72+
#
73+
# expect => string / regex
74+
# - when specified it expects evaluated code to not fail and validates result
75+
# - when not specified it just expect evaluated to not fail
76+
# - accepts string (acting as `is`) or regex (acting as `like`)
77+
#
78+
# throws => string / regex
79+
# - when specified it expects evaluated code to fail and validates failure ($@)
80+
# - accepts string (acting as `is`) or regex (acting as `like`)
81+
82+
my $got;
83+
my $lives = eval qq {
84+
do {
85+
use strict;
86+
use warnings;
87+
my \$result = q ();
88+
\$got = do { $args{eval}; };
89+
};
90+
1;
91+
};
92+
my $error = $@;
93+
94+
if (exists $args{throws}) {
95+
if ($lives) {
96+
my $rv = fail $message;
97+
diag q (Expected to fail but it lives);
98+
return $rv;
99+
}
100+
101+
return ref $args{throws}
102+
? like $@, $args{throws}, $message
103+
: is $@, $args{throws}, $message
104+
;
105+
}
106+
107+
unless ($lives) {
108+
my $rv = fail $message;
109+
110+
diag q (Expected to live but it died:);
111+
diag $error =~ s (^) ( )rmg;
112+
113+
return $rv;
114+
}
115+
116+
return ref $args{expect}
117+
? like $got, $args{expect}, $message
118+
: is $got, $args{expect}, $message
119+
;
120+
}
121+
55122
sub plan {
56123
my $n;
57124
if (@_ == 1) {

0 commit comments

Comments
 (0)