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