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