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