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