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