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