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