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