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