Bug 29364: Revert changes to framework visibility made by 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     # FIXME This change is revert in END
524     # Hide subfield 'p' in OPAC
525     $dbh->do(qq{
526         UPDATE marc_subfield_structure
527         SET hidden=4
528         WHERE frameworkcode='$fw' AND
529               tagfield=952 AND
530               tagsubfield='p';
531     });
532
533     # Hide subfield 'y' in Staff
534     $dbh->do(qq{
535         UPDATE marc_subfield_structure
536         SET hidden=-7
537         WHERE frameworkcode='$fw' AND
538               tagfield=952 AND
539               tagsubfield='y';
540     });
541
542     Koha::Caches->get_instance->flush_all;
543
544     @newresults = searchResults(
545         { 'interface' => 'opac' },
546         $query_desc,
547         $results_hashref->{'biblioserver'}->{'hits'},
548         17,
549         0,
550         0,
551         $results_hashref->{'biblioserver'}->{"RECORDS"}
552     );
553
554     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, '952\$p hidden in OPAC' );
555
556     @newresults = searchResults(
557         { 'interface' => 'intranet' },
558         $query_desc,
559         $results_hashref->{'biblioserver'}->{'hits'},
560         17,
561         0,
562         0,
563         $results_hashref->{'biblioserver'}->{"RECORDS"}
564     );
565
566     unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, '952\$y hidden on staff interface' );
567
568     ( $error, $query, $simple_query, $query_cgi,
569     $query_desc, $limit, $limit_cgi, $limit_desc,
570     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
571
572     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
573     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
574
575     ( $error, $query, $simple_query, $query_cgi,
576     $query_desc, $limit, $limit_cgi, $limit_desc,
577     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
578
579     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
580     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
581
582     ( $error, $query, $simple_query, $query_cgi,
583     $query_desc, $limit, $limit_cgi, $limit_desc,
584     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
585
586     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
587     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
588
589     ( $error, $query, $simple_query, $query_cgi,
590     $query_desc, $limit, $limit_cgi, $limit_desc,
591     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
592
593     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
594     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
595
596     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
597     $QueryWeightFields = 1;
598     ( $error, $query, $simple_query, $query_cgi,
599     $query_desc, $limit, $limit_cgi, $limit_desc,
600     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
601
602     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
603     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
604     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");
605
606     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
607     $QueryAutoTruncate = 1;
608     ( $error, $query, $simple_query, $query_cgi,
609     $query_desc, $limit, $limit_cgi, $limit_desc,
610     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
611
612     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
613     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
614
615     ( $error, $query, $simple_query, $query_cgi,
616     $query_desc, $limit, $limit_cgi, $limit_desc,
617     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
618
619     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
620     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
621
622     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
623     $QueryWeightFields = 1;
624     ( $error, $query, $simple_query, $query_cgi,
625     $query_desc, $limit, $limit_cgi, $limit_desc,
626     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
627     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
628     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
629
630     ( $error, $query, $simple_query, $query_cgi,
631     $query_desc, $limit, $limit_cgi, $limit_desc,
632     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
633     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
634     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
635
636     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
637     ( $error, $query, $simple_query, $query_cgi,
638     $query_desc, $limit, $limit_cgi, $limit_desc,
639     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
640
641     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
642     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
643
644     ( $error, $query, $simple_query, $query_cgi,
645     $query_desc, $limit, $limit_cgi, $limit_desc,
646     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
647
648     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
649     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
650
651     $QueryStemming = $QueryWeightFields = 1;
652     $QueryFuzzy = $QueryAutoTruncate = 0;
653     ( $error, $query, $simple_query, $query_cgi,
654     $query_desc, $limit, $limit_cgi, $limit_desc,
655     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
656
657     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
658     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
659
660     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
661     ( $error, $query, $simple_query, $query_cgi,
662     $query_desc, $limit, $limit_cgi, $limit_desc,
663     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
664
665     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
666     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
667
668     ( $error, $query, $simple_query, $query_cgi,
669     $query_desc, $limit, $limit_cgi, $limit_desc,
670     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en');
671     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' );
672     is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' );
673
674     ( $error, $query, $simple_query, $query_cgi,
675     $query_desc, $limit, $limit_cgi, $limit_desc,
676     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
677     is($query, 'su,phr=(rk=(0)) ', 'buildQuery should keep 0 value');
678
679     # Bug 23086
680     ( $error, $query, $simple_query, $query_cgi,
681     $query_desc, $limit, $limit_cgi, $limit_desc,
682     $query_type ) = buildQuery([], [], [], [ 'mc-ccode:NF(IC'], [], 0, 'en');
683     like($query, qr/ccode="NF\(IC"/, "Limit quoted correctly");
684
685     # Let's see what happens when we pass bad data into these routines.
686     # We have to catch warnings since we're not very good about returning errors.
687
688     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
689         "SimpleSearch warns about CCL parsing error with nonsense query";
690     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
691
692     warning_like {( undef, $results_hashref, $facets_loop ) =
693         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'nonsense', undef) }
694         qr/Unknown query_type/, "getRecords warns about unknown query type";
695
696     warning_like {( undef, $results_hashref, $facets_loop ) =
697         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, '', undef) }
698         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
699
700     # Let's just test a few other bits and bobs, just for fun
701
702     ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
703     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
704         $results_hashref->{'biblioserver'}->{"RECORDS"});
705     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
706
707
708     ## Regression test for Bug 10741
709
710     # make one of the test items appear to be in transit
711     my $circ_module = Test::MockModule->new('C4::Circulation');
712     $circ_module->mock('GetTransfers', sub {
713         my $itemnumber = shift // -1;
714         if ($itemnumber == 11) {
715             return ('2013-07-19', 'MPL', 'CPL');
716         } else {
717             return;
718         }
719     });
720
721     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
722     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
723         $results_hashref->{'biblioserver'}->{"RECORDS"});
724     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
725
726     ## Regression test for bug 10684
727     ( undef, $results_hashref, $facets_loop ) =
728         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
729     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
730     warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc,
731                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
732                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
733                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
734                 "Warning is raised correctly for invalid tags in MARC::Record";
735     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
736
737     my ($auths, $count) = SearchAuthorities(
738         ['mainentry'], ['and'], [''], ['starts'],
739         ['shakespeare'], 0, 10, '', '', 1
740     );
741     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
742     ($auths, $count) = SearchAuthorities(
743         ['mainentry'], ['and'], [''], ['starts'],
744         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
745     );
746     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
747     ($auths, $count) = SearchAuthorities(
748         ['mainentry'], ['and'], [''], ['starts'],
749         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
750     );
751     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
752     ($auths, $count) = SearchAuthorities(
753         ['match'], ['and'], [''], ['contains'],
754         ['沙士北亞威廉姆'], 0, 10, '', '', 1
755     );
756     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
757     ($auths, $count) = SearchAuthorities(
758         ['LC-card-number'], ['and'], [''], ['contains'],
759         ['99282477'], 0, 10, '', '', 1
760     );
761     is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"');
762     ($auths, $count) = SearchAuthorities(
763         ['all'], ['and'], [''], ['contains'],
764         ['professional wrestler'], 0, 10, '', '', 1
765     );
766     is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"');
767
768     # retrieve records that are larger than the MARC limit of 99,999 octets
769     ( undef, $results_hashref, $facets_loop ) =
770         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
771     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
772     @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
773         $results_hashref->{'biblioserver'}->{"RECORDS"});
774     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
775     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
776     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
777
778     # notforloancount should be returned as part of searchResults output
779     ok( defined $newresults[0]->{notforloancount},
780         '\'notforloancount\' defined in searchResults output (Bug 12419)');
781     is( $newresults[0]->{notforloancount}, 2,
782         '\'notforloancount\' == 2 (Bug 12419)');
783
784     # verify that we don't attempt to sort if no results were returned
785     # because of a query error
786     warning_like {( undef, $results_hashref, $facets_loop ) =
787         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef)
788     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
789     
790     # Test facet calculation
791     my $facets_counter = {};
792     my $facets         = C4::Koha::getFacets();
793     # Create a record with a 100$z field
794     my $marc_record    = MARC::Record->new;
795     $marc_record->add_fields(
796         [ '001', '1234' ],
797         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
798         [ '100', 'z', ' ', a => 'Tomasito' ],
799         [ '245', ' ', ' ', a => 'First try' ]
800     );
801     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
802     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
803         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
804     $marc_record    = MARC::Record->new;
805     $marc_record->add_fields(
806         [ '001', '1234' ],
807         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
808         [ '100', 'z', ' ', a => 'Tomasito' ],
809         [ '245', ' ', ' ', a => 'Second try' ]
810     );
811     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
812     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
813         "_get_facets_data_from_record correctly counts author facet twice");
814
815     # Test _get_facets_info
816     my $facets_info = C4::Search::_get_facets_info( $facets );
817     my $expected_facets_info_marc21 = {
818                    'au' => { 'label_value' => "Authors" },
819                 'ccode' => { 'label_value' => "CollectionCodes" },
820         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
821                 'itype' => { 'label_value' => "ItemTypes" },
822              'location' => { 'label_value' => "Location" },
823                    'se' => { 'label_value' => "Series" },
824                'su-geo' => { 'label_value' => "Places" },
825                 'su-to' => { 'label_value' => "Topics" },
826                 'su-ut' => { 'label_value' => "Titles" }
827     };
828     delete $expected_facets_info_marc21->{holdingbranch}
829         if Koha::Libraries->count == 1;
830     is_deeply( $facets_info, $expected_facets_info_marc21,
831         "_get_facets_info returns the correct data");
832
833     cleanup();
834 }
835
836 sub run_unimarc_search_tests {
837     $datadir = tempdir();
838     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc");
839
840     Koha::Caches->get_instance('config')->flush_all;
841
842     mock_GetMarcSubfieldStructure('unimarc');
843     my $context = C4::Context->new("$datadir/etc/koha-conf.xml");
844     $context->set_context();
845
846     use_ok('C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults ));
847
848     # set search syspreferences to a known starting point
849     $QueryStemming = 0;
850     $QueryAutoTruncate = 0;
851     $QueryWeightFields = 0;
852     $QueryFuzzy = 0;
853     $marcflavour = 'UNIMARC';
854
855     index_sample_records_and_launch_zebra($datadir, 'unimarc');
856
857     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
858     is($total_hits, 1, 'UNIMARC title search');
859     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
860     is($total_hits, 1, 'UNIMARC target audience = u');
861     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
862     is($total_hits, 4, 'UNIMARC target audience = k');
863     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
864     is($total_hits, 3, 'UNIMARC target audience = m');
865     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
866     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
867
868     # authority records
869     use_ok('C4::AuthoritiesMarc', qw( SearchAuthorities ));
870
871     my ($auths, $count) = SearchAuthorities(
872         ['mainentry'], ['and'], [''], ['contains'],
873         ['wil'], 0, 10, '', '', 1
874     );
875     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
876     ($auths, $count) = SearchAuthorities(
877         ['match'], ['and'], [''], ['contains'],
878         ['wil'], 0, 10, '', '', 1
879     );
880     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
881     ($auths, $count) = SearchAuthorities(
882         ['mainentry'], ['and'], [''], ['contains'],
883         ['michel'], 0, 20, '', '', 1
884     );
885     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
886     ($auths, $count) = SearchAuthorities(
887         ['mainmainentry'], ['and'], [''], ['exact'],
888         ['valley'], 0, 20, '', '', 1
889     );
890     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
891     ($auths, $count) = SearchAuthorities(
892         ['mainmainentry'], ['and'], [''], ['exact'],
893         ['vall'], 0, 20, '', '', 1
894     );
895     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
896     ($auths, $count) = SearchAuthorities(
897         ['Any'], ['and'], [''], ['starts'],
898         ['jean'], 0, 30, '', '', 1
899     );
900     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
901
902     # Test _get_facets_info
903     my $facets      = C4::Koha::getFacets();
904     my $facets_info = C4::Search::_get_facets_info( $facets );
905     my $expected_facets_info_unimarc = {
906                    'au' => { 'label_value' => "Authors" },
907                 'ccode' => { 'label_value' => "CollectionCodes" },
908         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
909              'location' => { 'label_value' => "Location" },
910                    'se' => { 'label_value' => "Series" },
911                'su-geo' => { 'label_value' => "Places" },
912                 'su-to' => { 'label_value' => "Topics" }
913     };
914     delete $expected_facets_info_unimarc->{holdingbranch}
915         if Koha::Libraries->count == 1;
916     is_deeply( $facets_info, $expected_facets_info_unimarc,
917         "_get_facets_info returns the correct data");
918
919     cleanup();
920 }
921
922 subtest 'MARC21 + DOM' => sub {
923     plan tests => 88;
924     run_marc21_search_tests();
925 };
926
927 subtest 'UNIMARC + DOM' => sub {
928     plan tests => 14;
929     run_unimarc_search_tests();
930 };
931
932
933 subtest 'FindDuplicate' => sub {
934     plan tests => 6;
935     Koha::Caches->get_instance('config')->flush_all;
936     t::lib::Mocks::mock_preference('marcflavour', 'marc21' );
937     mock_GetMarcSubfieldStructure('marc21');
938     my $z_searcher = Test::MockModule->new('C4::Search');
939     $z_searcher->mock('SimpleSearch', sub {
940         warn shift @_;
941         return 1;
942     });
943     my $e_searcher = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search');
944     $e_searcher->mock('simple_search_compat', sub {
945         shift @_;
946         warn shift @_;
947         return 1;
948     });
949
950     my $record_1 = MARC::Record->new;
951     $record_1 ->add_fields(
952             [ '100', '0', '0', a => 'Morgenstern, Erin' ],
953             [ '245', '0', '0', a => 'The night circus /' ]
954     );
955     my $record_2 = MARC::Record->new;
956     $record_2 ->add_fields(
957             [ '245', '0', '0', a => 'The book of nothing /' ]
958     );
959     my $record_3 = MARC::Record->new;
960     $record_3->add_fields(
961             [ '245', '0', '0', a => 'Frog and toad all year /' ]
962     );
963
964     foreach my $engine ('Zebra','Elasticsearch'){
965         t::lib::Mocks::mock_preference('searchEngine', $engine );
966
967         warning_is { C4::Search::FindDuplicate($record_1);}
968             q/ti,ext:"The night circus \/" and au,ext:"Morgenstern, Erin"/,"Term correctly formed and passed to $engine";
969
970         warning_is { C4::Search::FindDuplicate($record_2);}
971             q/ti,ext:"The book of nothing \/"/,"Term correctly formed and passed to $engine";
972
973         warning_is { C4::Search::FindDuplicate($record_3);}
974             q/ti,ext:"Frog and toad all year \/"/,"Term correctly formed and passed to $engine";
975     }
976
977 };
978
979 # Make sure that following tests are not using our config settings
980 Koha::Caches->get_instance('config')->flush_all;
981
982 END {
983     my $dbh = C4::Context->dbh;
984     # Restore visibility of subfields in OPAC
985     $dbh->do(q{
986         UPDATE marc_subfield_structure
987         SET hidden=0
988         WHERE tagfield=952 AND
989               ( tagsubfield IN ('p', 'y') )
990     });
991
992     Koha::Caches->get_instance->flush_all;
993 };