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