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