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