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