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