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