Bug 25416: (follow-up) Remove useless use statement
[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     ( $error, $query, $simple_query, $query_cgi,
507     $query_desc, $limit, $limit_cgi, $limit_desc,
508     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
509
510     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
511     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
512
513     ( $error, $query, $simple_query, $query_cgi,
514     $query_desc, $limit, $limit_cgi, $limit_desc,
515     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
516
517     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
518     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
519
520     ( $error, $query, $simple_query, $query_cgi,
521     $query_desc, $limit, $limit_cgi, $limit_desc,
522     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
523
524     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
525     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
526
527     ( $error, $query, $simple_query, $query_cgi,
528     $query_desc, $limit, $limit_cgi, $limit_desc,
529     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
530
531     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
532     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
533
534     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
535     $QueryWeightFields = 1;
536     ( $error, $query, $simple_query, $query_cgi,
537     $query_desc, $limit, $limit_cgi, $limit_desc,
538     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
539
540     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
541     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
542     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");
543
544     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
545     $QueryAutoTruncate = 1;
546     ( $error, $query, $simple_query, $query_cgi,
547     $query_desc, $limit, $limit_cgi, $limit_desc,
548     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
549
550     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
551     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
552
553     ( $error, $query, $simple_query, $query_cgi,
554     $query_desc, $limit, $limit_cgi, $limit_desc,
555     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
556
557     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
558     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
559
560     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
561     $QueryWeightFields = 1;
562     ( $error, $query, $simple_query, $query_cgi,
563     $query_desc, $limit, $limit_cgi, $limit_desc,
564     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
565     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
566     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
567
568     ( $error, $query, $simple_query, $query_cgi,
569     $query_desc, $limit, $limit_cgi, $limit_desc,
570     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
571     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
572     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
573
574     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
575     ( $error, $query, $simple_query, $query_cgi,
576     $query_desc, $limit, $limit_cgi, $limit_desc,
577     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 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}, undef, "Search for 'medic' returns no matches with automatic truncation off");
581
582     ( $error, $query, $simple_query, $query_cgi,
583     $query_desc, $limit, $limit_cgi, $limit_desc,
584     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
585
586     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
587     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
588
589     $QueryStemming = $QueryWeightFields = 1;
590     $QueryFuzzy = $QueryAutoTruncate = 0;
591     ( $error, $query, $simple_query, $query_cgi,
592     $query_desc, $limit, $limit_cgi, $limit_desc,
593     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
594
595     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
596     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
597
598     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
599     ( $error, $query, $simple_query, $query_cgi,
600     $query_desc, $limit, $limit_cgi, $limit_desc,
601     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
602
603     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
604     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
605
606     ( $error, $query, $simple_query, $query_cgi,
607     $query_desc, $limit, $limit_cgi, $limit_desc,
608     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en');
609     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' );
610     is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' );
611
612     ( $error, $query, $simple_query, $query_cgi,
613     $query_desc, $limit, $limit_cgi, $limit_desc,
614     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
615     is($query, 'su,phr=0 ', 'buildQuery should keep 0 value');
616
617     # Let's see what happens when we pass bad data into these routines.
618     # We have to catch warnings since we're not very good about returning errors.
619
620     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
621         "SimpleSearch warns about CCL parsing error with nonsense query";
622     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
623
624     warning_like {( undef, $results_hashref, $facets_loop ) =
625         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'nonsense', undef) }
626         qr/Unknown query_type/, "getRecords warns about unknown query type";
627
628     warning_like {( undef, $results_hashref, $facets_loop ) =
629         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, '', undef) }
630         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
631
632     # Let's just test a few other bits and bobs, just for fun
633
634     ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
635     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
636         $results_hashref->{'biblioserver'}->{"RECORDS"});
637     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
638
639
640     ## Regression test for Bug 10741
641
642     # make one of the test items appear to be in transit
643     my $circ_module = new Test::MockModule('C4::Circulation');
644     $circ_module->mock('GetTransfers', sub {
645         my $itemnumber = shift // -1;
646         if ($itemnumber == 11) {
647             return ('2013-07-19', 'MPL', 'CPL');
648         } else {
649             return;
650         }
651     });
652
653     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0);
654     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
655         $results_hashref->{'biblioserver'}->{"RECORDS"});
656     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
657
658     ## Regression test for bug 10684
659     ( undef, $results_hashref, $facets_loop ) =
660         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef);
661     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
662     warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc,
663                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
664                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
665                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
666                 "Warning is raised correctly for invalid tags in MARC::Record";
667     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
668
669     my ($auths, $count) = SearchAuthorities(
670         ['mainentry'], ['and'], [''], ['starts'],
671         ['shakespeare'], 0, 10, '', '', 1
672     );
673     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
674     ($auths, $count) = SearchAuthorities(
675         ['mainentry'], ['and'], [''], ['starts'],
676         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
677     );
678     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
679     ($auths, $count) = SearchAuthorities(
680         ['mainentry'], ['and'], [''], ['starts'],
681         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
682     );
683     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
684     ($auths, $count) = SearchAuthorities(
685         ['match'], ['and'], [''], ['contains'],
686         ['沙士北亞威廉姆'], 0, 10, '', '', 1
687     );
688     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
689     ($auths, $count) = SearchAuthorities(
690         ['LC-card-number'], ['and'], [''], ['contains'],
691         ['99282477'], 0, 10, '', '', 1
692     );
693     is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"');
694     ($auths, $count) = SearchAuthorities(
695         ['all'], ['and'], [''], ['contains'],
696         ['professional wrestler'], 0, 10, '', '', 1
697     );
698     is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"');
699
700     # retrieve records that are larger than the MARC limit of 99,999 octets
701     ( undef, $results_hashref, $facets_loop ) =
702         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef);
703     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
704     @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
705         $results_hashref->{'biblioserver'}->{"RECORDS"});
706     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
707     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
708     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
709
710     # notforloancount should be returned as part of searchResults output
711     ok( defined $newresults[0]->{notforloancount},
712         '\'notforloancount\' defined in searchResults output (Bug 12419)');
713     is( $newresults[0]->{notforloancount}, 2,
714         '\'notforloancount\' == 2 (Bug 12419)');
715
716     # verify that we don't attempt to sort if no results were returned
717     # because of a query error
718     warning_like {( undef, $results_hashref, $facets_loop ) =
719         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef)
720     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
721     
722     # Test facet calculation
723     my $facets_counter = {};
724     my $facets         = C4::Koha::getFacets();
725     # Create a record with a 100$z field
726     my $marc_record    = MARC::Record->new;
727     $marc_record->add_fields(
728         [ '001', '1234' ],
729         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
730         [ '100', 'z', ' ', a => 'Tomasito' ],
731         [ '245', ' ', ' ', a => 'First try' ]
732     );
733     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
734     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
735         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
736     $marc_record    = MARC::Record->new;
737     $marc_record->add_fields(
738         [ '001', '1234' ],
739         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
740         [ '100', 'z', ' ', a => 'Tomasito' ],
741         [ '245', ' ', ' ', a => 'Second try' ]
742     );
743     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
744     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
745         "_get_facets_data_from_record correctly counts author facet twice");
746
747     # Test _get_facets_info
748     my $facets_info = C4::Search::_get_facets_info( $facets );
749     my $expected_facets_info_marc21 = {
750                    'au' => { 'label_value' => "Authors" },
751                 'ccode' => { 'label_value' => "CollectionCodes" },
752         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
753                 'itype' => { 'label_value' => "ItemTypes" },
754              'location' => { 'label_value' => "Location" },
755                    'se' => { 'label_value' => "Series" },
756                'su-geo' => { 'label_value' => "Places" },
757                 'su-to' => { 'label_value' => "Topics" },
758                 'su-ut' => { 'label_value' => "Titles" }
759     };
760     delete $expected_facets_info_marc21->{holdingbranch}
761         if Koha::Libraries->count == 1;
762     is_deeply( $facets_info, $expected_facets_info_marc21,
763         "_get_facets_info returns the correct data");
764
765     cleanup();
766 }
767
768 sub run_unimarc_search_tests {
769     $datadir = tempdir();
770     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc");
771
772     Koha::Caches->get_instance('config')->flush_all;
773
774     mock_GetMarcSubfieldStructure('unimarc');
775     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
776     $context->set_context();
777
778     use_ok('C4::Search');
779
780     # set search syspreferences to a known starting point
781     $QueryStemming = 0;
782     $QueryAutoTruncate = 0;
783     $QueryWeightFields = 0;
784     $QueryFuzzy = 0;
785     $marcflavour = 'UNIMARC';
786
787     index_sample_records_and_launch_zebra($datadir, 'unimarc');
788
789     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
790     is($total_hits, 1, 'UNIMARC title search');
791     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
792     is($total_hits, 1, 'UNIMARC target audience = u');
793     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
794     is($total_hits, 4, 'UNIMARC target audience = k');
795     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
796     is($total_hits, 3, 'UNIMARC target audience = m');
797     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
798     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
799
800     # authority records
801     use_ok('C4::AuthoritiesMarc');
802
803     my ($auths, $count) = SearchAuthorities(
804         ['mainentry'], ['and'], [''], ['contains'],
805         ['wil'], 0, 10, '', '', 1
806     );
807     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
808     ($auths, $count) = SearchAuthorities(
809         ['match'], ['and'], [''], ['contains'],
810         ['wil'], 0, 10, '', '', 1
811     );
812     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
813     ($auths, $count) = SearchAuthorities(
814         ['mainentry'], ['and'], [''], ['contains'],
815         ['michel'], 0, 20, '', '', 1
816     );
817     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
818     ($auths, $count) = SearchAuthorities(
819         ['mainmainentry'], ['and'], [''], ['exact'],
820         ['valley'], 0, 20, '', '', 1
821     );
822     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
823     ($auths, $count) = SearchAuthorities(
824         ['mainmainentry'], ['and'], [''], ['exact'],
825         ['vall'], 0, 20, '', '', 1
826     );
827     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
828     ($auths, $count) = SearchAuthorities(
829         ['Any'], ['and'], [''], ['starts'],
830         ['jean'], 0, 30, '', '', 1
831     );
832     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
833
834     # Test _get_facets_info
835     my $facets      = C4::Koha::getFacets();
836     my $facets_info = C4::Search::_get_facets_info( $facets );
837     my $expected_facets_info_unimarc = {
838                    'au' => { 'label_value' => "Authors" },
839                 'ccode' => { 'label_value' => "CollectionCodes" },
840         'holdingbranch' => { 'label_value' => "HoldingLibrary" },
841              'location' => { 'label_value' => "Location" },
842                    'se' => { 'label_value' => "Series" },
843                'su-geo' => { 'label_value' => "Places" },
844                 'su-to' => { 'label_value' => "Topics" }
845     };
846     delete $expected_facets_info_unimarc->{holdingbranch}
847         if Koha::Libraries->count == 1;
848     is_deeply( $facets_info, $expected_facets_info_unimarc,
849         "_get_facets_info returns the correct data");
850
851     cleanup();
852 }
853
854 subtest 'MARC21 + DOM' => sub {
855     plan tests => 85;
856     run_marc21_search_tests();
857 };
858
859 subtest 'UNIMARC + DOM' => sub {
860     plan tests => 14;
861     run_unimarc_search_tests();
862 };
863
864 # Make sure that following tests are not using our config settings
865 Koha::Caches->get_instance('config')->flush_all;
866