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