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