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