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