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