bug 8252: (follow-up) add search tests on music number
[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 => 162;
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     ( $error, $marcresults, $total_hits ) = SimpleSearch("Music-number=49631-2", 0, 10);
280     is($total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)");
281     ( $error, $marcresults, $total_hits ) = SimpleSearch("Identifier-publisher-for-music=49631-2", 0, 10);
282     is($total_hits, 1, "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)");
283
284     # Testing getRecords
285
286     my $results_hashref;
287     my $facets_loop;
288     ( undef, $results_hashref, $facets_loop ) =
289         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
290     is($results_hashref->{biblioserver}->{hits}, 101, "getRecords keyword search for 'book' matched right number of records");
291     is(scalar @{$results_hashref->{biblioserver}->{RECORDS}}, 19, "getRecords returned requested number of records");
292     my $record5 = $results_hashref->{biblioserver}->{RECORDS}->[5];
293     ( undef, $results_hashref, $facets_loop ) =
294         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '20', 5, undef, \%branches, \%itemtypes, 'ccl', undef);
295     ok(!defined $results_hashref->{biblioserver}->{RECORDS}->[0] &&
296         !defined $results_hashref->{biblioserver}->{RECORDS}->[1] &&
297         !defined $results_hashref->{biblioserver}->{RECORDS}->[2] &&
298         !defined $results_hashref->{biblioserver}->{RECORDS}->[3] &&
299         !defined $results_hashref->{biblioserver}->{RECORDS}->[4] &&
300         $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works");
301
302     ( undef, $results_hashref, $facets_loop ) =
303         getRecords('ti:book', 'ti:book', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
304     is($results_hashref->{biblioserver}->{hits}, 11, "getRecords title search for 'book' matched right number of records");
305
306     ( undef, $results_hashref, $facets_loop ) =
307         getRecords('au:Lessig', 'au:Lessig', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
308     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords title search for 'Australia' matched right number of records");
309
310     ( undef, $results_hashref, $facets_loop ) =
311         getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
312     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/^Efectos del ambiente/ &&
313         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' &&
314         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/^Indicadores de resultados identificados/
315         , "Simple relevance sorting in getRecords matches old behavior");
316
317     ( undef, $results_hashref, $facets_loop ) =
318         getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
319     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/la enfermedad laboral\^ies$/ &&
320         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[6])->title_proper() =~ m/^Indicadores de resultados identificados/ &&
321         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() eq 'World health statistics 2009^ien'
322         , "Simple ascending author sorting in getRecords matches old behavior");
323
324     ( undef, $results_hashref, $facets_loop ) =
325         getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
326     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() eq 'World health statistics 2009^ien' &&
327         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[12])->title_proper() =~ m/^Indicadores de resultados identificados/ &&
328         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/la enfermedad laboral\^ies$/
329         , "Simple descending author sorting in getRecords matches old behavior");
330
331     ( undef, $results_hashref, $facets_loop ) =
332         getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
333     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() eq 'Manual de higiene industrial^ies' &&
334         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[7])->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ &&
335         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() =~ m/^Indicadores de resultados identificados/
336         , "Simple ascending publication date sorting in getRecords matches old behavior");
337
338     ( undef, $results_hashref, $facets_loop ) =
339         getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
340     ok(MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0])->title_proper() =~ m/^Estado de salud/ &&
341         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[7])->title_proper() eq 'World health statistics 2009^ien' &&
342         MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[18])->title_proper() eq 'Manual de higiene industrial^ies'
343         , "Simple descending publication date sorting in getRecords matches old behavior");
344
345     ( undef, $results_hashref, $facets_loop ) =
346         getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, undef, 1);
347     $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]);
348     is($record->title_proper(), 'books', "Scan returned requested item");
349     is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term");
350
351     # Time to test buildQuery and searchResults too.
352
353     my ( $query, $simple_query, $query_cgi,
354     $query_desc, $limit, $limit_cgi, $limit_desc,
355     $stopwords_removed, $query_type );
356     ( $error, $query, $simple_query, $query_cgi,
357     $query_desc, $limit, $limit_cgi, $limit_desc,
358     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en');
359     like($query, qr/kw\W.*salud/, "Built CCL keyword query");
360
361     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
362     is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records");
363
364     my @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0,
365         $results_hashref->{'biblioserver'}->{"RECORDS"});
366     is(scalar @newresults,18, "searchResults returns requested number of hits");
367
368     ( $error, $query, $simple_query, $query_cgi,
369     $query_desc, $limit, $limit_cgi, $limit_desc,
370     $stopwords_removed, $query_type ) = buildQuery([ 'and' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
371     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query");
372
373     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
374     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records");
375
376     ( $error, $query, $simple_query, $query_cgi,
377     $query_desc, $limit, $limit_cgi, $limit_desc,
378     $stopwords_removed, $query_type ) = buildQuery([ 'or' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
379     like($query, qr/kw\W.*salud\W.*or.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query");
380
381     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
382     is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records");
383
384     ( $error, $query, $simple_query, $query_cgi,
385     $query_desc, $limit, $limit_cgi, $limit_desc,
386     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
387     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query");
388
389     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
390     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records");
391
392     ( $error, $query, $simple_query, $query_cgi,
393     $query_desc, $limit, $limit_cgi, $limit_desc,
394     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en');
395     like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly");
396     unlike($query_desc, qr/Laboratorios/, "Facets not included in query description");
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}, 2, "getRecords generated faceted search matched right number of records");
400
401
402     ( $error, $query, $simple_query, $query_cgi,
403     $query_desc, $limit, $limit_cgi, $limit_desc,
404     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en');
405
406     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
407     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records");
408
409
410     ( $error, $query, $simple_query, $query_cgi,
411     $query_desc, $limit, $limit_cgi, $limit_desc,
412     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en');
413
414     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
415     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated multi-faceted search matched right number of records");
416
417
418     # FIXME: the availability limit does not actually work, so for the moment we
419     # are just checking that it behaves consistently
420     ( $error, $query, $simple_query, $query_cgi,
421     $query_desc, $limit, $limit_cgi, $limit_desc,
422     $stopwords_removed, $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
423
424     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
425     is($results_hashref->{biblioserver}->{hits}, 26, "getRecords generated availability-limited search matched right number of records");
426
427     @newresults = searchResults('opac', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
428         $results_hashref->{'biblioserver'}->{"RECORDS"});
429     my $allavailable = 'true';
430     foreach my $result (@newresults) {
431         $allavailable = 'false' unless $result->{availablecount} > 0;
432     }
433     is ($allavailable, 'true', 'All records have at least one item available');
434
435
436     ( $error, $query, $simple_query, $query_cgi,
437     $query_desc, $limit, $limit_cgi, $limit_desc,
438     $stopwords_removed, $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en');
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}, 178, "getRecords on _ALLRECORDS PQF returned all records");
442
443     ( $error, $query, $simple_query, $query_cgi,
444     $query_desc, $limit, $limit_cgi, $limit_desc,
445     $stopwords_removed, $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en');
446
447     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
448     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
449
450     ( $error, $query, $simple_query, $query_cgi,
451     $query_desc, $limit, $limit_cgi, $limit_desc,
452     $stopwords_removed, $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
453
454     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
455     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
456
457     ( $error, $query, $simple_query, $query_cgi,
458     $query_desc, $limit, $limit_cgi, $limit_desc,
459     $stopwords_removed, $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
460
461     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
462     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
463
464     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = $QueryRemoveStopwords = 0;
465     $QueryWeightFields = 1;
466     ( $error, $query, $simple_query, $query_cgi,
467     $query_desc, $limit, $limit_cgi, $limit_desc,
468     $stopwords_removed, $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
469
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}, 19, "Weighted query returned correct number of results");
472     if ($indexing_mode eq 'grs1') {
473         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");
474     } else {
475         local $TODO = "Query weighting does not behave exactly the same in DOM vs. GRS";
476         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");
477     }
478
479     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = 0;
480     $QueryAutoTruncate = 1;
481     ( $error, $query, $simple_query, $query_cgi,
482     $query_desc, $limit, $limit_cgi, $limit_desc,
483     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 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}, 5, "Search for 'medic' returns matches  with automatic truncation on");
487
488     ( $error, $query, $simple_query, $query_cgi,
489     $query_desc, $limit, $limit_cgi, $limit_desc,
490     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
491
492     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
493     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
494
495     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
496     ( $error, $query, $simple_query, $query_cgi,
497     $query_desc, $limit, $limit_cgi, $limit_desc,
498     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
499
500     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
501     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
502
503     ( $error, $query, $simple_query, $query_cgi,
504     $query_desc, $limit, $limit_cgi, $limit_desc,
505     $stopwords_removed, $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
506
507     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
508     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
509
510     $QueryStemming = $QueryWeightFields = 1;
511     $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
512     ( $error, $query, $simple_query, $query_cgi,
513     $query_desc, $limit, $limit_cgi, $limit_desc,
514     $stopwords_removed, $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
515
516     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
517     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
518
519     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryRemoveStopwords = $QueryAutoTruncate = 0;
520     ( $error, $query, $simple_query, $query_cgi,
521     $query_desc, $limit, $limit_cgi, $limit_desc,
522     $stopwords_removed, $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
523
524     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
525     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
526
527     # Let's see what happens when we pass bad data into these routines.
528     # We have to catch warnings since we're not very good about returning errors.
529
530     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
531         "SimpleSearch warns about CCL parsing error with nonsense query";
532     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
533
534     warning_like {( undef, $results_hashref, $facets_loop ) =
535         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'nonsense', undef) }
536         qr/Unknown query_type/, "getRecords warns about unknown query type";
537
538     warning_like {( undef, $results_hashref, $facets_loop ) =
539         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, '', undef) }
540         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
541
542     # Let's just test a few other bits and bobs, just for fun
543
544     ($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);
545     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
546         $results_hashref->{'biblioserver'}->{"RECORDS"});
547     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
548
549
550     ## Regression test for Bug 10741
551
552     # make one of the test items appear to be in transit
553     my $circ_module = new Test::MockModule('C4::Circulation');
554     $circ_module->mock('GetTransfers', sub {
555         my $itemnumber = shift;
556         if ($itemnumber == 11) {
557             return ('2013-07-19', 'MPL', 'CPL');
558         } else {
559             return;
560         }
561     });
562
563     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
564     @newresults = searchResults('intranet', $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
565         $results_hashref->{'biblioserver'}->{"RECORDS"});
566     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
567
568     # Testing exploding indexes
569     my $term;
570     my $searchmodule = new Test::MockModule('C4::Search');
571     $searchmodule->mock('SimpleSearch', sub {
572         my $query = shift;
573
574         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
575
576         my $record = MARC::Record->new;
577         if ($query =~ m/Arizona/) {
578             $record->add_fields(
579                 [ '001', '1234' ],
580                 [ '151', ' ', ' ', a => 'Arizona' ],
581                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
582                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
583                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
584                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
585                 [ '551', ' ', ' ', a => 'New Mexico' ],
586                 );
587         }
588         return '', [ $record->as_usmarc() ], 1;
589     });
590
591     $UseQueryParser = 1;
592     $term = 'Arizona';
593     ( $error, $query, $simple_query, $query_cgi,
594     $query_desc, $limit, $limit_cgi, $limit_desc,
595     $stopwords_removed, $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
596     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
597
598     ( $error, $query, $simple_query, $query_cgi,
599     $query_desc, $limit, $limit_cgi, $limit_desc,
600     $stopwords_removed, $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
601     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', '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 ], [ 'su-rl' ], [  ], [], 0, 'en');
606     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
607
608     ( $error, $query, $simple_query, $query_cgi,
609     $query_desc, $limit, $limit_cgi, $limit_desc,
610     $stopwords_removed, $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
611     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
612     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
613
614     ( $error, $query, $simple_query, $query_cgi,
615     $query_desc, $limit, $limit_cgi, $limit_desc,
616     $stopwords_removed, $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
617     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
618     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
619
620     ( $error, $query, $simple_query, $query_cgi,
621     $query_desc, $limit, $limit_cgi, $limit_desc,
622     $stopwords_removed, $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
623     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
624
625     ( $error, $query, $simple_query, $query_cgi,
626     $query_desc, $limit, $limit_cgi, $limit_desc,
627     $stopwords_removed, $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
628     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', '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([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
633     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
634
635     ( $error, $query, $simple_query, $query_cgi,
636     $query_desc, $limit, $limit_cgi, $limit_desc,
637     $stopwords_removed, $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
638     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
639     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
640
641     sub matchesExplodedTerms {
642         my ($message, $query, @terms) = @_;
643         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
644         like($query, qr/$match/, $message);
645     }
646
647     cleanup();
648 }
649
650 run_search_tests('grs1');
651 run_search_tests('dom');
652
653 1;