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