Bug 9021 [QA Followup] - Unit tests
[koha.git] / t / db_dependent / Search.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use utf8;
21
22 use YAML;
23
24 use C4::Debug;
25 require C4::Context;
26
27 # work around spurious wide character warnings
28 use open ':std', ':encoding(utf8)';
29
30 use Test::More tests => 4;
31 use Test::MockModule;
32 use MARC::Record;
33 use File::Spec;
34 use File::Basename;
35 use File::Find;
36 use Test::Warn;
37 use File::Temp qw/ tempdir /;
38 use File::Path;
39
40 our $child;
41 our $datadir;
42
43 sub index_sample_records_and_launch_zebra {
44     my ($datadir, $indexing_mode, $marc_type) = @_;
45
46     my $sourcedir = dirname(__FILE__) . "/data";
47     unlink("$datadir/zebra.log");
48     if (-f "$sourcedir/${marc_type}/zebraexport/biblio/exported_records") {
49         my $zebra_bib_cfg = ($indexing_mode eq 'dom') ? 'zebra-biblios-dom.cfg' : 'zebra-biblios.cfg';
50         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal,warn  -g iso2709 -d biblios init");
51         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal,warn   -g iso2709 -d biblios update $sourcedir/${marc_type}/zebraexport/biblio");
52         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal,warn  -g iso2709 -d biblios commit");
53     }
54     # ... and add large bib records, if present
55     if (-f "$sourcedir/${marc_type}/zebraexport/large_biblio_${indexing_mode}/exported_records.xml") {
56         my $zebra_bib_cfg = ($indexing_mode eq 'dom') ? 'zebra-biblios-dom.cfg' : 'zebra-biblios.cfg';
57         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal,warn   -g marcxml -d biblios update $sourcedir/${marc_type}/zebraexport/large_biblio_${indexing_mode}");
58         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal,warn  -g marcxml -d biblios commit");
59     }
60     if (-f "$sourcedir/${marc_type}/zebraexport/authority/exported_records") {
61         my $zebra_auth_cfg = ($indexing_mode eq 'dom') ? 'zebra-authorities-dom.cfg' : 'zebra-authorities.cfg';
62         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal,warn  -g iso2709 -d authorities init");
63         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal,warn   -g iso2709 -d authorities update $sourcedir/${marc_type}/zebraexport/authority");
64         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal,warn  -g iso2709 -d authorities commit");
65     }
66
67     $child = fork();
68     if ($child == 0) {
69         exec("zebrasrv -f $datadir/etc/koha-conf.xml -v none,request -l $datadir/zebra.log");
70         exit;
71     }
72
73     sleep(1);
74 }
75
76 sub cleanup {
77     if ($child) {
78         kill 9, $child;
79
80         # Clean up the Zebra files since the child process was just shot
81         rmtree $datadir;
82     }
83 }
84
85 # Fall back to make sure that the Zebra process
86 # and files get cleaned up
87 END {
88     cleanup();
89 }
90
91 our $QueryStemming = 0;
92 our $QueryAutoTruncate = 0;
93 our $QueryWeightFields = 0;
94 our $QueryFuzzy = 0;
95 our $UseQueryParser = 0;
96 our $marcflavour = 'MARC21';
97 our $contextmodule = new Test::MockModule('C4::Context');
98 $contextmodule->mock('preference', sub {
99     my ($self, $pref) = @_;
100     if ($pref eq 'marcflavour') {
101         return $marcflavour;
102     } elsif ($pref eq 'QueryStemming') {
103         return $QueryStemming;
104     } elsif ($pref eq 'QueryAutoTruncate') {
105         return $QueryAutoTruncate;
106     } elsif ($pref eq 'QueryWeightFields') {
107         return $QueryWeightFields;
108     } elsif ($pref eq 'QueryFuzzy') {
109         return $QueryFuzzy;
110     } elsif ($pref eq 'UseQueryParser') {
111         return $UseQueryParser;
112     } elsif ($pref eq 'maxRecordsForFacets') {
113         return 20;
114     } elsif ($pref eq 'FacetLabelTruncationLength') {
115         return 20;
116     } elsif ($pref eq 'FacetMaxCount') {
117         return 20;
118     } elsif ($pref eq 'OpacHiddenItems') {
119         return '';
120     } elsif ($pref eq 'opacthemes') {
121         return 'bootstrap';
122     } elsif ($pref eq 'opaclanguages') {
123         return 'en';
124     } elsif ($pref eq 'AlternateHoldingsField') {
125         return '490av';
126     } elsif ($pref eq 'AuthoritySeparator') {
127         return '--';
128     } elsif ($pref eq 'DisplayLibraryFacets') {
129         return 'holding';
130     } elsif ($pref eq 'UNIMARCAuthorsFacetsSeparator') {
131         return '--';
132     } else {
133         warn "The syspref $pref was requested but I don't know what to say; this indicates that the test requires updating"
134             unless $pref =~ m/(XSLT|item|branch|holding|image)/i;
135         return 0;
136     }
137 });
138 $contextmodule->mock('queryparser', sub {
139     my $QParser     = Koha::QueryParser::Driver::PQF->new();
140     $QParser->load_config("$datadir/etc/searchengine/queryparser.yaml");
141     return $QParser;
142 });
143
144 sub mock_marcfromkohafield {
145     my $marc_type = shift;
146     if ($marc_type eq 'marc21') {
147         $contextmodule->mock('marcfromkohafield', sub {
148             return {
149                 '' => {
150                     'biblio.biblionumber' => [ '999', 'c' ],
151                     'items.barcode' => ['952', 'p' ],
152                     'items.booksellerid' => ['952', 'e' ],
153                     'items.ccode' => ['952', '8' ],
154                     'items.cn_sort' => ['952', '6' ],
155                     'items.cn_source' => ['952', '2' ],
156                     'items.coded_location_qualifier' => ['952', 'f' ],
157                     'items.copynumber' => ['952', 't' ],
158                     'items.damaged' => ['952', '4' ],
159                     'items.dateaccessioned' => ['952', 'd' ],
160                     'items.datelastborrowed' => ['952', 's' ],
161                     'items.datelastseen' => ['952', 'r' ],
162                     'items.enumchron' => ['952', 'h' ],
163                     'items.holdingbranch' => ['952', 'b' ],
164                     'items.homebranch' => ['952', 'a' ],
165                     'items.issues' => ['952', 'l' ],
166                     'items.itemcallnumber' => ['952', 'o' ],
167                     'items.itemlost' => ['952', '1' ],
168                     'items.itemnotes' => ['952', 'z' ],
169                     'items.itemnumber' => ['952', '9' ],
170                     'items.itype' => ['952', 'y' ],
171                     'items.location' => ['952', 'c' ],
172                     'items.materials' => ['952', '3' ],
173                     'items.nonpublicnote' => ['952', 'x' ],
174                     'items.notforloan' => ['952', '7' ],
175                     'items.onloan' => ['952', 'q' ],
176                     'items.price' => ['952', 'g' ],
177                     'items.renewals' => ['952', 'm' ],
178                     'items.replacementprice' => ['952', 'v' ],
179                     'items.replacementpricedate' => ['952', 'w' ],
180                     'items.reserves' => ['952', 'n' ],
181                     'items.restricted' => ['952', '5' ],
182                     'items.stack' => ['952', 'j' ],
183                     'items.uri' => ['952', 'u' ],
184                     'items.withdrawn' => ['952', '0' ]
185                     }
186                 };
187         });
188     }
189 }
190
191 sub run_marc21_search_tests {
192     my $indexing_mode = shift;
193     $datadir = tempdir();
194     system(dirname(__FILE__) . "/zebra_config.pl $datadir marc21 $indexing_mode");
195
196     mock_marcfromkohafield('marc21');
197     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
198     $context->set_context();
199
200     is($context->config('zebra_bib_index_mode'),$indexing_mode,
201         "zebra_bib_index_mode is properly set to '$indexing_mode' in the created koha-conf.xml file (BZ11499)");
202     is($context->config('zebra_auth_index_mode'),$indexing_mode,
203         "zebra_auth_index_mode is properly set to '$indexing_mode' in the created koha-conf.xml file (BZ11499)");
204
205     use_ok('C4::Search');
206
207     # set search syspreferences to a known starting point
208     $QueryStemming = 0;
209     $QueryAutoTruncate = 0;
210     $QueryWeightFields = 0;
211     $QueryFuzzy = 0;
212     $UseQueryParser = 0;
213     $marcflavour = 'MARC21';
214
215     my $indexes = C4::Search::getIndexes();
216     is(scalar(grep(/^ti$/, @$indexes)), 1, "Title index supported");
217
218     my $bibliomodule = new Test::MockModule('C4::Biblio');
219     $bibliomodule->mock('_get_inverted_marc_field_map', sub {
220         my %hash = (
221             '' => {
222                 '245' => { 'sfs' => { 'a' => [ [ 'biblio', 'title' ] ], 'b' => [ [ 'bibliosubtitle', 'subtitle' ] ] },
223                     'list' => [ [ 'a', 'biblio', 'title' ], [ 'b', 'bibliosubtitle', 'subtitle' ] ]
224                 },
225                 '100' => {
226                     'sfs' => { 'a' => [ [ 'biblio', 'author' ] ] },
227                     'list' => [ [ 'a', 'biblio', 'author' ] ]
228                 },
229                 '999' => {
230                     'sfs' => { 'c' => [ [ 'biblio', 'biblionumber' ] ], 'd' => [ [ 'biblioitems', 'biblioitemnumber' ] ] },
231                     'list' => [ [ 'd', 'biblioitems', 'biblioitemnumber' ], [ 'c', 'biblio', 'biblionumber' ] ]
232                 },
233                 '020' => {
234                     'sfs' => { 'a' => [ [ 'biblioitems', 'isbn' ] ] },
235                     'list' => [ [ 'a', 'biblioitems', 'isbn' ] ]
236                 },
237                 '500' => {
238                     'sfs' => { 'a' => [ [ 'biblioitems', 'notes' ] ] },
239                     'list' => [ [ 'a', 'biblioitems', 'notes' ] ]
240                 },
241             }
242         );
243         return \%hash;
244     });
245
246     my %branches = (
247         'CPL' => { 'branchaddress1' => 'Jefferson Summit', 'branchcode' => 'CPL', 'branchname' => 'Centerville', },
248         'FFL' => { 'branchaddress1' => 'River Station', 'branchcode' => 'FFL', 'branchname' => 'Fairfield', },
249         'FPL' => { 'branchaddress1' => 'Hickory Squere', 'branchcode' => 'FPL', 'branchname' => 'Fairview', },
250         'FRL' => { 'branchaddress1' => 'Smith Heights', 'branchcode' => 'FRL', 'branchname' => 'Franklin', },
251         'IPT' => { 'branchaddress1' => '', 'branchcode' => 'IPT', 'branchname' => "Institut Protestant de Théologie", },
252         'LPL' => { 'branchaddress1' => 'East Hills', 'branchcode' => 'LPL', 'branchname' => 'Liberty', },
253         'MPL' => { 'branchaddress1' => '372 Forest Street', 'branchcode' => 'MPL', 'branchname' => 'Midway', },
254         'PVL' => { 'branchaddress1' => 'Meadow Grove', 'branchcode' => 'PVL', 'branchname' => 'Pleasant Valley', },
255         'RPL' => { 'branchaddress1' => 'Johnson Terrace', 'branchcode' => 'RPL', 'branchname' => 'Riverside', },
256         'SPL' => { 'branchaddress1' => 'Highland Boulevard', 'branchcode' => 'SPL', 'branchname' => 'Springfield', },
257         'S'   => { 'branchaddress1' => '', 'branchcode' => 'S', 'branchname' => 'Test', },
258         'TPL' => { 'branchaddress1' => 'Valley Way', 'branchcode' => 'TPL', 'branchname' => 'Troy', },
259         'UPL' => { 'branchaddress1' => 'Chestnut Hollow', 'branchcode' => 'UPL', 'branchname' => 'Union', },
260     );
261     my %itemtypes = (
262         'BK' => { 'imageurl' => 'bridge/book.gif', 'summary' => '', 'itemtype' => 'BK', 'description' => 'Books' },
263         'CF' => { 'imageurl' => 'bridge/computer_file.gif', 'summary' => '', 'itemtype' => 'CF', 'description' => 'Computer Files' },
264         'CR' => { 'imageurl' => 'bridge/periodical.gif', 'summary' => '', 'itemtype' => 'CR', 'description' => 'Continuing Resources' },
265         'MP' => { 'imageurl' => 'bridge/map.gif', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' },
266         'MU' => { 'imageurl' => 'bridge/sound.gif', 'summary' => '', 'itemtype' => 'MU', 'description' => 'Music' },
267         'MX' => { 'imageurl' => 'bridge/kit.gif', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' },
268         'REF' => { 'imageurl' => '', 'summary' => '', 'itemtype' => 'REF', 'description' => 'Reference' },
269         'VM' => { 'imageurl' => 'bridge/dvd.gif', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' },
270     );
271
272     index_sample_records_and_launch_zebra($datadir, $indexing_mode, 'marc21');
273
274     my ($biblionumber, $title);
275     my $record = MARC::Record->new;
276
277     $record->add_fields(
278             [ '020', ' ', ' ', a => '9788522421718' ],
279             [ '245', '0', '0', a => 'Administração da produção /' ]
280             );
281     ($biblionumber,undef,$title) = FindDuplicate($record);
282     is($biblionumber, 51, 'Found duplicate with ISBN');
283
284     $record = MARC::Record->new;
285
286     $record->add_fields(
287             [ '100', '1', ' ', a => 'Carter, Philip J.' ],
288             [ '245', '1', '4', a => 'Test your emotional intelligence :' ]
289             );
290     ($biblionumber,undef,$title) = FindDuplicate($record);
291     is($biblionumber, 203, 'Found duplicate with author/title');
292
293     # Testing SimpleSearch
294
295     my ( $error, $marcresults, $total_hits ) = SimpleSearch("book", 0, 9);
296
297     is(scalar @$marcresults, 9, "SimpleSearch retrieved requested number of records");
298     is($total_hits, 101, "SimpleSearch for 'book' matched right number of records");
299     is($error, undef, "SimpleSearch does not return an error when successful");
300
301     my $marcresults2;
302     ( $error, $marcresults2, $total_hits ) = SimpleSearch("book", 5, 5);
303     is($marcresults->[5], $marcresults2->[0], "SimpleSearch cursor functions");
304
305     ( $error, $marcresults, $total_hits ) = SimpleSearch("kw=book", 0, 10);
306     is($total_hits, 101, "SimpleSearch handles simple CCL");
307
308     ( $error, $marcresults, $total_hits ) = SimpleSearch("Music-number=49631-2", 0, 10);
309     is($total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)");
310     ( $error, $marcresults, $total_hits ) = SimpleSearch("Identifier-publisher-for-music=49631-2", 0, 10);
311     is($total_hits, 1, "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)");
312
313     # Testing getRecords
314
315     my $results_hashref;
316     my $facets_loop;
317     ( undef, $results_hashref, $facets_loop ) =
318         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
319     is($results_hashref->{biblioserver}->{hits}, 101, "getRecords keyword search for 'book' matched right number of records");
320     is(scalar @{$results_hashref->{biblioserver}->{RECORDS}}, 19, "getRecords returned requested number of records");
321     my $record5 = $results_hashref->{biblioserver}->{RECORDS}->[5];
322     ( undef, $results_hashref, $facets_loop ) =
323         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '20', 5, undef, \%branches, \%itemtypes, 'ccl', undef);
324     ok(!defined $results_hashref->{biblioserver}->{RECORDS}->[0] &&
325         !defined $results_hashref->{biblioserver}->{RECORDS}->[1] &&
326         !defined $results_hashref->{biblioserver}->{RECORDS}->[2] &&
327         !defined $results_hashref->{biblioserver}->{RECORDS}->[3] &&
328         !defined $results_hashref->{biblioserver}->{RECORDS}->[4] &&
329         $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works");
330
331     ( undef, $results_hashref, $facets_loop ) =
332         getRecords('ti:book', 'ti:book', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
333     is($results_hashref->{biblioserver}->{hits}, 11, "getRecords title search for 'book' matched right number of records");
334
335     ( undef, $results_hashref, $facets_loop ) =
336         getRecords('au:Lessig', 'au:Lessig', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
337     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords title search for 'Australia' matched right number of records");
338
339 if ( $indexing_mode eq 'dom' ) {
340     ( undef, $results_hashref, $facets_loop ) =
341         getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
342     ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Efectos del ambiente/ &&
343         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies' &&
344         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
345         , "Simple relevance sorting in getRecords matches old behavior");
346
347     ( undef, $results_hashref, $facets_loop ) =
348         getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
349     ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/ &&
350         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[6],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
351         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'World health statistics 2009^ien'
352         , "Simple ascending author sorting in getRecords matches old behavior");
353
354     ( undef, $results_hashref, $facets_loop ) =
355         getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
356     ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
357         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[12],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
358         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/
359         , "Simple descending author sorting in getRecords matches old behavior");
360
361     ( undef, $results_hashref, $facets_loop ) =
362         getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
363     ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies' &&
364         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ &&
365         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
366         , "Simple ascending publication date sorting in getRecords matches old behavior");
367
368     ( undef, $results_hashref, $facets_loop ) =
369         getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
370     ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Estado de salud/ &&
371         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
372         MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies'
373         , "Simple descending publication date sorting in getRecords matches old behavior");
374
375 } elsif ( $indexing_mode eq 'grs1' ){
376     ( undef, $results_hashref, $facets_loop ) =
377         getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
378     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/^Efectos del ambiente/ &&
379         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[7])->title_proper() eq 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies' &&
380         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/^Indicadores de resultados identificados/
381         , "Simple relevance sorting in getRecords matches old behavior");
382
383     ( undef, $results_hashref, $facets_loop ) =
384         getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
385     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/la enfermedad laboral\^ies$/ &&
386         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[6])->title_proper() =~ m/^Indicadores de resultados identificados/ &&
387         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() eq 'World health statistics 2009^ien'
388         , "Simple ascending author sorting in getRecords matches old behavior");
389
390     ( undef, $results_hashref, $facets_loop ) =
391         getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
392     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() eq 'World health statistics 2009^ien' &&
393         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[12])->title_proper() =~ m/^Indicadores de resultados identificados/ &&
394         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/la enfermedad laboral\^ies$/
395         , "Simple descending author sorting in getRecords matches old behavior");
396
397     ( undef, $results_hashref, $facets_loop ) =
398         getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
399     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() eq 'Manual de higiene industrial^ies' &&
400         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[7])->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ &&
401         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/^Indicadores de resultados identificados/
402         , "Simple ascending publication date sorting in getRecords matches old behavior");
403
404     ( undef, $results_hashref, $facets_loop ) =
405         getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
406     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/^Estado de salud/ &&
407         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[7])->title_proper() eq 'World health statistics 2009^ien' &&
408         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() eq 'Manual de higiene industrial^ies'
409         , "Simple descending publication date sorting in getRecords matches old behavior");
410 }
411
412     ( undef, $results_hashref, $facets_loop ) =
413         getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, undef, 1);
414     $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]);
415     is($record->title_proper(), 'Books', "Scan returned requested item");
416     is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term");
417     # Time to test buildQuery and searchResults too.
418
419     my ( $query, $simple_query, $query_cgi,
420     $query_desc, $limit, $limit_cgi, $limit_desc,
421     $query_type );
422     ( $error, $query, $simple_query, $query_cgi,
423     $query_desc, $limit, $limit_cgi, $limit_desc,
424     $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en');
425     like($query, qr/kw\W.*salud/, "Built CCL keyword query");
426
427     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
428     is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records");
429
430     my @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0,
431         $results_hashref->{'biblioserver'}->{"RECORDS"});
432     is(scalar @newresults,18, "searchResults returns requested number of hits");
433
434     ( $error, $query, $simple_query, $query_cgi,
435     $query_desc, $limit, $limit_cgi, $limit_desc,
436     $query_type ) = buildQuery([ 'and' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
437     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query");
438
439     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
440     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records");
441
442     ( $error, $query, $simple_query, $query_cgi,
443     $query_desc, $limit, $limit_cgi, $limit_desc,
444     $query_type ) = buildQuery([ 'or' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
445     like($query, qr/kw\W.*salud\W.*or.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query");
446
447     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
448     is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records");
449
450     ( $error, $query, $simple_query, $query_cgi,
451     $query_desc, $limit, $limit_cgi, $limit_desc,
452     $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
453     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query");
454
455     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
456     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records");
457
458     ( $error, $query, $simple_query, $query_cgi,
459     $query_desc, $limit, $limit_cgi, $limit_desc,
460     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en');
461     like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly");
462     unlike($query_desc, qr/Laboratorios/, "Facets not included in query description");
463
464     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
465     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated faceted search matched right number of records");
466
467
468     ( $error, $query, $simple_query, $query_cgi,
469     $query_desc, $limit, $limit_cgi, $limit_desc,
470     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en');
471
472     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
473     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records");
474
475
476     ( $error, $query, $simple_query, $query_cgi,
477     $query_desc, $limit, $limit_cgi, $limit_desc,
478     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en');
479
480     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
481     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated multi-faceted search matched right number of records");
482
483     ( $error, $query, $simple_query, $query_cgi,
484     $query_desc, $limit, $limit_cgi, $limit_desc,
485     $query_type ) = buildQuery([], [ 'NEKLS' ], [ 'Code-institution' ], [], [], 0, 'en');
486     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
487     is($results_hashref->{biblioserver}->{hits}, 12,
488        'search using index whose name contains "ns" returns expected results (bug 10271)');
489
490     $UseQueryParser = 1;
491     ( $error, $query, $simple_query, $query_cgi,
492     $query_desc, $limit, $limit_cgi, $limit_desc,
493     $query_type ) = buildQuery([], [ 'book' ], [ 'kw' ], [], [], 0, 'en');
494     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
495     is($results_hashref->{biblioserver}->{hits}, 101, "Search for 'book' with index set to 'kw' returns 101 hits");
496     ( $error, $query, $simple_query, $query_cgi,
497     $query_desc, $limit, $limit_cgi, $limit_desc,
498     $query_type ) = buildQuery([ 'and' ], [ 'book', 'another' ], [ 'kw', 'kw' ], [], [], 0, 'en');
499     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
500     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'kw:book && kw:another' returns 1 hit");
501     $UseQueryParser = 0;
502
503     # FIXME: the availability limit does not actually work, so for the moment we
504     # are just checking that it behaves consistently
505     ( $error, $query, $simple_query, $query_cgi,
506     $query_desc, $limit, $limit_cgi, $limit_desc,
507     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
508
509     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
510     is($results_hashref->{biblioserver}->{hits}, 26, "getRecords generated availability-limited search matched right number of records");
511
512     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
513         $results_hashref->{'biblioserver'}->{"RECORDS"});
514     my $allavailable = 'true';
515     foreach my $result (@newresults) {
516         $allavailable = 'false' unless $result->{availablecount} > 0;
517     }
518     is ($allavailable, 'true', 'All records have at least one item available');
519
520
521     ( $error, $query, $simple_query, $query_cgi,
522     $query_desc, $limit, $limit_cgi, $limit_desc,
523     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
524
525     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
526     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
527
528     ( $error, $query, $simple_query, $query_cgi,
529     $query_desc, $limit, $limit_cgi, $limit_desc,
530     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
531
532     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
533     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
534
535     ( $error, $query, $simple_query, $query_cgi,
536     $query_desc, $limit, $limit_cgi, $limit_desc,
537     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
538
539     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
540     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
541
542     ( $error, $query, $simple_query, $query_cgi,
543     $query_desc, $limit, $limit_cgi, $limit_desc,
544     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
545
546     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
547     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
548
549     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
550     $QueryWeightFields = 1;
551     ( $error, $query, $simple_query, $query_cgi,
552     $query_desc, $limit, $limit_cgi, $limit_desc,
553     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
554
555     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
556     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
557     if ($indexing_mode eq 'grs1') {
558         is(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper(), 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies', "Weighted query returns best match first");
559     } else {
560         local $TODO = "Query weighting does not behave exactly the same in DOM vs. GRS";
561         is(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper(), 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies', "Weighted query returns best match first");
562     }
563
564     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
565     $QueryAutoTruncate = 1;
566     ( $error, $query, $simple_query, $query_cgi,
567     $query_desc, $limit, $limit_cgi, $limit_desc,
568     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
569
570     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
571     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
572
573     ( $error, $query, $simple_query, $query_cgi,
574     $query_desc, $limit, $limit_cgi, $limit_desc,
575     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
576
577     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
578     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
579
580     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
581     $QueryWeightFields = 1;
582     ( $error, $query, $simple_query, $query_cgi,
583     $query_desc, $limit, $limit_cgi, $limit_desc,
584     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
585     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
586     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
587
588     ( $error, $query, $simple_query, $query_cgi,
589     $query_desc, $limit, $limit_cgi, $limit_desc,
590     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
591     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
592     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
593
594     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
595     ( $error, $query, $simple_query, $query_cgi,
596     $query_desc, $limit, $limit_cgi, $limit_desc,
597     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
598
599     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
600     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
601
602     ( $error, $query, $simple_query, $query_cgi,
603     $query_desc, $limit, $limit_cgi, $limit_desc,
604     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
605
606     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
607     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
608
609     $QueryStemming = $QueryWeightFields = 1;
610     $QueryFuzzy = $QueryAutoTruncate = 0;
611     ( $error, $query, $simple_query, $query_cgi,
612     $query_desc, $limit, $limit_cgi, $limit_desc,
613     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
614
615     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
616     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
617
618     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
619     ( $error, $query, $simple_query, $query_cgi,
620     $query_desc, $limit, $limit_cgi, $limit_desc,
621     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
622
623     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
624     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
625
626     # Let's see what happens when we pass bad data into these routines.
627     # We have to catch warnings since we're not very good about returning errors.
628
629     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
630         "SimpleSearch warns about CCL parsing error with nonsense query";
631     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
632
633     warning_like {( undef, $results_hashref, $facets_loop ) =
634         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'nonsense', undef) }
635         qr/Unknown query_type/, "getRecords warns about unknown query type";
636
637     warning_like {( undef, $results_hashref, $facets_loop ) =
638         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, '', undef) }
639         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
640
641     # Let's just test a few other bits and bobs, just for fun
642
643     ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
644     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
645         $results_hashref->{'biblioserver'}->{"RECORDS"});
646     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
647
648
649     ## Regression test for Bug 10741
650
651     # make one of the test items appear to be in transit
652     my $circ_module = new Test::MockModule('C4::Circulation');
653     $circ_module->mock('GetTransfers', sub {
654         my $itemnumber = shift // -1;
655         if ($itemnumber == 11) {
656             return ('2013-07-19', 'MPL', 'CPL');
657         } else {
658             return;
659         }
660     });
661
662     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
663     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
664         $results_hashref->{'biblioserver'}->{"RECORDS"});
665     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
666
667     ## Regression test for bug 10684
668     ( undef, $results_hashref, $facets_loop ) =
669         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
670     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
671     warning_like { @newresults = searchResults('intranet', $query_desc,
672                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
673                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
674                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
675                 "Warning is raised correctly for invalid tags in MARC::Record";
676     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
677
678     # Testing exploding indexes
679     my $term;
680     my $searchmodule = new Test::MockModule('C4::Search');
681     $searchmodule->mock('SimpleSearch', sub {
682         my $query = shift;
683
684         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
685
686         my $record = MARC::Record->new;
687         if ($query =~ m/Arizona/) {
688             $record->add_fields(
689                 [ '001', '1234' ],
690                 [ '151', ' ', ' ', a => 'Arizona' ],
691                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
692                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
693                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
694                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
695                 [ '551', ' ', ' ', a => 'New Mexico' ],
696                 );
697         }
698         return '', [ $record->as_usmarc() ], 1;
699     });
700
701     $UseQueryParser = 1;
702     $term = 'Arizona';
703     ( $error, $query, $simple_query, $query_cgi,
704     $query_desc, $limit, $limit_cgi, $limit_desc,
705     $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
706     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
707
708     ( $error, $query, $simple_query, $query_cgi,
709     $query_desc, $limit, $limit_cgi, $limit_desc,
710     $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
711     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
712
713     ( $error, $query, $simple_query, $query_cgi,
714     $query_desc, $limit, $limit_cgi, $limit_desc,
715     $query_type ) = buildQuery([], [ $term ], [ 'su-rl' ], [  ], [], 0, 'en');
716     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
717
718     ( $error, $query, $simple_query, $query_cgi,
719     $query_desc, $limit, $limit_cgi, $limit_desc,
720     $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
721     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
722     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
723
724     ( $error, $query, $simple_query, $query_cgi,
725     $query_desc, $limit, $limit_cgi, $limit_desc,
726     $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
727     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
728     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
729
730     ( $error, $query, $simple_query, $query_cgi,
731     $query_desc, $limit, $limit_cgi, $limit_desc,
732     $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
733     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
734
735     ( $error, $query, $simple_query, $query_cgi,
736     $query_desc, $limit, $limit_cgi, $limit_desc,
737     $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
738     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
739
740     ( $error, $query, $simple_query, $query_cgi,
741     $query_desc, $limit, $limit_cgi, $limit_desc,
742     $query_type ) = buildQuery([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
743     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
744
745     ( $error, $query, $simple_query, $query_cgi,
746     $query_desc, $limit, $limit_cgi, $limit_desc,
747     $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
748     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
749     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
750
751     sub matchesExplodedTerms {
752         my ($message, $query, @terms) = @_;
753         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
754         like($query, qr/$match/, $message);
755     }
756
757     # authority records
758     use_ok('C4::AuthoritiesMarc');
759     $UseQueryParser = 0;
760
761     my ($auths, $count) = SearchAuthorities(
762         ['mainentry'], ['and'], [''], ['starts'],
763         ['shakespeare'], 0, 10, '', '', 1
764     );
765     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
766     ($auths, $count) = SearchAuthorities(
767         ['mainentry'], ['and'], [''], ['starts'],
768         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
769     );
770     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
771     ($auths, $count) = SearchAuthorities(
772         ['mainentry'], ['and'], [''], ['starts'],
773         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
774     );
775     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
776     ($auths, $count) = SearchAuthorities(
777         ['match'], ['and'], [''], ['contains'],
778         ['沙士北亞威廉姆'], 0, 10, '', '', 1
779     );
780     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
781
782     $UseQueryParser = 1;
783
784     ($auths, $count) = SearchAuthorities(
785         ['mainentry'], ['and'], [''], ['starts'],
786         ['shakespeare'], 0, 10, '', '', 1
787     );
788     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
789     ($auths, $count) = SearchAuthorities(
790         ['mainentry'], ['and'], [''], ['starts'],
791         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
792     );
793     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
794     ($auths, $count) = SearchAuthorities(
795         ['mainentry'], ['and'], [''], ['starts'],
796         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
797     );
798     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
799     ($auths, $count) = SearchAuthorities(
800         ['match'], ['and'], [''], ['contains'],
801         ['沙士北亞威廉姆'], 0, 10, '', '', 1
802     );
803     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
804
805     # retrieve records that are larger than the MARC limit of 99,999 octets
806     ( undef, $results_hashref, $facets_loop ) =
807         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
808     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
809     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
810         $results_hashref->{'biblioserver'}->{"RECORDS"});
811     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
812     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
813     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
814
815     # notforloancount should be returned as part of searchResults output
816     ok( defined $newresults[0]->{notforloancount},
817         '\'notforloancount\' defined in searchResults output (Bug 12419)');
818     is( $newresults[0]->{notforloancount}, 2,
819         '\'notforloancount\' == 2 (Bug 12419)');
820
821     # verify that we don't attempt to sort if no results were returned
822     # because of a query error
823     warning_like {( undef, $results_hashref, $facets_loop ) =
824         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef)
825     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
826     
827     # Test facet calculation
828     my $facets_counter = {};
829     my $facets         = C4::Koha::getFacets();
830     # Create a record with a 100$z field
831     my $marc_record    = MARC::Record->new;
832     $marc_record->add_fields(
833         [ '001', '1234' ],
834         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
835         [ '100', 'z', ' ', a => 'Tomasito' ],
836         [ '245', ' ', ' ', a => 'First try' ]
837     );
838     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
839     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
840         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
841     $marc_record    = MARC::Record->new;
842     $marc_record->add_fields(
843         [ '001', '1234' ],
844         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
845         [ '100', 'z', ' ', a => 'Tomasito' ],
846         [ '245', ' ', ' ', a => 'Second try' ]
847     );
848     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
849     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
850         "_get_facets_data_from_record correctly counts author facet twice");
851
852     # Test _get_facets_info
853     my $facets_info = C4::Search::_get_facets_info( $facets );
854     my $expected_facets_info_marc21 = {
855                    'au' => { 'expanded'    => undef,
856                              'label_value' => "Authors" },
857         'holdingbranch' => { 'expanded'    => undef,
858                              'label_value' => "HoldingLibrary" },
859                 'itype' => { 'expanded'    => undef,
860                              'label_value' => "ItemTypes" },
861              'location' => { 'expanded'    => undef,
862                              'label_value' => "Location" },
863                    'se' => { 'expanded'    => undef,
864                              'label_value' => "Series" },
865                'su-geo' => { 'expanded'    => undef,
866                              'label_value' => "Places" },
867                 'su-to' => { 'expanded'    => undef,
868                              'label_value' => "Topics" },
869                 'su-ut' => { 'expanded'    => undef,
870                              'label_value' => "Titles" }
871     };
872     is_deeply( $facets_info, $expected_facets_info_marc21,
873         "_get_facets_info returns the correct data");
874
875     cleanup();
876 }
877
878 sub run_unimarc_search_tests {
879     my $indexing_mode = shift;
880     $datadir = tempdir();
881     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc $indexing_mode");
882
883     mock_marcfromkohafield('unimarc');
884     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
885     $context->set_context();
886
887     use_ok('C4::Search');
888
889     # set search syspreferences to a known starting point
890     $QueryStemming = 0;
891     $QueryAutoTruncate = 0;
892     $QueryWeightFields = 0;
893     $QueryFuzzy = 0;
894     $UseQueryParser = 0;
895     $marcflavour = 'UNIMARC';
896
897     index_sample_records_and_launch_zebra($datadir, $indexing_mode, 'unimarc');
898
899     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
900     is($total_hits, 1, 'UNIMARC title search');
901     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
902     is($total_hits, 1, 'UNIMARC target audience = u');
903     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
904     is($total_hits, 4, 'UNIMARC target audience = k');
905     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
906     is($total_hits, 3, 'UNIMARC target audience = m');
907     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
908     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
909
910     # authority records
911     use_ok('C4::AuthoritiesMarc');
912     $UseQueryParser = 0;
913
914     my ($auths, $count) = SearchAuthorities(
915         ['mainentry'], ['and'], [''], ['contains'],
916         ['wil'], 0, 10, '', '', 1
917     );
918     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
919     ($auths, $count) = SearchAuthorities(
920         ['match'], ['and'], [''], ['contains'],
921         ['wil'], 0, 10, '', '', 1
922     );
923     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
924     ($auths, $count) = SearchAuthorities(
925         ['mainentry'], ['and'], [''], ['contains'],
926         ['michel'], 0, 20, '', '', 1
927     );
928     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
929     ($auths, $count) = SearchAuthorities(
930         ['mainmainentry'], ['and'], [''], ['exact'],
931         ['valley'], 0, 20, '', '', 1
932     );
933     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
934     ($auths, $count) = SearchAuthorities(
935         ['mainmainentry'], ['and'], [''], ['exact'],
936         ['vall'], 0, 20, '', '', 1
937     );
938     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
939     ($auths, $count) = SearchAuthorities(
940         ['Any'], ['and'], [''], ['starts'],
941         ['jean'], 0, 30, '', '', 1
942     );
943     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
944
945     # Test _get_facets_info
946     my $facets      = C4::Koha::getFacets();
947     my $facets_info = C4::Search::_get_facets_info( $facets );
948     my $expected_facets_info_unimarc = {
949                    'au' => { 'expanded'    => undef,
950                              'label_value' => "Authors" },
951         'holdingbranch' => { 'expanded'    => undef,
952                              'label_value' => "HoldingLibrary" },
953              'location' => { 'expanded'    => undef,
954                              'label_value' => "Location" },
955                    'se' => { 'expanded'    => undef,
956                              'label_value' => "Series" },
957                'su-geo' => { 'expanded'    => undef,
958                              'label_value' => "Places" },
959                 'su-to' => { 'expanded'    => undef,
960                              'label_value' => "Topics" },
961                 'su-ut' => { 'expanded'    => undef,
962                              'label_value' => "Titles" }
963     };
964     is_deeply( $facets_info, $expected_facets_info_unimarc,
965         "_get_facets_info returns the correct data");
966
967     cleanup();
968 }
969
970 subtest 'MARC21 + GRS-1' => sub {
971     plan tests => 107;
972     run_marc21_search_tests('grs1');
973 };
974
975 subtest 'MARC21 + DOM' => sub {
976     plan tests => 107;
977     run_marc21_search_tests('dom');
978 };
979
980 subtest 'UNIMARC + GRS-1' => sub {
981     plan tests => 14;
982     run_unimarc_search_tests('grs1');
983 };
984
985 subtest 'UNIMARC + DOM' => sub {
986     plan tests => 14;
987     run_unimarc_search_tests('dom');
988 };
989
990 1;