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