Debian Codegraph @

t/lib/CmarkTest.pm

raw
1 # A package to execute the cmark test suite (and those of the specs derived from
2 # it).
3 # There is a fast version that we execute ourselves based on a JSON file with
4 # all the tests and there is the full version using the cmark test tool but
5 # which is much slower (and has a more aggressive HTML normalization that
6 # actually hides some bugs).
7
8 package CmarkTest;
9
10 use strict;
11 use warnings;
12 use utf8;
13 use feature ':5.24';
14
15 use Exporter 'import';
16 use HtmlSanitizer;
17 use JSON 'from_json';
18 use Markdown::Perl;
19 use Test2::V0;
20
21 our @EXPORT = qw(test_suite);
22
23 sub json_test {
24 my ($pmarkdown, %opt) = @_;
25 my $test_data;
26 {
27 local $/ = undef;
28 open my $f, '<:encoding(utf-8)', $opt{json_file};
29 my $json_data = <$f>;
30 close $f;
31 $test_data = from_json($json_data);
32 }
33 my %todo = map { $_ => 1 } @{$opt{todo} // []};
34 my %bugs = map { $_ => 1 } @{$opt{bugs} // []};
35 my $i = 0;
36 for my $t (@{$test_data}) {
37 $i++;
38 next if exists $opt{test_num} && $opt{test_num} != $i;
39
40 my $out = $pmarkdown->convert($t->{markdown});
41 my $val = sanitize_html($out);
42 my $expected = sanitize_html($t->{html});
43
44 my $title = sprintf "%s (%d)", $t->{section}, $t->{example};
45 my @diag;
46 push @diag, sprintf $opt{test_url}, $t->{example} if exists $opt{test_url};
47 push @diag, 'Input markdown:', $t->{markdown}, "\n";
48
49 my $test = sub { is($val, $expected, $title, @diag) };
50
51 if ($todo{$i}) {
52 todo 'Not yet supported' => $test;
53 } elsif ($bugs{$i}) {
54 todo 'The spec is buggy' => $test;
55 } else {
56 $test->();
57 }
58 }
59 }
60
61 sub full_test {
62 my (%opt) = @_;
63
64 skip_all('Python3 must be installed.') if system 'python3 -c "exit()" 2>/dev/null';
65
66 skip_all('commonmark-spec must be checked out.') unless -e $opt{spec_tool};
67 skip_all("The $opt{spec_name} test suite must be checked out.") unless -e $opt{spec};
68
69 my $root_dir = "${FindBin::Bin}/..";
70
71 my $mode;
72 if (exists $opt{test_num}) {
73 $mode = "-n ".$opt{test_num};
74 } else {
75 $mode = "--track ${root_dir}/commonmark.$opt{mode}.tests";
76 }
77
78 my $test_suite_output = system "python3 $opt{spec_tool} --spec $opt{spec} ${mode} --program '$^X -I${root_dir}/lib ${root_dir}/script/pmarkdown -m $opt{mode} -o warn_for_unused_input=0'";
79 is($test_suite_output, 0, "$opt{spec_name} test suite");
80 }
81
82 sub test_suite {
83 my (%opt) = @_;
84
85 if ($opt{use_full_spec}) {
86 full_test(%opt);
87 } else {
88 my $pmarkdown = Markdown::Perl->new(mode => $opt{mode}, warn_for_unused_input => 0);
89 json_test($pmarkdown, %opt);
90 }
91 }