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