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