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