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