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