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