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