Bug 31196: Remove 'default_value_for_mod_marc-' clear_from_cache calls
[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
297     $record->add_fields(
298             [ '100', '1', ' ', a => 'Carter, Philip J.' ],
299             [ '245', '1', '4', a => 'Test your emotional intelligence :' ]
300             );
301     ($biblionumber,undef,$title) = FindDuplicate($record);
302     is($biblionumber, 203, 'Found duplicate with author/title');
303
304     # Testing SimpleSearch
305
306     my ( $error, $marcresults, $total_hits ) = SimpleSearch("book", 0, 9);
307
308     is(scalar @$marcresults, 9, "SimpleSearch retrieved requested number of records");
309     is($total_hits, 101, "SimpleSearch for 'book' matched right number of records");
310     is($error, undef, "SimpleSearch does not return an error when successful");
311
312     my $marcresults2;
313     ( $error, $marcresults2, $total_hits ) = SimpleSearch("book", 5, 5);
314     is($marcresults->[5], $marcresults2->[0], "SimpleSearch cursor functions");
315
316     ( $error, $marcresults, $total_hits ) = SimpleSearch("kw=book", 0, 10);
317     is($total_hits, 101, "SimpleSearch handles simple CCL");
318
319     ( $error, $marcresults, $total_hits ) = SimpleSearch("Music-number=49631-2", 0, 10);
320     is($total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)");
321     ( $error, $marcresults, $total_hits ) = SimpleSearch("Identifier-publisher-for-music=49631-2", 0, 10);
322     is($total_hits, 1, "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)");
323
324     # Testing getRecords
325
326     my $results_hashref;
327     my $facets_loop;
328     ( undef, $results_hashref, $facets_loop ) =
329         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
330     is($results_hashref->{biblioserver}->{hits}, 101, "getRecords keyword search for 'book' matched right number of records");
331     is(scalar @{$results_hashref->{biblioserver}->{RECORDS}}, 19, "getRecords returned requested number of records");
332     my $record5 = $results_hashref->{biblioserver}->{RECORDS}->[5];
333     ( undef, $results_hashref, $facets_loop ) =
334         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '20', 5, \%branches, \%itemtypes, 'ccl', undef);
335     ok(!defined $results_hashref->{biblioserver}->{RECORDS}->[0] &&
336         !defined $results_hashref->{biblioserver}->{RECORDS}->[1] &&
337         !defined $results_hashref->{biblioserver}->{RECORDS}->[2] &&
338         !defined $results_hashref->{biblioserver}->{RECORDS}->[3] &&
339         !defined $results_hashref->{biblioserver}->{RECORDS}->[4] &&
340         $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works");
341
342     ( undef, $results_hashref, $facets_loop ) =
343         getRecords('ti:book', 'ti:book', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
344     is($results_hashref->{biblioserver}->{hits}, 11, "getRecords title search for 'book' matched right number of records");
345
346     ( undef, $results_hashref, $facets_loop ) =
347         getRecords('au:Lessig', 'au:Lessig', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
348     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords title search for 'Australia' matched right number of records");
349
350 ( undef, $results_hashref, $facets_loop ) =
351     getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
352 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Efectos del ambiente/ &&
353     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' &&
354     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
355     , "Simple relevance sorting in getRecords matches old behavior");
356
357 ( undef, $results_hashref, $facets_loop ) =
358     getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef);
359 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/ &&
360     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[6],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
361     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'World health statistics 2009^ien'
362     , "Simple ascending author sorting in getRecords matches old behavior");
363
364 ( undef, $results_hashref, $facets_loop ) =
365     getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef);
366 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
367     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[12],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
368     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/
369     , "Simple descending author sorting in getRecords matches old behavior");
370
371 ( undef, $results_hashref, $facets_loop ) =
372     getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef);
373 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies' &&
374     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ &&
375     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
376     , "Simple ascending publication date sorting in getRecords matches old behavior");
377
378 ( undef, $results_hashref, $facets_loop ) =
379     getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef);
380 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Estado de salud/ &&
381     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
382     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies'
383     , "Simple descending publication date sorting in getRecords matches old behavior");
384
385     ( undef, $results_hashref, $facets_loop ) =
386         getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, undef, 1);
387     $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]);
388     is($record->title_proper(), 'Books', "Scan returned requested item");
389     is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term");
390     # Time to test buildQuery and searchResults too.
391
392     my ( $query, $simple_query, $query_cgi,
393     $query_desc, $limit, $limit_cgi, $limit_desc,
394     $query_type );
395     ( $error, $query, $simple_query, $query_cgi,
396     $query_desc, $limit, $limit_cgi, $limit_desc,
397     $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en');
398     like($query, qr/kw\W.*salud/, "Built CCL keyword query");
399
400     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
401     is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records");
402
403     my @newresults = searchResults({'interface' => 'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0,
404         $results_hashref->{'biblioserver'}->{"RECORDS"});
405     is(scalar @newresults,18, "searchResults returns requested number of hits");
406
407     ( $error, $query, $simple_query, $query_cgi,
408     $query_desc, $limit, $limit_cgi, $limit_desc,
409     $query_type ) = buildQuery([ 'AND' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
410     like($query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query");
411
412     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
413     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records");
414
415     ( $error, $query, $simple_query, $query_cgi,
416     $query_desc, $limit, $limit_cgi, $limit_desc,
417     $query_type ) = buildQuery([ 'OR' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
418     like($query, qr/kw\W.*salud\W.*OR.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query");
419
420     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
421     is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records");
422
423     ( $error, $query, $simple_query, $query_cgi,
424     $query_desc, $limit, $limit_cgi, $limit_desc,
425     $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
426     like($query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query");
427
428     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
429     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records");
430
431     ( $error, $query, $simple_query, $query_cgi,
432     $query_desc, $limit, $limit_cgi, $limit_desc,
433     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en');
434     like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly");
435     unlike($query_desc, qr/Laboratorios/, "Facets not included in query description");
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}, 2, "getRecords generated faceted search matched right number of records");
439
440
441     ( $error, $query, $simple_query, $query_cgi,
442     $query_desc, $limit, $limit_cgi, $limit_desc,
443     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en');
444
445     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
446     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records");
447
448
449     ( $error, $query, $simple_query, $query_cgi,
450     $query_desc, $limit, $limit_cgi, $limit_desc,
451     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en');
452
453     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
454     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated multi-faceted search matched right number of records");
455
456     ( $error, $query, $simple_query, $query_cgi,
457     $query_desc, $limit, $limit_cgi, $limit_desc,
458     $query_type ) = buildQuery([], [ 'NEKLS' ], [ 'Code-institution' ], [], [], 0, 'en');
459     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
460     is($results_hashref->{biblioserver}->{hits}, 12,
461        'search using index whose name contains "ns" returns expected results (bug 10271)');
462
463     ( $error, $query, $simple_query, $query_cgi,
464     $query_desc, $limit, $limit_cgi, $limit_desc,
465     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
466
467     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
468     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated availability-limited search matched right number of records");
469
470     {
471         my $mock_items = Test::MockModule->new('Koha::Items');
472         $mock_items->mock( 'count', 1 );
473         @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
474             $results_hashref->{'biblioserver'}->{"RECORDS"});
475         my $allavailable = 'true';
476         foreach my $result (@newresults) {
477             $allavailable = 'false' unless $result->{availablecount} > 0;
478         }
479         is ($allavailable, 'true', 'All records have at least one item available');
480     }
481
482     my $mocked_xslt = Test::MockModule->new('Koha::XSLT::Base');
483     $mocked_xslt->mock( 'transform', sub {
484         my ($self, $xml) = @_;
485         return $xml;
486     });
487
488     @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
489         $results_hashref->{'biblioserver'}->{"RECORDS"}, { anonymous_session => 1 });
490
491     like( $newresults[0]->{XSLTResultsRecord}, qr/<variable name="anonymous_session">1<\/variable>/, "Variable injected correctly" );
492
493     my $biblio_id = $newresults[0]->{biblionumber};
494     my $fw = C4::Biblio::GetFrameworkCode($biblio_id) // '';
495
496     my $dbh = C4::Context->dbh;
497     # FIXME This change is revert in END
498     # Hide subfield 'p' in OPAC
499     $dbh->do(qq{
500         UPDATE marc_subfield_structure
501         SET hidden=4
502         WHERE frameworkcode='$fw' AND
503               tagfield=952 AND
504               tagsubfield='p';
505     });
506
507     # Hide subfield 'y' in Staff
508     $dbh->do(qq{
509         UPDATE marc_subfield_structure
510         SET hidden=-7
511         WHERE frameworkcode='$fw' AND
512               tagfield=952 AND
513               tagsubfield='y';
514     });
515
516     Koha::Caches->get_instance->flush_all;
517
518     @newresults = searchResults(
519         { 'interface' => 'opac' },
520         $query_desc,
521         $results_hashref->{'biblioserver'}->{'hits'},
522         17,
523         0,
524         0,
525         $results_hashref->{'biblioserver'}->{"RECORDS"}
526     );
527
528     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, '952\$p hidden in OPAC' );
529
530     @newresults = searchResults(
531         { 'interface' => 'intranet' },
532         $query_desc,
533         $results_hashref->{'biblioserver'}->{'hits'},
534         17,
535         0,
536         0,
537         $results_hashref->{'biblioserver'}->{"RECORDS"}
538     );
539
540     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, '952\$y hidden on staff interface' );
541
542     ( $error, $query, $simple_query, $query_cgi,
543     $query_desc, $limit, $limit_cgi, $limit_desc,
544     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
545
546     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
547     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
548
549     ( $error, $query, $simple_query, $query_cgi,
550     $query_desc, $limit, $limit_cgi, $limit_desc,
551     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
552
553     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
554     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
555
556     ( $error, $query, $simple_query, $query_cgi,
557     $query_desc, $limit, $limit_cgi, $limit_desc,
558     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
559
560     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
561     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
562
563     ( $error, $query, $simple_query, $query_cgi,
564     $query_desc, $limit, $limit_cgi, $limit_desc,
565     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
566
567     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
568     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
569
570     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
571     $QueryWeightFields = 1;
572     ( $error, $query, $simple_query, $query_cgi,
573     $query_desc, $limit, $limit_cgi, $limit_desc,
574     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 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}, 19, "Weighted query returned correct number of results");
578     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");
579
580     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
581     $QueryAutoTruncate = 1;
582     ( $error, $query, $simple_query, $query_cgi,
583     $query_desc, $limit, $limit_cgi, $limit_desc,
584     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
585
586     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
587     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
588
589     ( $error, $query, $simple_query, $query_cgi,
590     $query_desc, $limit, $limit_cgi, $limit_desc,
591     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
592
593     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
594     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
595
596     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
597     $QueryWeightFields = 1;
598     ( $error, $query, $simple_query, $query_cgi,
599     $query_desc, $limit, $limit_cgi, $limit_desc,
600     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
601     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
602     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
603
604     ( $error, $query, $simple_query, $query_cgi,
605     $query_desc, $limit, $limit_cgi, $limit_desc,
606     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
607     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
608     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
609
610     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
611     ( $error, $query, $simple_query, $query_cgi,
612     $query_desc, $limit, $limit_cgi, $limit_desc,
613     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
614
615     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
616     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
617
618     ( $error, $query, $simple_query, $query_cgi,
619     $query_desc, $limit, $limit_cgi, $limit_desc,
620     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
621
622     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
623     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
624
625     $QueryStemming = $QueryWeightFields = 1;
626     $QueryFuzzy = $QueryAutoTruncate = 0;
627     ( $error, $query, $simple_query, $query_cgi,
628     $query_desc, $limit, $limit_cgi, $limit_desc,
629     $query_type ) = buildQuery([], [ 'pressed' ], [ '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}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
633
634     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
635     ( $error, $query, $simple_query, $query_cgi,
636     $query_desc, $limit, $limit_cgi, $limit_desc,
637     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
638
639     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
640     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
641
642     ( $error, $query, $simple_query, $query_cgi,
643     $query_desc, $limit, $limit_cgi, $limit_desc,
644     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en');
645     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' );
646     is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' );
647
648     ( $error, $query, $simple_query, $query_cgi,
649     $query_desc, $limit, $limit_cgi, $limit_desc,
650     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['branch:CPL'], [], 0, 'en');
651     is( $query, "an:42 and (homebranch: CPL or holdingbranch: CPL)", 'buildQuery should expand the limit as necessary for ccl queries' );
652     is( $query_desc, 'an:42', 'buildQuery should not add limit to limit desc for ccl queries' );
653
654     ( $error, $query, $simple_query, $query_cgi,
655     $query_desc, $limit, $limit_cgi, $limit_desc,
656     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
657     is($query, 'su,phr=(rk=(0)) ', 'buildQuery should keep 0 value in query');
658     is($query_cgi, 'idx=su%2Cphr&q=0', 'buildQuery should keep 0 value in query_cgi');
659     is($query_desc, 'su,phr: 0', 'buildQuery should keep 0 value in query_desc');
660
661     # Bug 23086
662     ( $error, $query, $simple_query, $query_cgi,
663     $query_desc, $limit, $limit_cgi, $limit_desc,
664     $query_type ) = buildQuery([], [], [], [ 'mc-ccode:NF(IC'], [], 0, 'en');
665     like($query, qr/ccode="NF\(IC"/, "Limit quoted correctly");
666
667     # Let's see what happens when we pass bad data into these routines.
668     # We have to catch warnings since we're not very good about returning errors.
669
670     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
671         "SimpleSearch warns about CCL parsing error with nonsense query";
672     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
673
674     warning_like {( undef, $results_hashref, $facets_loop ) =
675         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'nonsense', undef) }
676         qr/Unknown query_type/, "getRecords warns about unknown query type";
677
678     warning_like {( undef, $results_hashref, $facets_loop ) =
679         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, '', undef) }
680         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
681
682     # Let's just test a few other bits and bobs, just for fun
683
684     ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
685     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
686         $results_hashref->{'biblioserver'}->{"RECORDS"});
687     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
688
689
690     ## Regression test for Bug 10741
691
692     # make one of the test items appear to be in transit
693     my $circ_module = Test::MockModule->new('C4::Circulation');
694     my $builder = t::lib::TestBuilder->new;
695     my $transfer = $builder->build(
696         {
697             source => 'Branchtransfer',
698             value => {
699                 itemnumber => 11,
700                 frombranch => 'MPL',
701                 tobranch => 'CPL',
702                 datesent => \'NOW()'
703             }
704         }
705     );
706
707     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
708     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
709         $results_hashref->{'biblioserver'}->{"RECORDS"});
710     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
711
712     ## Regression test for bug 10684
713     ( undef, $results_hashref, $facets_loop ) =
714         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
715     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
716     warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc,
717                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
718                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
719                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
720                 "Warning is raised correctly for invalid tags in MARC::Record";
721     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
722
723     my ($auths, $count) = SearchAuthorities(
724         ['mainentry'], ['and'], [''], ['starts'],
725         ['shakespeare'], 0, 10, '', '', 1
726     );
727     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
728     ($auths, $count) = SearchAuthorities(
729         ['mainentry'], ['and'], [''], ['starts'],
730         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
731     );
732     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
733     ($auths, $count) = SearchAuthorities(
734         ['mainentry'], ['and'], [''], ['starts'],
735         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
736     );
737     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
738     ($auths, $count) = SearchAuthorities(
739         ['match'], ['and'], [''], ['contains'],
740         ['沙士北亞威廉姆'], 0, 10, '', '', 1
741     );
742     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
743     ($auths, $count) = SearchAuthorities(
744         ['LC-card-number'], ['and'], [''], ['contains'],
745         ['99282477'], 0, 10, '', '', 1
746     );
747     is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"');
748     ($auths, $count) = SearchAuthorities(
749         ['all'], ['and'], [''], ['contains'],
750         ['professional wrestler'], 0, 10, '', '', 1
751     );
752     is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"');
753
754     # retrieve records that are larger than the MARC limit of 99,999 octets
755     ( undef, $results_hashref, $facets_loop ) =
756         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
757     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
758
759     {
760         my $mock_items = Test::MockModule->new('Koha::Items');
761         $mock_items->mock( 'count', 1 );
762         @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
763             $results_hashref->{'biblioserver'}->{"RECORDS"});
764         is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
765         is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
766         like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
767     }
768
769     # notforloancount should be returned as part of searchResults output
770     ok( defined $newresults[0]->{notforloancount},
771         '\'notforloancount\' defined in searchResults output (Bug 12419)');
772     is( $newresults[0]->{notforloancount}, 2,
773         '\'notforloancount\' == 2 (Bug 12419)');
774
775     # verify that we don't attempt to sort if no results were returned
776     # because of a query error
777     warning_like {( undef, $results_hashref, $facets_loop ) =
778         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef)
779     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
780     
781     # Test facet calculation
782     my $facets_counter = {};
783     my $facets         = C4::Koha::getFacets();
784     # Create a record with a 100$z field
785     my $marc_record    = MARC::Record->new;
786     $marc_record->add_fields(
787         [ '001', '1234' ],
788         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
789         [ '100', 'z', ' ', a => 'Tomasito' ],
790         [ '245', ' ', ' ', a => 'First try' ]
791     );
792     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
793     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
794         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
795     $marc_record    = MARC::Record->new;
796     $marc_record->add_fields(
797         [ '001', '1234' ],
798         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
799         [ '100', 'z', ' ', a => 'Tomasito' ],
800         [ '245', ' ', ' ', a => 'Second try' ]
801     );
802     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
803     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
804         "_get_facets_data_from_record correctly counts author facet twice");
805
806     # Test _get_facets_info
807     my $facets_info = C4::Search::_get_facets_info( $facets );
808     my $expected_facets_info_marc21 = {
809                    'au' => { 'label_value' => "Authors" },
810                 'ccode' => { 'label_value' => "CollectionCodes" },
811         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
812                 'itype' => { 'label_value' => "ItemTypes" },
813              'location' => { 'label_value' => "Location" },
814                    'se' => { 'label_value' => "Series" },
815                'su-geo' => { 'label_value' => "Places" },
816                 'su-to' => { 'label_value' => "Topics" },
817                 'su-ut' => { 'label_value' => "Titles" }
818     };
819     delete $expected_facets_info_marc21->{holdingbranch}
820         if Koha::Libraries->count == 1;
821     is_deeply( $facets_info, $expected_facets_info_marc21,
822         "_get_facets_info returns the correct data");
823
824     $mock_zebra->cleanup;
825 }
826
827 sub run_unimarc_search_tests {
828
829     $marcflavour = 'UNIMARC';
830     my $mock_zebra = t::lib::Mocks::Zebra->new({marcflavour => $marcflavour});
831     push @cleanup, $mock_zebra;
832
833     mock_GetMarcSubfieldStructure($marcflavour);
834
835     use_ok('C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults ));
836
837     # set search syspreferences to a known starting point
838     $QueryStemming = 0;
839     $QueryAutoTruncate = 0;
840     $QueryWeightFields = 0;
841     $QueryFuzzy = 0;
842
843     my $sourcedir = dirname(__FILE__) . "/data";
844     $mock_zebra->load_records(
845         sprintf( "%s/%s/zebraexport/biblio", $sourcedir, lc($marcflavour) ),
846         'iso2709', 'biblios', 1 );
847     $mock_zebra->load_records(
848         sprintf(
849             "%s/%s/zebraexport/large_biblio",
850             $sourcedir, lc($marcflavour)
851         ),
852         'marcxml', 'biblios', 0
853     );
854     $mock_zebra->load_records(
855         sprintf( "%s/%s/zebraexport/authority", $sourcedir, lc($marcflavour) ),
856         'iso2709', 'authorities', 1
857     );
858     $mock_zebra->launch_zebra;
859
860     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
861     is($total_hits, 1, 'UNIMARC title search');
862     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
863     is($total_hits, 1, 'UNIMARC target audience = u');
864     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
865     is($total_hits, 4, 'UNIMARC target audience = k');
866     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
867     is($total_hits, 3, 'UNIMARC target audience = m');
868     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
869     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
870
871     # authority records
872     use_ok('C4::AuthoritiesMarc', qw( SearchAuthorities ));
873
874     my ($auths, $count) = SearchAuthorities(
875         ['mainentry'], ['and'], [''], ['contains'],
876         ['wil'], 0, 10, '', '', 1
877     );
878     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
879     ($auths, $count) = SearchAuthorities(
880         ['match'], ['and'], [''], ['contains'],
881         ['wil'], 0, 10, '', '', 1
882     );
883     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
884     ($auths, $count) = SearchAuthorities(
885         ['mainentry'], ['and'], [''], ['contains'],
886         ['michel'], 0, 20, '', '', 1
887     );
888     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
889     ($auths, $count) = SearchAuthorities(
890         ['mainmainentry'], ['and'], [''], ['exact'],
891         ['valley'], 0, 20, '', '', 1
892     );
893     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
894     ($auths, $count) = SearchAuthorities(
895         ['mainmainentry'], ['and'], [''], ['exact'],
896         ['vall'], 0, 20, '', '', 1
897     );
898     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
899     ($auths, $count) = SearchAuthorities(
900         ['Any'], ['and'], [''], ['starts'],
901         ['jean'], 0, 30, '', '', 1
902     );
903     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
904
905     # Test _get_facets_info
906     my $facets      = C4::Koha::getFacets();
907     my $facets_info = C4::Search::_get_facets_info( $facets );
908     my $expected_facets_info_unimarc = {
909                    'au' => { 'label_value' => "Authors" },
910                 'ccode' => { 'label_value' => "CollectionCodes" },
911         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
912              'location' => { 'label_value' => "Location" },
913                    'se' => { 'label_value' => "Series" },
914                'su-geo' => { 'label_value' => "Places" },
915                 'su-to' => { 'label_value' => "Topics" }
916     };
917     delete $expected_facets_info_unimarc->{holdingbranch}
918         if Koha::Libraries->count == 1;
919     is_deeply( $facets_info, $expected_facets_info_unimarc,
920         "_get_facets_info returns the correct data");
921
922     $mock_zebra->cleanup;
923 }
924
925 subtest 'MARC21 + DOM' => sub {
926     plan tests => 92;
927     run_marc21_search_tests();
928 };
929
930 subtest 'UNIMARC + DOM' => sub {
931     plan tests => 14;
932     run_unimarc_search_tests();
933 };
934
935
936 subtest 'FindDuplicate' => sub {
937     plan tests => 6;
938     Koha::Caches->get_instance('config')->flush_all;
939     t::lib::Mocks::mock_preference('marcflavour', 'MARC21' );
940     mock_GetMarcSubfieldStructure('MARC21');
941     my $z_searcher = Test::MockModule->new('C4::Search');
942     $z_searcher->mock('SimpleSearch', sub {
943         warn shift @_;
944         return 1;
945     });
946     my $e_searcher = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search');
947     $e_searcher->mock('simple_search_compat', sub {
948         shift @_;
949         warn shift @_;
950         return 1;
951     });
952
953     my $record_1 = MARC::Record->new;
954     $record_1 ->add_fields(
955             [ '100', '0', '0', a => 'Morgenstern, Erin' ],
956             [ '245', '0', '0', a => 'The night circus /' ]
957     );
958     my $record_2 = MARC::Record->new;
959     $record_2 ->add_fields(
960             [ '245', '0', '0', a => 'The book of nothing /' ]
961     );
962     my $record_3 = MARC::Record->new;
963     $record_3->add_fields(
964             [ '245', '0', '0', a => 'Frog and toad all year /' ]
965     );
966
967     foreach my $engine ('Zebra','Elasticsearch'){
968         t::lib::Mocks::mock_preference('searchEngine', $engine );
969
970         warning_is { C4::Search::FindDuplicate($record_1);}
971             q/ti,ext:"The night circus \/" AND au,ext:"Morgenstern, Erin"/,"Term correctly formed and passed to $engine";
972
973         warning_is { C4::Search::FindDuplicate($record_2);}
974             q/ti,ext:"The book of nothing \/"/,"Term correctly formed and passed to $engine";
975
976         warning_is { C4::Search::FindDuplicate($record_3);}
977             q/ti,ext:"Frog and toad all year \/"/,"Term correctly formed and passed to $engine";
978     }
979
980 };
981
982 # Make sure that following tests are not using our config settings
983 Koha::Caches->get_instance('config')->flush_all;
984
985 END {
986
987     $_->cleanup for @cleanup;
988     my $dbh = C4::Context->dbh;
989     # Restore visibility of subfields in OPAC
990     $dbh->do(q{
991         UPDATE marc_subfield_structure
992         SET hidden=0
993         WHERE tagfield=952 AND
994               ( tagsubfield IN ('p', 'y') )
995     });
996
997     Koha::Caches->get_instance->flush_all;
998 };