aboutsummaryrefslogtreecommitdiff
path: root/challenge-085/abigail/test.pl
blob: 74cf691f6e55e35cb4726ae991fdfeb8715c2aae (plain)
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
#!/opt/perl/bin/perl

#
# Test the solutions. Either call it with the directory name you
# want to test in, or call it as "../test.pl" from within the directory.
#

use 5.032;

use strict;
use warnings;
no  warnings 'syntax';

chdir ".." if -f "../test.pl";

use experimental 'signatures';

use Test::More;
use DBI;


my %languages = (
    Perl        =>   {
        exe     =>   "/opt/perl/bin/perl",
        ext     =>   "pl",
    },
    JavaScript  =>   {
        exe     =>   "/usr/local/bin/node",
        ext     =>   "js",
        dir     =>   "node",
    },
    bc          =>   {
        exe     =>   "/usr/bin/bc",
        ext     =>   "bc",
        filter  =>   's/.*/main($&)/',
    },
    awk         =>   {
        exe     =>   "/usr/bin/awk",
        ext     =>   "awk",
        args    =>   ["-f"],
    },
    C           =>   {
        exe     =>   "/usr/bin/cc",
        ext     =>   "c",
        dir     =>   "c",
    },
    SQL         =>   {
        ext     =>   "sql",
    },
);

my $perl_exe = $languages {Perl} {exe};

foreach my $challenge (1, 2) {
    my ($dbh, $query, $tables_info);   # Only for SQL tests.

    my @inputs = <input-$challenge-*> or next;
    subtest "Challenge $challenge" => sub {
        foreach my $language (sort keys %languages) {
            my $info     =   $languages {$language};
            my $exe      =   $$info {exe};
            my $ext      =   $$info {ext};
            my $dir      =   $$info {dir}     // lc $language;
            my @args     = @{$$info {args}    // []};
            my $filter   =   $$info {filter}  // '';
            my $ext_out  =   $$info {ext_out} // "out";
            my $source   =  "$dir/ch-$challenge.$ext";
            my $compiled;
            next unless -r $source;

            #
            # C requires special handling. The source needs to be compiled.
            #
            if ($language eq "C") {
                $compiled = $source =~ s/\.$ext$/.$ext_out/r;
                system $exe, "-o", $compiled, $source;
            }

            #
            # SQL requires requires creating an in-memory database,
            # and loading some tables. For that, we need a .tables
            # file. We also read the actual query at this time.
            #
            if ($language eq "SQL") {
                my $tables = $source =~ s/\.\Q$ext\E$/.table/r;
                next unless -r $tables;
               ($dbh, $query, $tables_info) = init_sql ($source, $tables);
            }

            subtest $language => sub {
                foreach my $input (@inputs) {
                    my $output_exp = ($input =~ s/input/output/r) . ".exp";
                    my $exp        = `cat $output_exp`;

                    my $name = $input;
                    if ($exp =~ s/^\s*#\s*(.*)\n//) {
                        $name = $1;
                    }

                    my $got;
                    if ($compiled) {
                        $got = `$perl_exe -ple '$filter' $input | ./$compiled`;
                    }
                    elsif ($language eq "SQL") {
                        $got = test_sql ($dbh, $query, $tables_info, $input);
                    }
                    else {
                        $got = `$perl_exe -ple '$filter' $input |\
                                $exe @args ./$source`;
                    }

                    s/\h+$//gm for $exp, $got;
                    is $got, $exp, $name;
                }
            };

            unlink $compiled if $compiled;
        }
    }
}

done_testing;

#
# Parse the tables SQL, extract the table names, and the column names,
# *EXCLUDING* any primary key of the form "integer PRIMARY KEY"
# We're assuming some sane formatting (one column per line).
#
# Returns an array of arrays. Each (inner) array consists of a table
# name, followed by the name of the columns of that table.
#
# We will also create the database handle, use it to create the tables,
# and return the database handle as a second value.
#
sub init_sql ($query_file, $tables_file) {
    my $query  = `cat $query_file`;
    my $tables = `cat $tables_file`;

    my $in_table = 0;
    my @info;
    foreach (split /\n/ => $tables) {
        if (!$in_table) {
            if (/^\s* CREATE \s+ TABLE \s+ (\w+)/xi) {
                $in_table = 1;
                push @info => [$1];
            }
            next;
        }
        else {
            if (/^\s* \)/x) {
                $in_table = 0;
                next;
            }
            # Any other line is a column definition
            next if /^ \s* \w+ \s+ integer \s+ PRIMARY \s+ KEY \s*,/xi;
            if (/^ \s* (\w+)/x) {
                push @{$info [-1]} => $1;
            }
        }
    }

    my $dbh = DBI:: -> connect ("dbi:SQLite:dbname=:memory:", "", "",
                                {RaiseError   =>  1,
                                 PrintError   =>  1,
                                 AutoCommit   =>  1});
    $dbh -> do ($tables);

    return ($dbh, $query, \@info);
}


sub test_sql ($dbh, $query, $tables_info, $input) {
    #
    # For now, assume we each set of N lines, where N is the number of tables
    # is a test. We also assume that if a line has P items (space separated),
    # and the corresponing table has Q columns (not counting any integer primary
    # keys, as SQLite fills them automatically), we have to fill int (P/Q) rows.
    #

    #
    # Read the input
    #
    open my $i_fh, "<", $input or die "Failed to open $input: $!";
    my @input = <$i_fh>;

    my $output = "";

  TEST:
    while (@input >= @$tables_info) {
        foreach my $table_info (@$tables_info) {
            my ($table, @fields) = @$table_info;
            my $input            = shift @input;
            my @values           = split ' ' => $input;
            last TEST if @values < @fields;
            #
            # Clear the table
            #
            $dbh -> do ("DELETE FROM $table");

            #
            # Construct an input query
            #
            my $place  = "(" . join (", " => ("?") x @fields) . ")";
            my $insert = do {local $" = ", "; <<~ "--"};
                INSERT
                  INTO  $table
                       (@fields)
                VALUES  @{[($place) x (@values / @fields)]}
            --

            $dbh -> do ($insert, undef, @values);

            #
            # Run the query. If we have multiple results, join columns
            # by spaces, and rows by newlines.
            #
            my $result = $dbh -> selectall_arrayref ($query);

            $output .= join "\n" => map {join " " => @$_} @$result;
            $output .= "\n";
        }
    }

    $output;
}




__END__