Bug 23624: (QA follow-up) Test error cases
[koha.git] / t / db_dependent / Reports / Guided.t
blobe0aacfd29ebbc12c0da4c1155bdaf8d9cfe29418
1 # Copyright 2012 Catalyst IT Ltd.
2 # Copyright 2015 Koha Development team
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19 use Modern::Perl;
21 use Test::More tests => 11;
22 use Test::Warn;
24 use t::lib::TestBuilder;
25 use C4::Context;
26 use Koha::Database;
27 use Koha::Items;
28 use Koha::Reports;
29 use Koha::Notice::Messages;
31 use_ok('C4::Reports::Guided');
32 can_ok(
33     'C4::Reports::Guided',
34     qw(save_report delete_report execute_query)
37 my $schema = Koha::Database->new->schema;
38 $schema->storage->txn_begin;
39 my $builder = t::lib::TestBuilder->new;
41 subtest 'strip_limit' => sub {
42     # This is the query I found that triggered bug 8594.
43     my $sql = "SELECT aqorders.ordernumber, biblio.title, biblio.biblionumber, items.homebranch,
44         aqorders.entrydate, aqorders.datereceived,
45         (SELECT DATE(datetime) FROM statistics
46             WHERE itemnumber=items.itemnumber AND
47                 (type='return' OR type='issue') LIMIT 1)
48         AS shelvedate,
49         DATEDIFF(COALESCE(
50             (SELECT DATE(datetime) FROM statistics
51                 WHERE itemnumber=items.itemnumber AND
52                 (type='return' OR type='issue') LIMIT 1),
53         aqorders.datereceived), aqorders.entrydate) AS totaldays
54     FROM aqorders
55     LEFT JOIN biblio USING (biblionumber)
56     LEFT JOIN items ON (items.biblionumber = biblio.biblionumber
57         AND dateaccessioned=aqorders.datereceived)
58     WHERE (entrydate >= '2011-01-01' AND (datereceived < '2011-02-01' OR datereceived IS NULL))
59         AND items.homebranch LIKE 'INFO'
60     ORDER BY title";
62     my ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($sql);
63     is($res_sql, $sql, "Not breaking subqueries");
64     is($res_lim1, 0, "Returns correct default offset");
65     is($res_lim2, undef, "Returns correct default LIMIT");
67     # Now the same thing, but we want it to remove the LIMIT from the end
69     my $test_sql = $res_sql . " LIMIT 242";
70     ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql);
71     # The replacement drops a ' ' where the limit was
72     is(trim($res_sql), $sql, "Correctly removes only final LIMIT");
73     is($res_lim1, 0, "Returns correct default offset");
74     is($res_lim2, 242, "Returns correct extracted LIMIT");
76     $test_sql = $res_sql . " LIMIT 13,242";
77     ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql);
78     # The replacement drops a ' ' where the limit was
79     is(trim($res_sql), $sql, "Correctly removes only final LIMIT (with offset)");
80     is($res_lim1, 13, "Returns correct extracted offset");
81     is($res_lim2, 242, "Returns correct extracted LIMIT");
83     # After here is the simpler case, where there isn't a WHERE clause to worry
84     # about.
86     # First case with nothing to change
87     $sql = "SELECT * FROM items";
88     ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($sql);
89     is($res_sql, $sql, "Not breaking simple queries");
90     is($res_lim1, 0, "Returns correct default offset");
91     is($res_lim2, undef, "Returns correct default LIMIT");
93     $test_sql = $sql . " LIMIT 242";
94     ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql);
95     is(trim($res_sql), $sql, "Correctly removes LIMIT in simple case");
96     is($res_lim1, 0, "Returns correct default offset");
97     is($res_lim2, 242, "Returns correct extracted LIMIT");
99     $test_sql = $sql . " LIMIT 13,242";
100     ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql);
101     is(trim($res_sql), $sql, "Correctly removes LIMIT in simple case (with offset)");
102     is($res_lim1, 13, "Returns correct extracted offset");
103     is($res_lim2, 242, "Returns correct extracted LIMIT");
106 $_->delete for Koha::AuthorisedValues->search({ category => 'XXX' });
107 Koha::AuthorisedValue->new({category => 'LOC'})->store;
109 subtest 'GetReservedAuthorisedValues' => sub {
110     plan tests => 1;
111     # This one will catch new reserved words not added
112     # to GetReservedAuthorisedValues
113     my %test_authval = (
114         'date' => 1,
115         'branches' => 1,
116         'itemtypes' => 1,
117         'cn_source' => 1,
118         'categorycode' => 1,
119         'biblio_framework' => 1,
120     );
122     my $reserved_authorised_values = GetReservedAuthorisedValues();
123     is_deeply(\%test_authval, $reserved_authorised_values,
124                 'GetReservedAuthorisedValues returns a fixed list');
127 subtest 'IsAuthorisedValueValid' => sub {
128     plan tests => 8;
129     ok( IsAuthorisedValueValid('LOC'),
130         'User defined authorised value category is valid');
132     ok( ! IsAuthorisedValueValid('XXX'),
133         'Not defined authorised value category is invalid');
135     # Loop through the reserved authorised values
136     foreach my $authorised_value ( keys %{GetReservedAuthorisedValues()} ) {
137         ok( IsAuthorisedValueValid($authorised_value),
138             '\''.$authorised_value.'\' is a reserved word, and thus a valid authorised value');
139     }
142 subtest 'GetParametersFromSQL+ValidateSQLParameters' => sub  {
143     plan tests => 3;
144     my $test_query_1 = "
145         SELECT date_due
146         FROM old_issues
147         WHERE YEAR(timestamp) = <<Year|custom_list>> AND
148               branchcode = <<Branch|branches>> AND
149               borrowernumber = <<Borrower>>
150     ";
152     my @test_parameters_with_custom_list = (
153         { 'name' => 'Year', 'authval' => 'custom_list' },
154         { 'name' => 'Branch', 'authval' => 'branches' },
155         { 'name' => 'Borrower', 'authval' => undef }
156     );
158     is_deeply( GetParametersFromSQL($test_query_1), \@test_parameters_with_custom_list,
159         'SQL params are correctly parsed');
161     my @problematic_parameters = ();
162     push @problematic_parameters, { 'name' => 'Year', 'authval' => 'custom_list' };
163     is_deeply( ValidateSQLParameters( $test_query_1 ),
164                \@problematic_parameters,
165                '\'custom_list\' not a valid category' );
167     my $test_query_2 = "
168         SELECT date_due
169         FROM old_issues
170         WHERE YEAR(timestamp) = <<Year|date>> AND
171               branchcode = <<Branch|branches>> AND
172               borrowernumber = <<Borrower|LOC>>
173     ";
175     is_deeply( ValidateSQLParameters( $test_query_2 ),
176         [],
177         'All parameters valid, empty problematic authvals list'
178     );
181 subtest 'get_saved_reports' => sub {
182     plan tests => 16;
183     my $dbh = C4::Context->dbh;
184     $dbh->do(q|DELETE FROM saved_sql|);
185     $dbh->do(q|DELETE FROM saved_reports|);
187     #Test save_report
188     my $count = scalar @{ get_saved_reports() };
189     is( $count, 0, "There is no report" );
191     my @report_ids;
192     foreach my $ii ( 1..3 ) {
193         my $id = $builder->build({ source => 'Borrower' })->{ borrowernumber };
194         push @report_ids, save_report({
195             borrowernumber => $id,
196             sql            => "SQL$id",
197             name           => "Name$id",
198             area           => "area$ii", # ii vs id area is varchar(6)
199             group          => "group$id",
200             subgroup       => "subgroup$id",
201             type           => "type$id",
202             notes          => "note$id",
203             cache_expiry   => undef,
204             public         => 0,
205         });
206         $count++;
207     }
208     like( $report_ids[0], '/^\d+$/', "Save_report returns an id for first" );
209     like( $report_ids[1], '/^\d+$/', "Save_report returns an id for second" );
210     like( $report_ids[2], '/^\d+$/', "Save_report returns an id for third" );
212     is( scalar @{ get_saved_reports() },
213         $count, "$count reports have been added" );
215     ok( 0 < scalar @{ get_saved_reports( $report_ids[0] ) }, "filter takes report id" );
217     #Test delete_report
218     is (delete_report(),undef, "Without id delete_report returns undef");
220     is( delete_report( $report_ids[0] ), 1, "report 1 is deleted" );
221     $count--;
223     is( scalar @{ get_saved_reports() }, $count, "Report1 has been deleted" );
225     is( delete_report( $report_ids[1], $report_ids[2] ), 2, "report 2 and 3 are deleted" );
226     $count -= 2;
228     is( scalar @{ get_saved_reports() },
229         $count, "Report2 and report3 have been deleted" );
231     my $sth = execute_query('SELECT COUNT(*) FROM systempreferences', 0, 10);
232     my $results = $sth->fetchall_arrayref;
233     is(scalar @$results, 1, 'running a query returned a result');
235     my $version = C4::Context->preference('Version');
236     $sth = execute_query(
237         'SELECT value FROM systempreferences WHERE variable = ?',
238         0,
239         10,
240         [ 'Version' ],
241     );
242     $results = $sth->fetchall_arrayref;
243     is_deeply(
244         $results,
245         [ [ $version ] ],
246         'running a query with a parameter returned the expected result'
247     );
249     # for next test, we want to let execute_query capture any SQL errors
250     $dbh->{RaiseError} = 0;
251     my $errors;
252     warning_like { ($sth, $errors) = execute_query(
253             'SELECT surname FRM borrowers',  # error in the query is intentional
254             0, 10 ) }
255             qr/^DBD::mysql::st execute failed: You have an error in your SQL syntax;/,
256             "Wrong SQL syntax raises warning";
257     ok(
258         defined($errors) && exists($errors->{queryerr}),
259         'attempting to run a report with an SQL syntax error returns error message (Bug 12214)'
260     );
262     is_deeply( get_report_areas(), [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ],
263         "get_report_areas returns the correct array of report areas");
266 subtest 'Ensure last_run is populated' => sub {
267     plan tests => 3;
269     my $rs = Koha::Database->new()->schema()->resultset('SavedSql');
271     my $report = $rs->new(
272         {
273             report_name => 'Test Report',
274             savedsql    => 'SELECT * FROM branches',
275             notes       => undef,
276         }
277     )->insert();
279     is( $report->last_run, undef, 'Newly created report has null last_run ' );
281     execute_query( $report->savedsql, undef, undef, undef, $report->id );
282     $report->discard_changes();
284     isnt( $report->last_run, undef, 'First run of report populates last_run' );
286     my $previous_last_run = $report->last_run;
287     sleep(1); # last_run is stored to the second, so we need to ensure at least one second has passed between runs
288     execute_query( $report->savedsql, undef, undef, undef, $report->id );
289     $report->discard_changes();
291     isnt( $report->last_run, $previous_last_run, 'Second run of report updates last_run' );
294 subtest 'convert_sql' => sub {
295     plan tests => 4;
297     my $sql = q|
298     SELECT biblionumber, ExtractValue(marcxml,
299 'count(//datafield[@tag="505"])') AS count505
300     FROM biblioitems
301     HAVING count505 > 1|;
302     my $expected_converted_sql = q|
303     SELECT biblionumber, ExtractValue(metadata,
304 'count(//datafield[@tag="505"])') AS count505
305     FROM biblio_metadata
306     HAVING count505 > 1|;
308     is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Simple query should have been correctly converted");
310     $sql = q|
311     SELECT biblionumber, substring(
312 ExtractValue(marcxml,'//controlfield[@tag="008"]'), 8,4 ) AS 'PUB DATE',
313 title
314     FROM biblioitems
315     INNER JOIN biblio USING (biblionumber)
316     WHERE biblionumber = 14|;
318     $expected_converted_sql = q|
319     SELECT biblionumber, substring(
320 ExtractValue(metadata,'//controlfield[@tag="008"]'), 8,4 ) AS 'PUB DATE',
321 title
322     FROM biblio_metadata
323     INNER JOIN biblio USING (biblionumber)
324     WHERE biblionumber = 14|;
325     is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with biblio info should have been correctly converted");
327     $sql = q|
328     SELECT concat(b.title, ' ', ExtractValue(m.marcxml,
329 '//datafield[@tag="245"]/subfield[@code="b"]')) AS title, b.author,
330 count(h.reservedate) AS 'holds'
331     FROM biblio b
332     LEFT JOIN biblioitems m USING (biblionumber)
333     LEFT JOIN reserves h ON (b.biblionumber=h.biblionumber)
334     GROUP BY b.biblionumber
335     HAVING count(h.reservedate) >= 42|;
337     $expected_converted_sql = q|
338     SELECT concat(b.title, ' ', ExtractValue(m.metadata,
339 '//datafield[@tag="245"]/subfield[@code="b"]')) AS title, b.author,
340 count(h.reservedate) AS 'holds'
341     FROM biblio b
342     LEFT JOIN biblio_metadata m USING (biblionumber)
343     LEFT JOIN reserves h ON (b.biblionumber=h.biblionumber)
344     GROUP BY b.biblionumber
345     HAVING count(h.reservedate) >= 42|;
346     is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with 2 joins should have been correctly converted");
348     $sql = q|
349     SELECT t1.marcxml AS first, t2.marcxml AS second,
350     FROM biblioitems t1
351     LEFT JOIN biblioitems t2 USING ( biblionumber )|;
353     $expected_converted_sql = q|
354     SELECT t1.metadata AS first, t2.metadata AS second,
355     FROM biblio_metadata t1
356     LEFT JOIN biblio_metadata t2 USING ( biblionumber )|;
357     is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with multiple instances of marcxml and biblioitems should have them all replaced");
360 subtest 'Email report test' => sub {
362     plan tests => 8;
364     my $id1 = $builder->build({ source => 'Borrower',value => { surname => 'mailer', email => 'a@b.com' } })->{ borrowernumber };
365     my $id2 = $builder->build({ source => 'Borrower',value => { surname => 'nomailer', email => undef } })->{ borrowernumber };
366     my $report1 = $builder->build({ source => 'SavedSql', value => { savedsql => "SELECT surname,borrowernumber,email FROM borrowers WHERE borrowernumber IN ($id1,$id2)" } })->{ id };
367     my $report2 = $builder->build({ source => 'SavedSql', value => { savedsql => "SELECT potato FROM mashed" } })->{ id };
369     my $letter1 = $builder->build({
370             source => 'Letter',
371             value => {
372                 content => "[% surname %]",
373                 branchcode => "",
374                 message_transport_type => 'email'
375             }
376         });
377     my $letter2 = $builder->build({
378             source => 'Letter',
379             value => {
380                 content => "[% firstname %]",
381                 branchcode => "",
382                 message_transport_type => 'email'
383             }
384         });
386     my $message_count = Koha::Notice::Messages->search({})->count;
388     my ( $emails, $errors ) = C4::Reports::Guided::EmailReport();
389     is( $errors->[0]{FATAL}, 'MISSING_PARAMS', "Need to enter required params");
391     ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module}, code => $letter2->{code}});
392     is( $errors->[0]{FATAL}, 'NO_LETTER', "Must have a letter that exists");
394     warning_like { ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report2, module => $letter1->{module} , code => $letter1->{code} }) }
395         qr/^DBD::mysql::st execute failed/,
396         'Error from bad report';
397     is( $errors->[0]{FATAL}, 'REPORT_FAIL', "Bad report returns failure");
399     ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code} });
400     is( $errors->[0]{NO_FROM_COL} == 1 && $errors->[1]{NO_EMAIL_COL} == 2  && $errors->[2]{NO_FROM_COL} == 2, 1, "Correct warnings from the routine");
402     ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code}, from => 'the@future.ooh' });
403     is( $errors->[0]{NO_EMAIL_COL}, 2, "Warning only for patron with no email");
405     is( $message_count,  Koha::Notice::Messages->search({})->count, "Messages not added without commit");
407     ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code}, from => 'the@future.ooh' });
408     is( $emails->[0]{letter}->{content}, "mailer", "Message has expected content");
412 $schema->storage->txn_rollback;
414 subtest 'nb_rows() tests' => sub {
416     plan tests => 3;
418     $schema->storage->txn_begin;
420     my $items_count = Koha::Items->search->count;
421     $builder->build_object({ class => 'Koha::Items' });
422     $builder->build_object({ class => 'Koha::Items' });
423     $items_count += 2;
425     my $query = q{
426         SELECT * FROM items xxx
427     };
429     my $nb_rows = nb_rows( $query );
431     is( $nb_rows, $items_count, 'nb_rows returns the right value' );
433     my $bad_query = q{
434         SELECT * items xxx
435     };
437     warning_like
438         { $nb_rows = nb_rows( $bad_query ) }
439         qr/^DBD::mysql::st execute failed:/,
440         'Bad queries raise a warning';
442     is( $nb_rows, 0, 'nb_rows returns 0 on bad queries' );
444     $schema->storage->txn_rollback;
447 sub trim {
448     my ($s) = @_;
449     $s =~ s/^\s*(.*?)\s*$/$1/s;
450     return $s;