Bug 11334: (follow-up) teach the search tests to mock the DisplayLibraryFacets syspref
[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 TODO: {
437     local $TODO = "Switch relevance search to MARCXML too";
438     ( undef, $results_hashref, $facets_loop ) =
439         getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, undef, 1);
440     $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]);
441     is($record->title_proper(), 'books', "Scan returned requested item");
442     is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term");
443     # Time to test buildQuery and searchResults too.
444 }
445
446     my ( $query, $simple_query, $query_cgi,
447     $query_desc, $limit, $limit_cgi, $limit_desc,
448     $stopwords_removed, $query_type );
449     ( $error, $query, $simple_query, $query_cgi,
450     $query_desc, $limit, $limit_cgi, $limit_desc,
451     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en');
452     like($query, qr/kw\W.*salud/, "Built CCL keyword query");
453
454     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
455     is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records");
456
457     my @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0,
458         $results_hashref->{'biblioserver'}->{"RECORDS"});
459     is(scalar @newresults,18, "searchResults returns requested number of hits");
460
461     ( $error, $query, $simple_query, $query_cgi,
462     $query_desc, $limit, $limit_cgi, $limit_desc,
463     $stopwords_removed, $query_type ) = buildQuery([ 'and' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
464     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query");
465
466     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
467     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records");
468
469     ( $error, $query, $simple_query, $query_cgi,
470     $query_desc, $limit, $limit_cgi, $limit_desc,
471     $stopwords_removed, $query_type ) = buildQuery([ 'or' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
472     like($query, qr/kw\W.*salud\W.*or.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query");
473
474     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
475     is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records");
476
477     ( $error, $query, $simple_query, $query_cgi,
478     $query_desc, $limit, $limit_cgi, $limit_desc,
479     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
480     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query");
481
482     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
483     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records");
484
485     ( $error, $query, $simple_query, $query_cgi,
486     $query_desc, $limit, $limit_cgi, $limit_desc,
487     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en');
488     like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly");
489     unlike($query_desc, qr/Laboratorios/, "Facets not included in query description");
490
491     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
492     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated faceted search matched right number of records");
493
494
495     ( $error, $query, $simple_query, $query_cgi,
496     $query_desc, $limit, $limit_cgi, $limit_desc,
497     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en');
498
499     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
500     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records");
501
502
503     ( $error, $query, $simple_query, $query_cgi,
504     $query_desc, $limit, $limit_cgi, $limit_desc,
505     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en');
506
507     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
508     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated multi-faceted search matched right number of records");
509
510     ( $error, $query, $simple_query, $query_cgi,
511     $query_desc, $limit, $limit_cgi, $limit_desc,
512     $stopwords_removed, $query_type ) = buildQuery([], [ 'NEKLS' ], [ 'Code-institution' ], [], [], 0, 'en');
513     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
514     is($results_hashref->{biblioserver}->{hits}, 12,
515        'search using index whose name contains "ns" returns expected results (bug 10271)');
516
517     $UseQueryParser = 1;
518     ( $error, $query, $simple_query, $query_cgi,
519     $query_desc, $limit, $limit_cgi, $limit_desc,
520     $stopwords_removed, $query_type ) = buildQuery([], [ 'book' ], [ 'kw' ], [], [], 0, 'en');
521     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
522     is($results_hashref->{biblioserver}->{hits}, 101, "Search for 'book' with index set to 'kw' returns 101 hits");
523     ( $error, $query, $simple_query, $query_cgi,
524     $query_desc, $limit, $limit_cgi, $limit_desc,
525     $stopwords_removed, $query_type ) = buildQuery([ 'and' ], [ 'book', 'another' ], [ 'kw', 'kw' ], [], [], 0, 'en');
526     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
527     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'kw:book && kw:another' returns 1 hit");
528     $UseQueryParser = 0;
529
530     # FIXME: the availability limit does not actually work, so for the moment we
531     # are just checking that it behaves consistently
532     ( $error, $query, $simple_query, $query_cgi,
533     $query_desc, $limit, $limit_cgi, $limit_desc,
534     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
535
536     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
537     is($results_hashref->{biblioserver}->{hits}, 26, "getRecords generated availability-limited search matched right number of records");
538
539     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
540         $results_hashref->{'biblioserver'}->{"RECORDS"});
541     my $allavailable = 'true';
542     foreach my $result (@newresults) {
543         $allavailable = 'false' unless $result->{availablecount} > 0;
544     }
545     is ($allavailable, 'true', 'All records have at least one item available');
546
547
548     ( $error, $query, $simple_query, $query_cgi,
549     $query_desc, $limit, $limit_cgi, $limit_desc,
550     $stopwords_removed, $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
551
552     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
553     is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records");
554
555     ( $error, $query, $simple_query, $query_cgi,
556     $query_desc, $limit, $limit_cgi, $limit_desc,
557     $stopwords_removed, $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
558
559     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
560     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
561
562     ( $error, $query, $simple_query, $query_cgi,
563     $query_desc, $limit, $limit_cgi, $limit_desc,
564     $stopwords_removed, $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
565
566     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
567     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
568
569     ( $error, $query, $simple_query, $query_cgi,
570     $query_desc, $limit, $limit_cgi, $limit_desc,
571     $stopwords_removed, $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
572
573     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
574     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
575
576     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = $QueryRemoveStopwords = 0;
577     $QueryWeightFields = 1;
578     ( $error, $query, $simple_query, $query_cgi,
579     $query_desc, $limit, $limit_cgi, $limit_desc,
580     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
581
582     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
583     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
584     if ($indexing_mode eq 'grs1') {
585         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");
586     } else {
587         local $TODO = "Query weighting does not behave exactly the same in DOM vs. GRS";
588         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");
589     }
590
591     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = 0;
592     $QueryAutoTruncate = 1;
593     ( $error, $query, $simple_query, $query_cgi,
594     $query_desc, $limit, $limit_cgi, $limit_desc,
595     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
596
597     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
598     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
599
600     ( $error, $query, $simple_query, $query_cgi,
601     $query_desc, $limit, $limit_cgi, $limit_desc,
602     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
603
604     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
605     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
606
607     $QueryStemming = $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
608     $QueryWeightFields = 1;
609     ( $error, $query, $simple_query, $query_cgi,
610     $query_desc, $limit, $limit_cgi, $limit_desc,
611     $stopwords_removed, $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
612     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
613     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
614
615     ( $error, $query, $simple_query, $query_cgi,
616     $query_desc, $limit, $limit_cgi, $limit_desc,
617     $stopwords_removed, $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
618     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
619     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
620
621     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
622     ( $error, $query, $simple_query, $query_cgi,
623     $query_desc, $limit, $limit_cgi, $limit_desc,
624     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
625
626     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
627     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
628
629     ( $error, $query, $simple_query, $query_cgi,
630     $query_desc, $limit, $limit_cgi, $limit_desc,
631     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
632
633     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
634     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
635
636     $QueryStemming = $QueryWeightFields = 1;
637     $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
638     ( $error, $query, $simple_query, $query_cgi,
639     $query_desc, $limit, $limit_cgi, $limit_desc,
640     $stopwords_removed, $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
641
642     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
643     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
644
645     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
646     ( $error, $query, $simple_query, $query_cgi,
647     $query_desc, $limit, $limit_cgi, $limit_desc,
648     $stopwords_removed, $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
649
650     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
651     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
652
653     # Let's see what happens when we pass bad data into these routines.
654     # We have to catch warnings since we're not very good about returning errors.
655
656     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
657         "SimpleSearch warns about CCL parsing error with nonsense query";
658     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
659
660     warning_like {( undef, $results_hashref, $facets_loop ) =
661         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'nonsense', undef) }
662         qr/Unknown query_type/, "getRecords warns about unknown query type";
663
664     warning_like {( undef, $results_hashref, $facets_loop ) =
665         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, '', undef) }
666         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
667
668     # Let's just test a few other bits and bobs, just for fun
669
670     ($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);
671     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
672         $results_hashref->{'biblioserver'}->{"RECORDS"});
673     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
674
675
676     ## Regression test for Bug 10741
677
678     # make one of the test items appear to be in transit
679     my $circ_module = new Test::MockModule('C4::Circulation');
680     $circ_module->mock('GetTransfers', sub {
681         my $itemnumber = shift;
682         if ($itemnumber == 11) {
683             return ('2013-07-19', 'MPL', 'CPL');
684         } else {
685             return;
686         }
687     });
688
689     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
690     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
691         $results_hashref->{'biblioserver'}->{"RECORDS"});
692     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
693
694     ## Regression test for bug 10684
695     ( undef, $results_hashref, $facets_loop ) =
696         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
697     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
698     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
699         $results_hashref->{'biblioserver'}->{"RECORDS"});
700     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
701
702     # Testing exploding indexes
703     my $term;
704     my $searchmodule = new Test::MockModule('C4::Search');
705     $searchmodule->mock('SimpleSearch', sub {
706         my $query = shift;
707
708         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
709
710         my $record = MARC::Record->new;
711         if ($query =~ m/Arizona/) {
712             $record->add_fields(
713                 [ '001', '1234' ],
714                 [ '151', ' ', ' ', a => 'Arizona' ],
715                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
716                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
717                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
718                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
719                 [ '551', ' ', ' ', a => 'New Mexico' ],
720                 );
721         }
722         return '', [ $record->as_usmarc() ], 1;
723     });
724
725     $UseQueryParser = 1;
726     $term = 'Arizona';
727     ( $error, $query, $simple_query, $query_cgi,
728     $query_desc, $limit, $limit_cgi, $limit_desc,
729     $stopwords_removed, $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
730     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
731
732     ( $error, $query, $simple_query, $query_cgi,
733     $query_desc, $limit, $limit_cgi, $limit_desc,
734     $stopwords_removed, $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
735     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
736
737     ( $error, $query, $simple_query, $query_cgi,
738     $query_desc, $limit, $limit_cgi, $limit_desc,
739     $stopwords_removed, $query_type ) = buildQuery([], [ $term ], [ 'su-rl' ], [  ], [], 0, 'en');
740     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
741
742     ( $error, $query, $simple_query, $query_cgi,
743     $query_desc, $limit, $limit_cgi, $limit_desc,
744     $stopwords_removed, $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
745     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
746     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
747
748     ( $error, $query, $simple_query, $query_cgi,
749     $query_desc, $limit, $limit_cgi, $limit_desc,
750     $stopwords_removed, $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
751     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
752     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
753
754     ( $error, $query, $simple_query, $query_cgi,
755     $query_desc, $limit, $limit_cgi, $limit_desc,
756     $stopwords_removed, $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
757     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
758
759     ( $error, $query, $simple_query, $query_cgi,
760     $query_desc, $limit, $limit_cgi, $limit_desc,
761     $stopwords_removed, $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
762     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
763
764     ( $error, $query, $simple_query, $query_cgi,
765     $query_desc, $limit, $limit_cgi, $limit_desc,
766     $stopwords_removed, $query_type ) = buildQuery([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
767     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
768
769     ( $error, $query, $simple_query, $query_cgi,
770     $query_desc, $limit, $limit_cgi, $limit_desc,
771     $stopwords_removed, $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
772     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
773     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
774
775     sub matchesExplodedTerms {
776         my ($message, $query, @terms) = @_;
777         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
778         like($query, qr/$match/, $message);
779     }
780
781     # authority records
782     use_ok('C4::AuthoritiesMarc');
783     $UseQueryParser = 0;
784
785     my ($auths, $count) = SearchAuthorities(
786         ['mainentry'], ['and'], [''], ['starts'],
787         ['shakespeare'], 0, 10, '', '', 1
788     );
789     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
790     ($auths, $count) = SearchAuthorities(
791         ['mainentry'], ['and'], [''], ['starts'],
792         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
793     );
794     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
795     ($auths, $count) = SearchAuthorities(
796         ['mainentry'], ['and'], [''], ['starts'],
797         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
798     );
799     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
800     ($auths, $count) = SearchAuthorities(
801         ['match'], ['and'], [''], ['contains'],
802         ['沙士北亞威廉姆'], 0, 10, '', '', 1
803     );
804     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
805
806     $UseQueryParser = 1;
807
808     ($auths, $count) = SearchAuthorities(
809         ['mainentry'], ['and'], [''], ['starts'],
810         ['shakespeare'], 0, 10, '', '', 1
811     );
812     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
813     ($auths, $count) = SearchAuthorities(
814         ['mainentry'], ['and'], [''], ['starts'],
815         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
816     );
817     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
818     ($auths, $count) = SearchAuthorities(
819         ['mainentry'], ['and'], [''], ['starts'],
820         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
821     );
822     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
823     ($auths, $count) = SearchAuthorities(
824         ['match'], ['and'], [''], ['contains'],
825         ['沙士北亞威廉姆'], 0, 10, '', '', 1
826     );
827     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
828
829     # retrieve records that are larger than the MARC limit of 99,999 octets
830     ( undef, $results_hashref, $facets_loop ) =
831         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
832     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
833     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
834         $results_hashref->{'biblioserver'}->{"RECORDS"});
835     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
836     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
837     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
838
839     # verify that we don't attempt to sort if no results were returned
840     # because of a query error
841     warning_like {( undef, $results_hashref, $facets_loop ) =
842         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef)
843     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
844     
845     cleanup();
846 }
847
848 sub run_unimarc_search_tests {
849     my $indexing_mode = shift;
850     $datadir = tempdir();
851     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc $indexing_mode");
852
853     mock_marcfromkohafield('unimarc');
854     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
855     $context->set_context();
856
857     use_ok('C4::Search');
858
859     # set search syspreferences to a known starting point
860     $QueryStemming = 0;
861     $QueryAutoTruncate = 0;
862     $QueryWeightFields = 0;
863     $QueryFuzzy = 0;
864     $QueryRemoveStopwords = 0;
865     $UseQueryParser = 0;
866     $marcflavour = 'UNIMARC';
867
868     index_sample_records_and_launch_zebra($datadir, $indexing_mode, 'unimarc');
869
870     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
871     is($total_hits, 1, 'UNIMARC title search');
872     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
873     is($total_hits, 1, 'UNIMARC target audience = u');
874     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
875     is($total_hits, 4, 'UNIMARC target audience = k');
876     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
877     is($total_hits, 3, 'UNIMARC target audience = m');
878     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
879     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
880
881     # authority records
882     use_ok('C4::AuthoritiesMarc');
883     $UseQueryParser = 0;
884
885     my ($auths, $count) = SearchAuthorities(
886         ['mainentry'], ['and'], [''], ['contains'],
887         ['wil'], 0, 10, '', '', 1
888     );
889     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
890     ($auths, $count) = SearchAuthorities(
891         ['match'], ['and'], [''], ['contains'],
892         ['wil'], 0, 10, '', '', 1
893     );
894     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
895     ($auths, $count) = SearchAuthorities(
896         ['mainentry'], ['and'], [''], ['contains'],
897         ['michel'], 0, 20, '', '', 1
898     );
899     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
900     ($auths, $count) = SearchAuthorities(
901         ['mainmainentry'], ['and'], [''], ['exact'],
902         ['valley'], 0, 20, '', '', 1
903     );
904     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
905     ($auths, $count) = SearchAuthorities(
906         ['mainmainentry'], ['and'], [''], ['exact'],
907         ['vall'], 0, 20, '', '', 1
908     );
909     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
910     ($auths, $count) = SearchAuthorities(
911         ['Any'], ['and'], [''], ['starts'],
912         ['jean'], 0, 30, '', '', 1
913     );
914     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
915
916     cleanup();
917 }
918
919 subtest 'MARC21 + GRS-1' => sub {
920     plan tests => 104;
921     run_marc21_search_tests('grs1');
922 };
923
924 subtest 'MARC21 + DOM' => sub {
925     plan tests => 104;
926     run_marc21_search_tests('dom');
927 };
928
929 subtest 'UNIMARC + GRS-1' => sub {
930     plan tests => 13;
931     run_unimarc_search_tests('grs1');
932 };
933
934 subtest 'UNIMARC + DOM' => sub {
935     plan tests => 13;
936     run_unimarc_search_tests('dom');
937 };
938
939 1;