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