Bug 23086: Unit test
[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     my $mocked_xslt = Test::MockModule->new('Koha::XSLT_Handler');
517     $mocked_xslt->mock( 'transform', sub {
518         my ($self, $xml) = @_;
519         return $xml;
520     });
521
522     @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
523         $results_hashref->{'biblioserver'}->{"RECORDS"}, { anonymous_session => 1 });
524
525     like( $newresults[0]->{XSLTResultsRecord}, qr/<variable name="anonymous_session">1<\/variable>/, "Variable injected correctly" );
526
527     my $biblio_id = $newresults[0]->{biblionumber};
528     my $fw = C4::Biblio::GetFrameworkCode($biblio_id);
529
530     my $dbh = C4::Context->dbh;
531     # Hide subfield 'p' in OPAC
532     $dbh->do(qq{
533         UPDATE marc_subfield_structure
534         SET hidden=4
535         WHERE frameworkcode='$fw' AND
536               tagfield=952 AND
537               tagsubfield='p';
538     });
539
540     # Hide subfield 'y' in Staff
541     $dbh->do(qq{
542         UPDATE marc_subfield_structure
543         SET hidden=-7
544         WHERE frameworkcode='$fw' AND
545               tagfield=952 AND
546               tagsubfield='y';
547     });
548
549     Koha::Caches->get_instance->flush_all;
550
551     @newresults = searchResults(
552         { 'interface' => 'opac' },
553         $query_desc,
554         $results_hashref->{'biblioserver'}->{'hits'},
555         17,
556         0,
557         0,
558         $results_hashref->{'biblioserver'}->{"RECORDS"}
559     );
560
561     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, '952\$p hidden in OPAC' );
562
563     @newresults = searchResults(
564         { 'interface' => 'intranet' },
565         $query_desc,
566         $results_hashref->{'biblioserver'}->{'hits'},
567         17,
568         0,
569         0,
570         $results_hashref->{'biblioserver'}->{"RECORDS"}
571     );
572
573     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, '952\$y hidden on staff interface' );
574
575     ( $error, $query, $simple_query, $query_cgi,
576     $query_desc, $limit, $limit_cgi, $limit_desc,
577     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
578
579     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
580     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
581
582     ( $error, $query, $simple_query, $query_cgi,
583     $query_desc, $limit, $limit_cgi, $limit_desc,
584     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
585
586     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
587     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
588
589     ( $error, $query, $simple_query, $query_cgi,
590     $query_desc, $limit, $limit_cgi, $limit_desc,
591     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
592
593     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
594     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
595
596     ( $error, $query, $simple_query, $query_cgi,
597     $query_desc, $limit, $limit_cgi, $limit_desc,
598     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
599
600     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
601     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
602
603     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
604     $QueryWeightFields = 1;
605     ( $error, $query, $simple_query, $query_cgi,
606     $query_desc, $limit, $limit_cgi, $limit_desc,
607     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
608
609     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
610     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
611     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");
612
613     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
614     $QueryAutoTruncate = 1;
615     ( $error, $query, $simple_query, $query_cgi,
616     $query_desc, $limit, $limit_cgi, $limit_desc,
617     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
618
619     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
620     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
621
622     ( $error, $query, $simple_query, $query_cgi,
623     $query_desc, $limit, $limit_cgi, $limit_desc,
624     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
625
626     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
627     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
628
629     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
630     $QueryWeightFields = 1;
631     ( $error, $query, $simple_query, $query_cgi,
632     $query_desc, $limit, $limit_cgi, $limit_desc,
633     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
634     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
635     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
636
637     ( $error, $query, $simple_query, $query_cgi,
638     $query_desc, $limit, $limit_cgi, $limit_desc,
639     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
640     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
641     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
642
643     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
644     ( $error, $query, $simple_query, $query_cgi,
645     $query_desc, $limit, $limit_cgi, $limit_desc,
646     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
647
648     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
649     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
650
651     ( $error, $query, $simple_query, $query_cgi,
652     $query_desc, $limit, $limit_cgi, $limit_desc,
653     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
654
655     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
656     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
657
658     $QueryStemming = $QueryWeightFields = 1;
659     $QueryFuzzy = $QueryAutoTruncate = 0;
660     ( $error, $query, $simple_query, $query_cgi,
661     $query_desc, $limit, $limit_cgi, $limit_desc,
662     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
663
664     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
665     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
666
667     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
668     ( $error, $query, $simple_query, $query_cgi,
669     $query_desc, $limit, $limit_cgi, $limit_desc,
670     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
671
672     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
673     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
674
675     ( $error, $query, $simple_query, $query_cgi,
676     $query_desc, $limit, $limit_cgi, $limit_desc,
677     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en');
678     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' );
679     is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' );
680
681     ( $error, $query, $simple_query, $query_cgi,
682     $query_desc, $limit, $limit_cgi, $limit_desc,
683     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
684     is($query, 'su,phr=0 ', 'buildQuery should keep 0 value');
685
686     # Bug 23086
687     ( $error, $query, $simple_query, $query_cgi,
688     $query_desc, $limit, $limit_cgi, $limit_desc,
689     $query_type ) = buildQuery([], [], [], [ 'mc-ccode:NF(IC'], [], 0, 'en');
690     like($query, qr/ccode="NF\(IC"/, "Limit quoted correctly");
691
692     # Let's see what happens when we pass bad data into these routines.
693     # We have to catch warnings since we're not very good about returning errors.
694
695     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
696         "SimpleSearch warns about CCL parsing error with nonsense query";
697     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
698
699     warning_like {( undef, $results_hashref, $facets_loop ) =
700         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'nonsense', undef) }
701         qr/Unknown query_type/, "getRecords warns about unknown query type";
702
703     warning_like {( undef, $results_hashref, $facets_loop ) =
704         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, '', undef) }
705         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
706
707     # Let's just test a few other bits and bobs, just for fun
708
709     ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
710     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
711         $results_hashref->{'biblioserver'}->{"RECORDS"});
712     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
713
714
715     ## Regression test for Bug 10741
716
717     # make one of the test items appear to be in transit
718     my $circ_module = new Test::MockModule('C4::Circulation');
719     $circ_module->mock('GetTransfers', sub {
720         my $itemnumber = shift // -1;
721         if ($itemnumber == 11) {
722             return ('2013-07-19', 'MPL', 'CPL');
723         } else {
724             return;
725         }
726     });
727
728     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
729     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
730         $results_hashref->{'biblioserver'}->{"RECORDS"});
731     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
732
733     ## Regression test for bug 10684
734     ( undef, $results_hashref, $facets_loop ) =
735         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
736     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
737     warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc,
738                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
739                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
740                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
741                 "Warning is raised correctly for invalid tags in MARC::Record";
742     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
743
744     # Testing exploding indexes
745     my $term;
746     my $searchmodule = new Test::MockModule('C4::Search');
747     $searchmodule->mock('SimpleSearch', sub {
748         my $query = shift;
749
750         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
751
752         my $record = MARC::Record->new;
753         if ($query =~ m/Arizona/) {
754             $record->add_fields(
755                 [ '001', '1234' ],
756                 [ '151', ' ', ' ', a => 'Arizona' ],
757                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
758                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
759                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
760                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
761                 [ '551', ' ', ' ', a => 'New Mexico' ],
762                 );
763         }
764         return '', [ $record->as_usmarc() ], 1;
765     });
766
767     $UseQueryParser = 1;
768     $term = 'Arizona';
769     ( $error, $query, $simple_query, $query_cgi,
770     $query_desc, $limit, $limit_cgi, $limit_desc,
771     $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
772     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
773
774     ( $error, $query, $simple_query, $query_cgi,
775     $query_desc, $limit, $limit_cgi, $limit_desc,
776     $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
777     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
778
779     ( $error, $query, $simple_query, $query_cgi,
780     $query_desc, $limit, $limit_cgi, $limit_desc,
781     $query_type ) = buildQuery([], [ $term ], [ 'su-rl' ], [  ], [], 0, 'en');
782     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
783
784     ( $error, $query, $simple_query, $query_cgi,
785     $query_desc, $limit, $limit_cgi, $limit_desc,
786     $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
787     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
788     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
789
790     ( $error, $query, $simple_query, $query_cgi,
791     $query_desc, $limit, $limit_cgi, $limit_desc,
792     $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
793     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
794     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
795
796     ( $error, $query, $simple_query, $query_cgi,
797     $query_desc, $limit, $limit_cgi, $limit_desc,
798     $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
799     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
800
801     ( $error, $query, $simple_query, $query_cgi,
802     $query_desc, $limit, $limit_cgi, $limit_desc,
803     $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
804     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
805
806     ( $error, $query, $simple_query, $query_cgi,
807     $query_desc, $limit, $limit_cgi, $limit_desc,
808     $query_type ) = buildQuery([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
809     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
810
811     ( $error, $query, $simple_query, $query_cgi,
812     $query_desc, $limit, $limit_cgi, $limit_desc,
813     $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
814     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
815     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
816
817     sub matchesExplodedTerms {
818         my ($message, $query, @terms) = @_;
819         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
820         like($query, qr/$match/, $message);
821     }
822
823     # authority records
824     use_ok('C4::AuthoritiesMarc');
825     $UseQueryParser = 0;
826
827     my ($auths, $count) = SearchAuthorities(
828         ['mainentry'], ['and'], [''], ['starts'],
829         ['shakespeare'], 0, 10, '', '', 1
830     );
831     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
832     ($auths, $count) = SearchAuthorities(
833         ['mainentry'], ['and'], [''], ['starts'],
834         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
835     );
836     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
837     ($auths, $count) = SearchAuthorities(
838         ['mainentry'], ['and'], [''], ['starts'],
839         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
840     );
841     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
842     ($auths, $count) = SearchAuthorities(
843         ['match'], ['and'], [''], ['contains'],
844         ['沙士北亞威廉姆'], 0, 10, '', '', 1
845     );
846     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
847     ($auths, $count) = SearchAuthorities(
848         ['LC-card-number'], ['and'], [''], ['contains'],
849         ['99282477'], 0, 10, '', '', 1
850     );
851     is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"');
852     ($auths, $count) = SearchAuthorities(
853         ['all'], ['and'], [''], ['contains'],
854         ['professional wrestler'], 0, 10, '', '', 1
855     );
856     is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"');
857
858     $UseQueryParser = 1;
859
860     ($auths, $count) = SearchAuthorities(
861         ['mainentry'], ['and'], [''], ['starts'],
862         ['shakespeare'], 0, 10, '', '', 1
863     );
864     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
865     ($auths, $count) = SearchAuthorities(
866         ['mainentry'], ['and'], [''], ['starts'],
867         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
868     );
869     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
870     ($auths, $count) = SearchAuthorities(
871         ['mainentry'], ['and'], [''], ['starts'],
872         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
873     );
874     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
875     ($auths, $count) = SearchAuthorities(
876         ['match'], ['and'], [''], ['contains'],
877         ['沙士北亞威廉姆'], 0, 10, '', '', 1
878     );
879     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
880
881     # retrieve records that are larger than the MARC limit of 99,999 octets
882     ( undef, $results_hashref, $facets_loop ) =
883         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
884     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
885     @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
886         $results_hashref->{'biblioserver'}->{"RECORDS"});
887     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
888     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
889     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
890
891     # notforloancount should be returned as part of searchResults output
892     ok( defined $newresults[0]->{notforloancount},
893         '\'notforloancount\' defined in searchResults output (Bug 12419)');
894     is( $newresults[0]->{notforloancount}, 2,
895         '\'notforloancount\' == 2 (Bug 12419)');
896
897     # verify that we don't attempt to sort if no results were returned
898     # because of a query error
899     warning_like {( undef, $results_hashref, $facets_loop ) =
900         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef)
901     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
902     
903     # Test facet calculation
904     my $facets_counter = {};
905     my $facets         = C4::Koha::getFacets();
906     # Create a record with a 100$z field
907     my $marc_record    = MARC::Record->new;
908     $marc_record->add_fields(
909         [ '001', '1234' ],
910         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
911         [ '100', 'z', ' ', a => 'Tomasito' ],
912         [ '245', ' ', ' ', a => 'First try' ]
913     );
914     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
915     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
916         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
917     $marc_record    = MARC::Record->new;
918     $marc_record->add_fields(
919         [ '001', '1234' ],
920         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
921         [ '100', 'z', ' ', a => 'Tomasito' ],
922         [ '245', ' ', ' ', a => 'Second try' ]
923     );
924     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
925     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
926         "_get_facets_data_from_record correctly counts author facet twice");
927
928     # Test _get_facets_info
929     my $facets_info = C4::Search::_get_facets_info( $facets );
930     my $expected_facets_info_marc21 = {
931                    'au' => { 'label_value' => "Authors" },
932                 'ccode' => { 'label_value' => "CollectionCodes" },
933         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
934                 'itype' => { 'label_value' => "ItemTypes" },
935              'location' => { 'label_value' => "Location" },
936                    'se' => { 'label_value' => "Series" },
937                'su-geo' => { 'label_value' => "Places" },
938                 'su-to' => { 'label_value' => "Topics" },
939                 'su-ut' => { 'label_value' => "Titles" }
940     };
941     delete $expected_facets_info_marc21->{holdingbranch}
942         if Koha::Libraries->count == 1;
943     is_deeply( $facets_info, $expected_facets_info_marc21,
944         "_get_facets_info returns the correct data");
945
946     cleanup();
947 }
948
949 sub run_unimarc_search_tests {
950     $datadir = tempdir();
951     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc");
952
953     Koha::Caches->get_instance('config')->flush_all;
954
955     mock_GetMarcSubfieldStructure('unimarc');
956     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
957     $context->set_context();
958
959     use_ok('C4::Search');
960
961     # set search syspreferences to a known starting point
962     $QueryStemming = 0;
963     $QueryAutoTruncate = 0;
964     $QueryWeightFields = 0;
965     $QueryFuzzy = 0;
966     $UseQueryParser = 0;
967     $marcflavour = 'UNIMARC';
968
969     index_sample_records_and_launch_zebra($datadir, 'unimarc');
970
971     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
972     is($total_hits, 1, 'UNIMARC title search');
973     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
974     is($total_hits, 1, 'UNIMARC target audience = u');
975     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
976     is($total_hits, 4, 'UNIMARC target audience = k');
977     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
978     is($total_hits, 3, 'UNIMARC target audience = m');
979     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
980     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
981
982     # authority records
983     use_ok('C4::AuthoritiesMarc');
984     $UseQueryParser = 0;
985
986     my ($auths, $count) = SearchAuthorities(
987         ['mainentry'], ['and'], [''], ['contains'],
988         ['wil'], 0, 10, '', '', 1
989     );
990     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
991     ($auths, $count) = SearchAuthorities(
992         ['match'], ['and'], [''], ['contains'],
993         ['wil'], 0, 10, '', '', 1
994     );
995     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
996     ($auths, $count) = SearchAuthorities(
997         ['mainentry'], ['and'], [''], ['contains'],
998         ['michel'], 0, 20, '', '', 1
999     );
1000     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
1001     ($auths, $count) = SearchAuthorities(
1002         ['mainmainentry'], ['and'], [''], ['exact'],
1003         ['valley'], 0, 20, '', '', 1
1004     );
1005     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
1006     ($auths, $count) = SearchAuthorities(
1007         ['mainmainentry'], ['and'], [''], ['exact'],
1008         ['vall'], 0, 20, '', '', 1
1009     );
1010     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
1011     ($auths, $count) = SearchAuthorities(
1012         ['Any'], ['and'], [''], ['starts'],
1013         ['jean'], 0, 30, '', '', 1
1014     );
1015     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
1016
1017     # Test _get_facets_info
1018     my $facets      = C4::Koha::getFacets();
1019     my $facets_info = C4::Search::_get_facets_info( $facets );
1020     my $expected_facets_info_unimarc = {
1021                    'au' => { 'label_value' => "Authors" },
1022                 'ccode' => { 'label_value' => "CollectionCodes" },
1023         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
1024              'location' => { 'label_value' => "Location" },
1025                    'se' => { 'label_value' => "Series" },
1026                'su-geo' => { 'label_value' => "Places" },
1027                 'su-to' => { 'label_value' => "Topics" }
1028     };
1029     delete $expected_facets_info_unimarc->{holdingbranch}
1030         if Koha::Libraries->count == 1;
1031     is_deeply( $facets_info, $expected_facets_info_unimarc,
1032         "_get_facets_info returns the correct data");
1033
1034     cleanup();
1035 }
1036
1037 subtest 'MARC21 + DOM' => sub {
1038     plan tests => 116;
1039     run_marc21_search_tests();
1040 };
1041
1042 subtest 'UNIMARC + DOM' => sub {
1043     plan tests => 14;
1044     run_unimarc_search_tests();
1045 };
1046
1047 # Make sure that following tests are not using our config settings
1048 Koha::Caches->get_instance('config')->flush_all;
1049