115e384d3321abe52a1c4956dccb90db250da024
[koha-equinox.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     ( $error, $query, $simple_query, $query_cgi,
623     $query_desc, $limit, $limit_cgi, $limit_desc,
624     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
625     is($query, 'su,phr=0 ', 'buildQuery should keep 0 value');
626
627     # Let's see what happens when we pass bad data into these routines.
628     # We have to catch warnings since we're not very good about returning errors.
629
630     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
631         "SimpleSearch warns about CCL parsing error with nonsense query";
632     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
633
634     warning_like {( undef, $results_hashref, $facets_loop ) =
635         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'nonsense', undef) }
636         qr/Unknown query_type/, "getRecords warns about unknown query type";
637
638     warning_like {( undef, $results_hashref, $facets_loop ) =
639         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, '', undef) }
640         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
641
642     # Let's just test a few other bits and bobs, just for fun
643
644     ($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);
645     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
646         $results_hashref->{'biblioserver'}->{"RECORDS"});
647     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
648
649
650     ## Regression test for Bug 10741
651
652     # make one of the test items appear to be in transit
653     my $circ_module = new Test::MockModule('C4::Circulation');
654     $circ_module->mock('GetTransfers', sub {
655         my $itemnumber = shift // -1;
656         if ($itemnumber == 11) {
657             return ('2013-07-19', 'MPL', 'CPL');
658         } else {
659             return;
660         }
661     });
662
663     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
664     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
665         $results_hashref->{'biblioserver'}->{"RECORDS"});
666     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
667
668     ## Regression test for bug 10684
669     ( undef, $results_hashref, $facets_loop ) =
670         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
671     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
672     warning_like { @newresults = searchResults('intranet', $query_desc,
673                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
674                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
675                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
676                 "Warning is raised correctly for invalid tags in MARC::Record";
677     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
678
679     # Testing exploding indexes
680     my $term;
681     my $searchmodule = new Test::MockModule('C4::Search');
682     $searchmodule->mock('SimpleSearch', sub {
683         my $query = shift;
684
685         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
686
687         my $record = MARC::Record->new;
688         if ($query =~ m/Arizona/) {
689             $record->add_fields(
690                 [ '001', '1234' ],
691                 [ '151', ' ', ' ', a => 'Arizona' ],
692                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
693                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
694                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
695                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
696                 [ '551', ' ', ' ', a => 'New Mexico' ],
697                 );
698         }
699         return '', [ $record->as_usmarc() ], 1;
700     });
701
702     $UseQueryParser = 1;
703     $term = 'Arizona';
704     ( $error, $query, $simple_query, $query_cgi,
705     $query_desc, $limit, $limit_cgi, $limit_desc,
706     $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
707     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
708
709     ( $error, $query, $simple_query, $query_cgi,
710     $query_desc, $limit, $limit_cgi, $limit_desc,
711     $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
712     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', '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 ], [ 'su-rl' ], [  ], [], 0, 'en');
717     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
718
719     ( $error, $query, $simple_query, $query_cgi,
720     $query_desc, $limit, $limit_cgi, $limit_desc,
721     $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
722     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
723     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
724
725     ( $error, $query, $simple_query, $query_cgi,
726     $query_desc, $limit, $limit_cgi, $limit_desc,
727     $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
728     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
729     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
730
731     ( $error, $query, $simple_query, $query_cgi,
732     $query_desc, $limit, $limit_cgi, $limit_desc,
733     $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
734     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
735
736     ( $error, $query, $simple_query, $query_cgi,
737     $query_desc, $limit, $limit_cgi, $limit_desc,
738     $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
739     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', '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([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
744     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
745
746     ( $error, $query, $simple_query, $query_cgi,
747     $query_desc, $limit, $limit_cgi, $limit_desc,
748     $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
749     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
750     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
751
752     sub matchesExplodedTerms {
753         my ($message, $query, @terms) = @_;
754         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
755         like($query, qr/$match/, $message);
756     }
757
758     # authority records
759     use_ok('C4::AuthoritiesMarc');
760     $UseQueryParser = 0;
761
762     my ($auths, $count) = SearchAuthorities(
763         ['mainentry'], ['and'], [''], ['starts'],
764         ['shakespeare'], 0, 10, '', '', 1
765     );
766     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
767     ($auths, $count) = SearchAuthorities(
768         ['mainentry'], ['and'], [''], ['starts'],
769         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
770     );
771     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
772     ($auths, $count) = SearchAuthorities(
773         ['mainentry'], ['and'], [''], ['starts'],
774         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
775     );
776     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
777     ($auths, $count) = SearchAuthorities(
778         ['match'], ['and'], [''], ['contains'],
779         ['沙士北亞威廉姆'], 0, 10, '', '', 1
780     );
781     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
782
783     $UseQueryParser = 1;
784
785     ($auths, $count) = SearchAuthorities(
786         ['mainentry'], ['and'], [''], ['starts'],
787         ['shakespeare'], 0, 10, '', '', 1
788     );
789     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
790     ($auths, $count) = SearchAuthorities(
791         ['mainentry'], ['and'], [''], ['starts'],
792         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
793     );
794     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
795     ($auths, $count) = SearchAuthorities(
796         ['mainentry'], ['and'], [''], ['starts'],
797         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
798     );
799     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
800     ($auths, $count) = SearchAuthorities(
801         ['match'], ['and'], [''], ['contains'],
802         ['沙士北亞威廉姆'], 0, 10, '', '', 1
803     );
804     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
805
806     # retrieve records that are larger than the MARC limit of 99,999 octets
807     ( undef, $results_hashref, $facets_loop ) =
808         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
809     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
810     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
811         $results_hashref->{'biblioserver'}->{"RECORDS"});
812     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
813     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
814     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
815
816     # notforloancount should be returned as part of searchResults output
817     ok( defined $newresults[0]->{notforloancount},
818         '\'notforloancount\' defined in searchResults output (Bug 12419)');
819     is( $newresults[0]->{notforloancount}, 2,
820         '\'notforloancount\' == 2 (Bug 12419)');
821
822     # verify that we don't attempt to sort if no results were returned
823     # because of a query error
824     warning_like {( undef, $results_hashref, $facets_loop ) =
825         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef)
826     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
827     
828     # Test facet calculation
829     my $facets_counter = {};
830     my $facets         = C4::Koha::getFacets();
831     # Create a record with a 100$z field
832     my $marc_record    = MARC::Record->new;
833     $marc_record->add_fields(
834         [ '001', '1234' ],
835         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
836         [ '100', 'z', ' ', a => 'Tomasito' ],
837         [ '245', ' ', ' ', a => 'First try' ]
838     );
839     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
840     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
841         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
842     $marc_record    = MARC::Record->new;
843     $marc_record->add_fields(
844         [ '001', '1234' ],
845         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
846         [ '100', 'z', ' ', a => 'Tomasito' ],
847         [ '245', ' ', ' ', a => 'Second try' ]
848     );
849     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
850     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
851         "_get_facets_data_from_record correctly counts author facet twice");
852
853     # Test _get_facets_info
854     my $facets_info = C4::Search::_get_facets_info( $facets );
855     my $expected_facets_info_marc21 = {
856                    'au' => { 'expanded'    => undef,
857                              'label_value' => "Authors" },
858                 'ccode' => { 'expanded'    => undef,
859                              'label_value' => "CollectionCodes" },
860         'holdingbranch' => { 'expanded'    => undef,
861                              'label_value' => "HoldingLibrary" },
862                 'itype' => { 'expanded'    => undef,
863                              'label_value' => "ItemTypes" },
864              'location' => { 'expanded'    => undef,
865                              'label_value' => "Location" },
866                    'se' => { 'expanded'    => undef,
867                              'label_value' => "Series" },
868                'su-geo' => { 'expanded'    => undef,
869                              'label_value' => "Places" },
870                 'su-to' => { 'expanded'    => undef,
871                              'label_value' => "Topics" },
872                 'su-ut' => { 'expanded'    => undef,
873                              'label_value' => "Titles" }
874     };
875     delete $expected_facets_info_marc21->{holdingbranch}
876         if Koha::Libraries->count == 1;
877     is_deeply( $facets_info, $expected_facets_info_marc21,
878         "_get_facets_info returns the correct data");
879
880     cleanup();
881 }
882
883 sub run_unimarc_search_tests {
884     my $indexing_mode = shift;
885     $datadir = tempdir();
886     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc $indexing_mode");
887
888     Koha::Caches->get_instance('config')->flush_all;
889
890     mock_GetMarcSubfieldStructure('unimarc');
891     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
892     $context->set_context();
893
894     use_ok('C4::Search');
895
896     # set search syspreferences to a known starting point
897     $QueryStemming = 0;
898     $QueryAutoTruncate = 0;
899     $QueryWeightFields = 0;
900     $QueryFuzzy = 0;
901     $UseQueryParser = 0;
902     $marcflavour = 'UNIMARC';
903
904     index_sample_records_and_launch_zebra($datadir, $indexing_mode, 'unimarc');
905
906     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
907     is($total_hits, 1, 'UNIMARC title search');
908     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
909     is($total_hits, 1, 'UNIMARC target audience = u');
910     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
911     is($total_hits, 4, 'UNIMARC target audience = k');
912     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
913     is($total_hits, 3, 'UNIMARC target audience = m');
914     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
915     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
916
917     # authority records
918     use_ok('C4::AuthoritiesMarc');
919     $UseQueryParser = 0;
920
921     my ($auths, $count) = SearchAuthorities(
922         ['mainentry'], ['and'], [''], ['contains'],
923         ['wil'], 0, 10, '', '', 1
924     );
925     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
926     ($auths, $count) = SearchAuthorities(
927         ['match'], ['and'], [''], ['contains'],
928         ['wil'], 0, 10, '', '', 1
929     );
930     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
931     ($auths, $count) = SearchAuthorities(
932         ['mainentry'], ['and'], [''], ['contains'],
933         ['michel'], 0, 20, '', '', 1
934     );
935     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
936     ($auths, $count) = SearchAuthorities(
937         ['mainmainentry'], ['and'], [''], ['exact'],
938         ['valley'], 0, 20, '', '', 1
939     );
940     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
941     ($auths, $count) = SearchAuthorities(
942         ['mainmainentry'], ['and'], [''], ['exact'],
943         ['vall'], 0, 20, '', '', 1
944     );
945     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
946     ($auths, $count) = SearchAuthorities(
947         ['Any'], ['and'], [''], ['starts'],
948         ['jean'], 0, 30, '', '', 1
949     );
950     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
951
952     # Test _get_facets_info
953     my $facets      = C4::Koha::getFacets();
954     my $facets_info = C4::Search::_get_facets_info( $facets );
955     my $expected_facets_info_unimarc = {
956                    'au' => { 'expanded'    => undef,
957                              'label_value' => "Authors" },
958                 'ccode' => { 'expanded'    => undef,
959                              'label_value' => "CollectionCodes" },
960         'holdingbranch' => { 'expanded'    => undef,
961                              'label_value' => "HoldingLibrary" },
962              'location' => { 'expanded'    => undef,
963                              'label_value' => "Location" },
964                    'se' => { 'expanded'    => undef,
965                              'label_value' => "Series" },
966                'su-geo' => { 'expanded'    => undef,
967                              'label_value' => "Places" },
968                 'su-to' => { 'expanded'    => undef,
969                              'label_value' => "Topics" },
970                 'su-ut' => { 'expanded'    => undef,
971                              'label_value' => "Titles" }
972     };
973     delete $expected_facets_info_unimarc->{holdingbranch}
974         if Koha::Libraries->count == 1;
975     is_deeply( $facets_info, $expected_facets_info_unimarc,
976         "_get_facets_info returns the correct data");
977
978     cleanup();
979 }
980
981 subtest 'MARC21 + GRS-1' => sub {
982     plan tests => 110;
983     run_marc21_search_tests('grs1');
984 };
985
986 subtest 'MARC21 + DOM' => sub {
987     plan tests => 110;
988     run_marc21_search_tests('dom');
989 };
990
991 subtest 'UNIMARC + GRS-1' => sub {
992     plan tests => 14;
993     run_unimarc_search_tests('grs1');
994 };
995
996 subtest 'UNIMARC + DOM' => sub {
997     plan tests => 14;
998     run_unimarc_search_tests('dom');
999 };
1000
1001 # Make sure that following tests are not using our config settings
1002 Koha::Caches->get_instance('config')->flush_all;
1003