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