Bug 14385: Squash of a lot of patches rebased
[koha.git] / t / db_dependent / Search.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use utf8;
21
22 use YAML;
23
24 use C4::Debug;
25 use C4::XSLT;
26 require C4::Context;
27
28 # work around spurious wide character warnings
29 use open ':std', ':encoding(utf8)';
30
31 use Test::More tests => 2;
32 use Test::MockModule;
33 use Test::Warn;
34
35 use Koha::Caches;
36
37 use MARC::Record;
38 use File::Spec;
39 use File::Basename;
40 use File::Find;
41
42 use File::Temp qw/ tempdir /;
43 use File::Path;
44
45 our $child;
46 our $datadir;
47
48 sub index_sample_records_and_launch_zebra {
49     my ($datadir, $marc_type) = @_;
50
51     my $sourcedir = dirname(__FILE__) . "/data";
52     unlink("$datadir/zebra.log");
53     if (-f "$sourcedir/${marc_type}/zebraexport/biblio/exported_records") {
54         my $zebra_bib_cfg = 'zebra-biblios-dom.cfg';
55         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal -g iso2709 -d biblios init");
56         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal -g iso2709 -d biblios update $sourcedir/${marc_type}/zebraexport/biblio");
57         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal -g iso2709 -d biblios commit");
58     }
59     # ... and add large bib records, if present
60     if (-f "$sourcedir/${marc_type}/zebraexport/large_biblio/exported_records.xml") {
61         my $zebra_bib_cfg = 'zebra-biblios-dom.cfg';
62         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal -g marcxml -d biblios update $sourcedir/${marc_type}/zebraexport/large_biblio");
63         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_bib_cfg  -v none,fatal -g marcxml -d biblios commit");
64     }
65     if (-f "$sourcedir/${marc_type}/zebraexport/authority/exported_records") {
66         my $zebra_auth_cfg = 'zebra-authorities-dom.cfg';
67         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal -g iso2709 -d authorities init");
68         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal -g iso2709 -d authorities update $sourcedir/${marc_type}/zebraexport/authority");
69         system("zebraidx -c $datadir/etc/koha/zebradb/$zebra_auth_cfg  -v none,fatal -g iso2709 -d authorities commit");
70     }
71
72     $child = fork();
73     if ($child == 0) {
74         exec("zebrasrv -f $datadir/etc/koha-conf.xml -v none,request -l $datadir/zebra.log");
75         exit;
76     }
77
78     sleep(1);
79 }
80
81 sub cleanup {
82     if ($child) {
83         kill 9, $child;
84
85         # Clean up the Zebra files since the child process was just shot
86         rmtree $datadir;
87     }
88 }
89
90 # Fall back to make sure that the Zebra process
91 # and files get cleaned up
92 END {
93     cleanup();
94 }
95
96 our $QueryStemming = 0;
97 our $QueryAutoTruncate = 0;
98 our $QueryWeightFields = 0;
99 our $QueryFuzzy = 0;
100 our $UseQueryParser = 0;
101 our $SearchEngine = 'Zebra';
102 our $marcflavour = 'MARC21';
103 our $htdocs = File::Spec->rel2abs(dirname($0));
104 my @htdocs = split /\//, $htdocs;
105 $htdocs[-2] = 'koha-tmpl';
106 $htdocs[-1] = 'opac-tmpl';
107 $htdocs = join '/', @htdocs;
108 our $contextmodule = new Test::MockModule('C4::Context');
109 $contextmodule->mock('preference', sub {
110     my ($self, $pref) = @_;
111     if ($pref eq 'marcflavour') {
112         return $marcflavour;
113     } elsif ($pref eq 'QueryStemming') {
114         return $QueryStemming;
115     } elsif ($pref eq 'QueryAutoTruncate') {
116         return $QueryAutoTruncate;
117     } elsif ($pref eq 'QueryWeightFields') {
118         return $QueryWeightFields;
119     } elsif ($pref eq 'QueryFuzzy') {
120         return $QueryFuzzy;
121     } elsif ($pref eq 'UseQueryParser') {
122         return $UseQueryParser;
123     } elsif ($pref eq 'SearchEngine') {
124         return $SearchEngine;
125     } elsif ($pref eq 'maxRecordsForFacets') {
126         return 20;
127     } elsif ($pref eq 'FacetLabelTruncationLength') {
128         return 20;
129     } elsif ($pref eq 'FacetMaxCount') {
130         return 20;
131     } elsif ($pref eq 'OpacHiddenItems') {
132         return '';
133     } elsif ($pref eq 'opacthemes') {
134         return 'bootstrap';
135     } elsif ($pref eq 'opaclanguages') {
136         return 'en';
137     } elsif ($pref eq 'AlternateHoldingsField') {
138         return '490av';
139     } elsif ($pref eq 'AuthoritySeparator') {
140         return '--';
141     } elsif ($pref eq 'DisplayLibraryFacets') {
142         return 'holding';
143     } elsif ($pref eq 'UNIMARCAuthorsFacetsSeparator') {
144         return '--';
145     } elsif ($pref eq 'casAuthentication' or $pref eq 'casLogout' or $pref eq 'casServerUrl' ) {
146         return '';
147     } elsif ($pref eq 'template') {
148         return 'prog';
149     } elsif ($pref eq 'OPACXSLTResultsDisplay') {
150         return C4::XSLT::_get_best_default_xslt_filename($htdocs, 'bootstrap','en',$marcflavour . 'slim2OPACResults.xsl');
151     } elsif ($pref eq 'BiblioDefaultView') {
152         return 'normal';
153     } elsif ($pref eq 'IdRef') {
154         return '0';
155     } elsif ($pref eq 'IntranetBiblioDefaultView') {
156         return 'normal';
157     } elsif ($pref eq 'OPACBaseURL') {
158         return 'http://library.mydnsname.org';
159     } elsif ($pref eq 'OPACResultsLibrary') {
160         return 'homebranch';
161     } elsif ($pref eq 'OpacSuppression') {
162         return '0';
163     } elsif ($pref eq 'OPACURLOpenInNewWindow') {
164         return '0';
165     } elsif ($pref eq 'TraceCompleteSubfields') {
166         return '0';
167     } elsif ($pref eq 'TraceSubjectSubdivisions') {
168         return '0';
169     } elsif ($pref eq 'TrackClicks') {
170         return '0';
171     } elsif ($pref eq 'URLLinkText') {
172         return q{};
173     } elsif ($pref eq 'UseAuthoritiesForTracings') {
174         return '1';
175     } elsif ($pref eq 'UseControlNumber') {
176         return '0';
177     } elsif ($pref eq 'UseICU') {
178         return '0';
179     } elsif ($pref eq 'viewISBD') {
180         return '1';
181     } else {
182         warn "The syspref $pref was requested but I don't know what to say; this indicates that the test requires updating"
183             unless $pref =~ m/(XSLT|item|branch|holding|image)/i;
184         return 0;
185     }
186 });
187 $contextmodule->mock('queryparser', sub {
188     my $QParser     = Koha::QueryParser::Driver::PQF->new();
189     $QParser->load_config("$datadir/etc/searchengine/queryparser.yaml");
190     return $QParser;
191 });
192
193 our $bibliomodule = new Test::MockModule('C4::Biblio');
194
195 sub mock_GetMarcSubfieldStructure {
196     my $marc_type = shift;
197     if ($marc_type eq 'marc21') {
198         $bibliomodule->mock('GetMarcSubfieldStructure', sub {
199             return {
200                     'biblio.biblionumber' => [{ tagfield =>  '999', tagsubfield => 'c' }],
201                     'biblio.isbn' => [{ tagfield => '020', tagsubfield => 'a' }],
202                     'biblio.title' => [{ tagfield => '245', tagsubfield => 'a' }],
203                     'biblio.notes' => [{ tagfield => '500', tagsubfield => 'a' }],
204                     'items.barcode' => [{ tagfield => '952', tagsubfield => 'p' }],
205                     'items.booksellerid' => [{ tagfield => '952', tagsubfield => 'e' }],
206                     'items.ccode' => [{ tagfield => '952', tagsubfield => '8' }],
207                     'items.cn_sort' => [{ tagfield => '952', tagsubfield => '6' }],
208                     'items.cn_source' => [{ tagfield => '952', tagsubfield => '2' }],
209                     'items.coded_location_qualifier' => [{ tagfield => '952', tagsubfield => 'f' }],
210                     'items.copynumber' => [{ tagfield => '952', tagsubfield => 't' }],
211                     'items.damaged' => [{ tagfield => '952', tagsubfield => '4' }],
212                     'items.dateaccessioned' => [{ tagfield => '952', tagsubfield => 'd' }],
213                     'items.datelastborrowed' => [{ tagfield => '952', tagsubfield => 's' }],
214                     'items.datelastseen' => [{ tagfield => '952', tagsubfield => 'r' }],
215                     'items.enumchron' => [{ tagfield => '952', tagsubfield => 'h' }],
216                     'items.holdingbranch' => [{ tagfield => '952', tagsubfield => 'b' }],
217                     'items.homebranch' => [{ tagfield => '952', tagsubfield => 'a' }],
218                     'items.issues' => [{ tagfield => '952', tagsubfield => 'l' }],
219                     'items.itemcallnumber' => [{ tagfield => '952', tagsubfield => 'o' }],
220                     'items.itemlost' => [{ tagfield => '952', tagsubfield => '1' }],
221                     'items.itemnotes' => [{ tagfield => '952', tagsubfield => 'z' }],
222                     'items.itemnumber' => [{ tagfield => '952', tagsubfield => '9' }],
223                     'items.itype' => [{ tagfield => '952', tagsubfield => 'y' }],
224                     'items.location' => [{ tagfield => '952', tagsubfield => 'c' }],
225                     'items.materials' => [{ tagfield => '952', tagsubfield => '3' }],
226                     'items.nonpublicnote' => [{ tagfield => '952', tagsubfield => 'x' }],
227                     'items.notforloan' => [{ tagfield => '952', tagsubfield => '7' }],
228                     'items.onloan' => [{ tagfield => '952', tagsubfield => 'q' }],
229                     'items.price' => [{ tagfield => '952', tagsubfield => 'g' }],
230                     'items.renewals' => [{ tagfield => '952', tagsubfield => 'm' }],
231                     'items.replacementprice' => [{ tagfield => '952', tagsubfield => 'v' }],
232                     'items.replacementpricedate' => [{ tagfield => '952', tagsubfield => 'w' }],
233                     'items.reserves' => [{ tagfield => '952', tagsubfield => 'n' }],
234                     'items.restricted' => [{ tagfield => '952', tagsubfield => '5' }],
235                     'items.stack' => [{ tagfield => '952', tagsubfield => 'j' }],
236                     'items.uri' => [{ tagfield => '952', tagsubfield => 'u' }],
237                     'items.withdrawn' => [{ tagfield => '952', tagsubfield => '0' }],
238                 };
239         });
240     }
241 }
242
243 sub run_marc21_search_tests {
244     $datadir = tempdir();
245     system(dirname(__FILE__) . "/zebra_config.pl $datadir marc21");
246
247     Koha::Caches->get_instance('config')->flush_all;
248
249     mock_GetMarcSubfieldStructure('marc21');
250     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
251     $context->set_context();
252
253     use_ok('C4::Search');
254
255     # set search syspreferences to a known starting point
256     $QueryStemming = 0;
257     $QueryAutoTruncate = 0;
258     $QueryWeightFields = 0;
259     $QueryFuzzy = 0;
260     $UseQueryParser = 0;
261     $marcflavour = 'MARC21';
262
263     my $indexes = C4::Search::getIndexes();
264     is(scalar(grep(/^ti$/, @$indexes)), 1, "Title index supported");
265
266     my $bibliomodule = new Test::MockModule('C4::Biblio');
267
268     my %branches = (
269         'CPL' => { 'branchaddress1' => 'Jefferson Summit', 'branchcode' => 'CPL', 'branchname' => 'Centerville', },
270         'FFL' => { 'branchaddress1' => 'River Station', 'branchcode' => 'FFL', 'branchname' => 'Fairfield', },
271         'FPL' => { 'branchaddress1' => 'Hickory Squere', 'branchcode' => 'FPL', 'branchname' => 'Fairview', },
272         'FRL' => { 'branchaddress1' => 'Smith Heights', 'branchcode' => 'FRL', 'branchname' => 'Franklin', },
273         'IPT' => { 'branchaddress1' => '', 'branchcode' => 'IPT', 'branchname' => "Institut Protestant de Théologie", },
274         'LPL' => { 'branchaddress1' => 'East Hills', 'branchcode' => 'LPL', 'branchname' => 'Liberty', },
275         'MPL' => { 'branchaddress1' => '372 Forest Street', 'branchcode' => 'MPL', 'branchname' => 'Midway', },
276         'PVL' => { 'branchaddress1' => 'Meadow Grove', 'branchcode' => 'PVL', 'branchname' => 'Pleasant Valley', },
277         'RPL' => { 'branchaddress1' => 'Johnson Terrace', 'branchcode' => 'RPL', 'branchname' => 'Riverside', },
278         'SPL' => { 'branchaddress1' => 'Highland Boulevard', 'branchcode' => 'SPL', 'branchname' => 'Springfield', },
279         'S'   => { 'branchaddress1' => '', 'branchcode' => 'S', 'branchname' => 'Test', },
280         'TPL' => { 'branchaddress1' => 'Valley Way', 'branchcode' => 'TPL', 'branchname' => 'Troy', },
281         'UPL' => { 'branchaddress1' => 'Chestnut Hollow', 'branchcode' => 'UPL', 'branchname' => 'Union', },
282     );
283     my %itemtypes = (
284         'BK' => { 'imageurl' => 'bridge/book.gif', 'summary' => '', 'itemtype' => 'BK', 'description' => 'Books' },
285         'CF' => { 'imageurl' => 'bridge/computer_file.gif', 'summary' => '', 'itemtype' => 'CF', 'description' => 'Computer Files' },
286         'CR' => { 'imageurl' => 'bridge/periodical.gif', 'summary' => '', 'itemtype' => 'CR', 'description' => 'Continuing Resources' },
287         'MP' => { 'imageurl' => 'bridge/map.gif', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' },
288         'MU' => { 'imageurl' => 'bridge/sound.gif', 'summary' => '', 'itemtype' => 'MU', 'description' => 'Music' },
289         'MX' => { 'imageurl' => 'bridge/kit.gif', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' },
290         'REF' => { 'imageurl' => '', 'summary' => '', 'itemtype' => 'REF', 'description' => 'Reference' },
291         'VM' => { 'imageurl' => 'bridge/dvd.gif', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' },
292     );
293
294     index_sample_records_and_launch_zebra($datadir, 'marc21');
295
296     my ($biblionumber, $title);
297     my $record = MARC::Record->new;
298
299     $record->add_fields(
300             [ '020', ' ', ' ', a => '9788522421718' ],
301             [ '245', '0', '0', a => 'Administração da produção /' ]
302             );
303     ($biblionumber,undef,$title) = FindDuplicate($record);
304     is($biblionumber, 51, 'Found duplicate with ISBN');
305
306     $record = MARC::Record->new;
307
308     $record->add_fields(
309             [ '100', '1', ' ', a => 'Carter, Philip J.' ],
310             [ '245', '1', '4', a => 'Test your emotional intelligence :' ]
311             );
312     ($biblionumber,undef,$title) = FindDuplicate($record);
313     is($biblionumber, 203, 'Found duplicate with author/title');
314
315     # Testing SimpleSearch
316
317     my ( $error, $marcresults, $total_hits ) = SimpleSearch("book", 0, 9);
318
319     is(scalar @$marcresults, 9, "SimpleSearch retrieved requested number of records");
320     is($total_hits, 101, "SimpleSearch for 'book' matched right number of records");
321     is($error, undef, "SimpleSearch does not return an error when successful");
322
323     my $marcresults2;
324     ( $error, $marcresults2, $total_hits ) = SimpleSearch("book", 5, 5);
325     is($marcresults->[5], $marcresults2->[0], "SimpleSearch cursor functions");
326
327     ( $error, $marcresults, $total_hits ) = SimpleSearch("kw=book", 0, 10);
328     is($total_hits, 101, "SimpleSearch handles simple CCL");
329
330     ( $error, $marcresults, $total_hits ) = SimpleSearch("Music-number=49631-2", 0, 10);
331     is($total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)");
332     ( $error, $marcresults, $total_hits ) = SimpleSearch("Identifier-publisher-for-music=49631-2", 0, 10);
333     is($total_hits, 1, "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)");
334
335     # Testing getRecords
336
337     my $results_hashref;
338     my $facets_loop;
339     ( undef, $results_hashref, $facets_loop ) =
340         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
341     is($results_hashref->{biblioserver}->{hits}, 101, "getRecords keyword search for 'book' matched right number of records");
342     is(scalar @{$results_hashref->{biblioserver}->{RECORDS}}, 19, "getRecords returned requested number of records");
343     my $record5 = $results_hashref->{biblioserver}->{RECORDS}->[5];
344     ( undef, $results_hashref, $facets_loop ) =
345         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '20', 5, undef, \%branches, \%itemtypes, 'ccl', undef);
346     ok(!defined $results_hashref->{biblioserver}->{RECORDS}->[0] &&
347         !defined $results_hashref->{biblioserver}->{RECORDS}->[1] &&
348         !defined $results_hashref->{biblioserver}->{RECORDS}->[2] &&
349         !defined $results_hashref->{biblioserver}->{RECORDS}->[3] &&
350         !defined $results_hashref->{biblioserver}->{RECORDS}->[4] &&
351         $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works");
352
353     ( undef, $results_hashref, $facets_loop ) =
354         getRecords('ti:book', 'ti:book', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
355     is($results_hashref->{biblioserver}->{hits}, 11, "getRecords title search for 'book' matched right number of records");
356
357     ( undef, $results_hashref, $facets_loop ) =
358         getRecords('au:Lessig', 'au:Lessig', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
359     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords title search for 'Australia' matched right number of records");
360
361 ( undef, $results_hashref, $facets_loop ) =
362     getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
363 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Efectos del ambiente/ &&
364     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies' &&
365     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
366     , "Simple relevance sorting in getRecords matches old behavior");
367
368 ( undef, $results_hashref, $facets_loop ) =
369     getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
370 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/ &&
371     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[6],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
372     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'World health statistics 2009^ien'
373     , "Simple ascending author sorting in getRecords matches old behavior");
374
375 ( undef, $results_hashref, $facets_loop ) =
376     getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
377 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
378     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[12],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ &&
379     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/
380     , "Simple descending author sorting in getRecords matches old behavior");
381
382 ( undef, $results_hashref, $facets_loop ) =
383     getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
384 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies' &&
385     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ &&
386     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/
387     , "Simple ascending publication date sorting in getRecords matches old behavior");
388
389 ( undef, $results_hashref, $facets_loop ) =
390     getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
391 ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Estado de salud/ &&
392     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' &&
393     MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies'
394     , "Simple descending publication date sorting in getRecords matches old behavior");
395
396     ( undef, $results_hashref, $facets_loop ) =
397         getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, undef, 1);
398     $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]);
399     is($record->title_proper(), 'Books', "Scan returned requested item");
400     is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term");
401     # Time to test buildQuery and searchResults too.
402
403     my ( $query, $simple_query, $query_cgi,
404     $query_desc, $limit, $limit_cgi, $limit_desc,
405     $query_type );
406     ( $error, $query, $simple_query, $query_cgi,
407     $query_desc, $limit, $limit_cgi, $limit_desc,
408     $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en');
409     like($query, qr/kw\W.*salud/, "Built CCL keyword query");
410
411     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
412     is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records");
413
414     my @newresults = searchResults({'interface' => 'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0,
415         $results_hashref->{'biblioserver'}->{"RECORDS"});
416     is(scalar @newresults,18, "searchResults returns requested number of hits");
417
418     ( $error, $query, $simple_query, $query_cgi,
419     $query_desc, $limit, $limit_cgi, $limit_desc,
420     $query_type ) = buildQuery([ 'and' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
421     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query");
422
423     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
424     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records");
425
426     ( $error, $query, $simple_query, $query_cgi,
427     $query_desc, $limit, $limit_cgi, $limit_desc,
428     $query_type ) = buildQuery([ 'or' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
429     like($query, qr/kw\W.*salud\W.*or.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query");
430
431     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
432     is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records");
433
434     ( $error, $query, $simple_query, $query_cgi,
435     $query_desc, $limit, $limit_cgi, $limit_desc,
436     $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en');
437     like($query, qr/kw\W.*salud\W.*and.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query");
438
439     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
440     is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records");
441
442     ( $error, $query, $simple_query, $query_cgi,
443     $query_desc, $limit, $limit_cgi, $limit_desc,
444     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en');
445     like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly");
446     unlike($query_desc, qr/Laboratorios/, "Facets not included in query description");
447
448     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
449     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated faceted search matched right number of records");
450
451
452     ( $error, $query, $simple_query, $query_cgi,
453     $query_desc, $limit, $limit_cgi, $limit_desc,
454     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en');
455
456     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
457     is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records");
458
459
460     ( $error, $query, $simple_query, $query_cgi,
461     $query_desc, $limit, $limit_cgi, $limit_desc,
462     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 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}, 2, "getRecords generated multi-faceted search matched right number of records");
466
467     ( $error, $query, $simple_query, $query_cgi,
468     $query_desc, $limit, $limit_cgi, $limit_desc,
469     $query_type ) = buildQuery([], [ 'NEKLS' ], [ 'Code-institution' ], [], [], 0, 'en');
470     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
471     is($results_hashref->{biblioserver}->{hits}, 12,
472        'search using index whose name contains "ns" returns expected results (bug 10271)');
473
474     $UseQueryParser = 1;
475     ( $error, $query, $simple_query, $query_cgi,
476     $query_desc, $limit, $limit_cgi, $limit_desc,
477     $query_type ) = buildQuery([], [ 'book' ], [ 'kw' ], [], [], 0, 'en');
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}, 101, "Search for 'book' with index set to 'kw' returns 101 hits");
480     ( $error, $query, $simple_query, $query_cgi,
481     $query_desc, $limit, $limit_cgi, $limit_desc,
482     $query_type ) = buildQuery([ 'and' ], [ 'book', 'another' ], [ 'kw', 'kw' ], [], [], 0, 'en');
483     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
484     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'kw:book && kw:another' returns 1 hit");
485     $UseQueryParser = 0;
486
487     # FIXME: the availability limit does not actually work, so for the moment we
488     # are just checking that it behaves consistently
489     ( $error, $query, $simple_query, $query_cgi,
490     $query_desc, $limit, $limit_cgi, $limit_desc,
491     $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en');
492
493     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
494     is($results_hashref->{biblioserver}->{hits}, 26, "getRecords generated availability-limited search matched right number of records");
495
496     @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
497         $results_hashref->{'biblioserver'}->{"RECORDS"});
498     my $allavailable = 'true';
499     foreach my $result (@newresults) {
500         $allavailable = 'false' unless $result->{availablecount} > 0;
501     }
502     is ($allavailable, 'true', 'All records have at least one item available');
503
504
505     ( $error, $query, $simple_query, $query_cgi,
506     $query_desc, $limit, $limit_cgi, $limit_desc,
507     $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 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}, 180, "getRecords on _ALLRECORDS PQF returned all records");
511
512     ( $error, $query, $simple_query, $query_cgi,
513     $query_desc, $limit, $limit_cgi, $limit_desc,
514     $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 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}, 4, "getRecords PQF author search for Lessig returned proper number of matches");
518
519     ( $error, $query, $simple_query, $query_cgi,
520     $query_desc, $limit, $limit_cgi, $limit_desc,
521     $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en');
522
523     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
524     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches");
525
526     ( $error, $query, $simple_query, $query_cgi,
527     $query_desc, $limit, $limit_cgi, $limit_desc,
528     $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en');
529
530     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
531     is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches");
532
533     $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0;
534     $QueryWeightFields = 1;
535     ( $error, $query, $simple_query, $query_cgi,
536     $query_desc, $limit, $limit_cgi, $limit_desc,
537     $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en');
538
539     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
540     is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results");
541     is(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper(), 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies', "Weighted query returns best match first");
542
543     $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0;
544     $QueryAutoTruncate = 1;
545     ( $error, $query, $simple_query, $query_cgi,
546     $query_desc, $limit, $limit_cgi, $limit_desc,
547     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
548
549     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
550     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches  with automatic truncation on");
551
552     ( $error, $query, $simple_query, $query_cgi,
553     $query_desc, $limit, $limit_cgi, $limit_desc,
554     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
555
556     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
557     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on");
558
559     $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0;
560     $QueryWeightFields = 1;
561     ( $error, $query, $simple_query, $query_cgi,
562     $query_desc, $limit, $limit_cgi, $limit_desc,
563     $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en');
564     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
565     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on");
566
567     ( $error, $query, $simple_query, $query_cgi,
568     $query_desc, $limit, $limit_cgi, $limit_desc,
569     $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en');
570     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
571     is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)");
572
573     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
574     ( $error, $query, $simple_query, $query_cgi,
575     $query_desc, $limit, $limit_cgi, $limit_desc,
576     $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en');
577
578     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
579     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off");
580
581     ( $error, $query, $simple_query, $query_cgi,
582     $query_desc, $limit, $limit_cgi, $limit_desc,
583     $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en');
584
585     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
586     is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off");
587
588     $QueryStemming = $QueryWeightFields = 1;
589     $QueryFuzzy = $QueryAutoTruncate = 0;
590     ( $error, $query, $simple_query, $query_cgi,
591     $query_desc, $limit, $limit_cgi, $limit_desc,
592     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
593
594     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
595     is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on");
596
597     $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0;
598     ( $error, $query, $simple_query, $query_cgi,
599     $query_desc, $limit, $limit_cgi, $limit_desc,
600     $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en');
601
602     ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
603     is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off");
604
605     ( $error, $query, $simple_query, $query_cgi,
606     $query_desc, $limit, $limit_cgi, $limit_desc,
607     $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en');
608     is( $query, "an:42 and ( ( allrecords,AlwaysMatches:'' not onloan,AlwaysMatches:'') and (lost,st-numeric=0) )", 'buildQuery should add the available part to the query if requested with ccl' );
609     is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' );
610
611     ( $error, $query, $simple_query, $query_cgi,
612     $query_desc, $limit, $limit_cgi, $limit_desc,
613     $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en');
614     is($query, 'su,phr=0 ', 'buildQuery should keep 0 value');
615
616     # Let's see what happens when we pass bad data into these routines.
617     # We have to catch warnings since we're not very good about returning errors.
618
619     warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/,
620         "SimpleSearch warns about CCL parsing error with nonsense query";
621     isnt($error, undef, "SimpleSearch returns an error when passed gibberish");
622
623     warning_like {( undef, $results_hashref, $facets_loop ) =
624         getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'nonsense', undef) }
625         qr/Unknown query_type/, "getRecords warns about unknown query type";
626
627     warning_like {( undef, $results_hashref, $facets_loop ) =
628         getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, '', undef) }
629         qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query";
630
631     # Let's just test a few other bits and bobs, just for fun
632
633     ($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);
634     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
635         $results_hashref->{'biblioserver'}->{"RECORDS"});
636     is($newresults[0]->{'alternateholdings_count'}, 1, 'Alternate holdings filled in correctly');
637
638
639     ## Regression test for Bug 10741
640
641     # make one of the test items appear to be in transit
642     my $circ_module = new Test::MockModule('C4::Circulation');
643     $circ_module->mock('GetTransfers', sub {
644         my $itemnumber = shift // -1;
645         if ($itemnumber == 11) {
646             return ('2013-07-19', 'MPL', 'CPL');
647         } else {
648             return;
649         }
650     });
651
652     ($error, $results_hashref, $facets_loop) = getRecords("TEST12121212","TEST12121212",[ ], [ 'biblioserver' ],20,0,undef,\%branches,\%itemtypes,$query_type,0);
653     @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0,
654         $results_hashref->{'biblioserver'}->{"RECORDS"});
655     ok(!exists($newresults[0]->{norequests}), 'presence of a transit does not block hold request action (bug 10741)');
656
657     ## Regression test for bug 10684
658     ( undef, $results_hashref, $facets_loop ) =
659         getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
660     is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records");
661     warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc,
662                     $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0,
663                     $results_hashref->{'biblioserver'}->{"RECORDS"}) }
664                 qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/,
665                 "Warning is raised correctly for invalid tags in MARC::Record";
666     is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)');
667
668     # Testing exploding indexes
669     my $term;
670     my $searchmodule = new Test::MockModule('C4::Search');
671     $searchmodule->mock('SimpleSearch', sub {
672         my $query = shift;
673
674         is($query, "he:$term", "Searching for expected term '$term' for exploding") or return '', [], 0;
675
676         my $record = MARC::Record->new;
677         if ($query =~ m/Arizona/) {
678             $record->add_fields(
679                 [ '001', '1234' ],
680                 [ '151', ' ', ' ', a => 'Arizona' ],
681                 [ '551', ' ', ' ', a => 'United States', w => 'g' ],
682                 [ '551', ' ', ' ', a => 'Maricopa County', w => 'h' ],
683                 [ '551', ' ', ' ', a => 'Navajo County', w => 'h' ],
684                 [ '551', ' ', ' ', a => 'Pima County', w => 'h' ],
685                 [ '551', ' ', ' ', a => 'New Mexico' ],
686                 );
687         }
688         return '', [ $record->as_usmarc() ], 1;
689     });
690
691     $UseQueryParser = 1;
692     $term = 'Arizona';
693     ( $error, $query, $simple_query, $query_cgi,
694     $query_desc, $limit, $limit_cgi, $limit_desc,
695     $query_type ) = buildQuery([], [ $term ], [ 'su-br' ], [  ], [], 0, 'en');
696     matchesExplodedTerms("Advanced search for broader subjects", $query, 'Arizona', 'United States');
697
698     ( $error, $query, $simple_query, $query_cgi,
699     $query_desc, $limit, $limit_cgi, $limit_desc,
700     $query_type ) = buildQuery([], [ $term ], [ 'su-na' ], [  ], [], 0, 'en');
701     matchesExplodedTerms("Advanced search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
702
703     ( $error, $query, $simple_query, $query_cgi,
704     $query_desc, $limit, $limit_cgi, $limit_desc,
705     $query_type ) = buildQuery([], [ $term ], [ 'su-rl' ], [  ], [], 0, 'en');
706     matchesExplodedTerms("Advanced search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
707
708     ( $error, $query, $simple_query, $query_cgi,
709     $query_desc, $limit, $limit_cgi, $limit_desc,
710     $query_type ) = buildQuery([], [ "$term", 'history' ], [ 'su-rl', 'kw' ], [  ], [], 0, 'en');
711     matchesExplodedTerms("Advanced search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
712     like($query, qr/history/, "Advanced search for related subjects and keyword 'history' searches for 'history'");
713
714     ( $error, $query, $simple_query, $query_cgi,
715     $query_desc, $limit, $limit_cgi, $limit_desc,
716     $query_type ) = buildQuery([], [ 'history', "$term" ], [ 'kw', 'su-rl' ], [  ], [], 0, 'en');
717     matchesExplodedTerms("Order of terms doesn't matter for advanced search", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
718     like($query, qr/history/, "Order of terms doesn't matter for advanced search");
719
720     ( $error, $query, $simple_query, $query_cgi,
721     $query_desc, $limit, $limit_cgi, $limit_desc,
722     $query_type ) = buildQuery([], [ "su-br($term)" ], [  ], [  ], [], 0, 'en');
723     matchesExplodedTerms("Simple search for broader subjects", $query, 'Arizona', 'United States');
724
725     ( $error, $query, $simple_query, $query_cgi,
726     $query_desc, $limit, $limit_cgi, $limit_desc,
727     $query_type ) = buildQuery([], [ "su-na($term)" ], [  ], [  ], [], 0, 'en');
728     matchesExplodedTerms("Simple search for narrower subjects", $query, 'Arizona', 'Maricopa County', 'Navajo County', 'Pima County');
729
730     ( $error, $query, $simple_query, $query_cgi,
731     $query_desc, $limit, $limit_cgi, $limit_desc,
732     $query_type ) = buildQuery([], [ "su-rl($term)" ], [  ], [  ], [], 0, 'en');
733     matchesExplodedTerms("Simple search for related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
734
735     ( $error, $query, $simple_query, $query_cgi,
736     $query_desc, $limit, $limit_cgi, $limit_desc,
737     $query_type ) = buildQuery([], [ "history && su-rl($term)" ], [  ], [  ], [], 0, 'en');
738     matchesExplodedTerms("Simple search for related subjects and keyword 'history' searches related subjects", $query, 'Arizona', 'United States', 'Maricopa County', 'Navajo County', 'Pima County');
739     like($query, qr/history/, "Simple search for related subjects and keyword 'history' searches for 'history'");
740
741     sub matchesExplodedTerms {
742         my ($message, $query, @terms) = @_;
743         my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}";
744         like($query, qr/$match/, $message);
745     }
746
747     # authority records
748     use_ok('C4::AuthoritiesMarc');
749     $UseQueryParser = 0;
750
751     my ($auths, $count) = SearchAuthorities(
752         ['mainentry'], ['and'], [''], ['starts'],
753         ['shakespeare'], 0, 10, '', '', 1
754     );
755     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"');
756     ($auths, $count) = SearchAuthorities(
757         ['mainentry'], ['and'], [''], ['starts'],
758         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
759     );
760     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending');
761     ($auths, $count) = SearchAuthorities(
762         ['mainentry'], ['and'], [''], ['starts'],
763         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
764     );
765     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending');
766     ($auths, $count) = SearchAuthorities(
767         ['match'], ['and'], [''], ['contains'],
768         ['沙士北亞威廉姆'], 0, 10, '', '', 1
769     );
770     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"');
771     ($auths, $count) = SearchAuthorities(
772         ['LC-card-number'], ['and'], [''], ['contains'],
773         ['99282477'], 0, 10, '', '', 1
774     );
775     is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"');
776
777     $UseQueryParser = 1;
778
779     ($auths, $count) = SearchAuthorities(
780         ['mainentry'], ['and'], [''], ['starts'],
781         ['shakespeare'], 0, 10, '', '', 1
782     );
783     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" (QP)');
784     ($auths, $count) = SearchAuthorities(
785         ['mainentry'], ['and'], [''], ['starts'],
786         ['shakespeare'], 0, 10, '', 'HeadingAsc', 1
787     );
788     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending (QP)');
789     ($auths, $count) = SearchAuthorities(
790         ['mainentry'], ['and'], [''], ['starts'],
791         ['shakespeare'], 0, 10, '', 'HeadingDsc', 1
792     );
793     is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending (QP)');
794     ($auths, $count) = SearchAuthorities(
795         ['match'], ['and'], [''], ['contains'],
796         ['沙士北亞威廉姆'], 0, 10, '', '', 1
797     );
798     is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆" (QP)');
799
800     # retrieve records that are larger than the MARC limit of 99,999 octets
801     ( undef, $results_hashref, $facets_loop ) =
802         getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef);
803     is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)");
804     @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0,
805         $results_hashref->{'biblioserver'}->{"RECORDS"});
806     is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)');
807     is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)');
808     like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)');
809
810     # notforloancount should be returned as part of searchResults output
811     ok( defined $newresults[0]->{notforloancount},
812         '\'notforloancount\' defined in searchResults output (Bug 12419)');
813     is( $newresults[0]->{notforloancount}, 2,
814         '\'notforloancount\' == 2 (Bug 12419)');
815
816     # verify that we don't attempt to sort if no results were returned
817     # because of a query error
818     warning_like {( undef, $results_hashref, $facets_loop ) =
819         getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, undef, \%branches, \%itemtypes, 'ccl', undef)
820     } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)';
821     
822     # Test facet calculation
823     my $facets_counter = {};
824     my $facets         = C4::Koha::getFacets();
825     # Create a record with a 100$z field
826     my $marc_record    = MARC::Record->new;
827     $marc_record->add_fields(
828         [ '001', '1234' ],
829         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
830         [ '100', 'z', ' ', a => 'Tomasito' ],
831         [ '245', ' ', ' ', a => 'First try' ]
832     );
833     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
834     is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } },  $facets_counter,
835         "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)");
836     $marc_record    = MARC::Record->new;
837     $marc_record->add_fields(
838         [ '001', '1234' ],
839         [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ],
840         [ '100', 'z', ' ', a => 'Tomasito' ],
841         [ '245', ' ', ' ', a => 'Second try' ]
842     );
843     C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter );
844     is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } },  $facets_counter,
845         "_get_facets_data_from_record correctly counts author facet twice");
846
847     # Test _get_facets_info
848     my $facets_info = C4::Search::_get_facets_info( $facets );
849     my $expected_facets_info_marc21 = {
850                    'au' => { 'expanded'    => undef,
851                              'label_value' => "Authors" },
852                 'ccode' => { 'expanded'    => undef,
853                              'label_value' => "CollectionCodes" },
854         'holdingbranch' => { 'expanded'    => undef,
855                              'label_value' => "HoldingLibrary" },
856                 'itype' => { 'expanded'    => undef,
857                              'label_value' => "ItemTypes" },
858              'location' => { 'expanded'    => undef,
859                              'label_value' => "Location" },
860                    'se' => { 'expanded'    => undef,
861                              'label_value' => "Series" },
862                'su-geo' => { 'expanded'    => undef,
863                              'label_value' => "Places" },
864                 'su-to' => { 'expanded'    => undef,
865                              'label_value' => "Topics" },
866                 'su-ut' => { 'expanded'    => undef,
867                              'label_value' => "Titles" }
868     };
869     delete $expected_facets_info_marc21->{holdingbranch}
870         if Koha::Libraries->count == 1;
871     is_deeply( $facets_info, $expected_facets_info_marc21,
872         "_get_facets_info returns the correct data");
873
874     cleanup();
875 }
876
877 sub run_unimarc_search_tests {
878     $datadir = tempdir();
879     system(dirname(__FILE__) . "/zebra_config.pl $datadir unimarc");
880
881     Koha::Caches->get_instance('config')->flush_all;
882
883     mock_GetMarcSubfieldStructure('unimarc');
884     my $context = new C4::Context("$datadir/etc/koha-conf.xml");
885     $context->set_context();
886
887     use_ok('C4::Search');
888
889     # set search syspreferences to a known starting point
890     $QueryStemming = 0;
891     $QueryAutoTruncate = 0;
892     $QueryWeightFields = 0;
893     $QueryFuzzy = 0;
894     $UseQueryParser = 0;
895     $marcflavour = 'UNIMARC';
896
897     index_sample_records_and_launch_zebra($datadir, 'unimarc');
898
899     my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10);
900     is($total_hits, 1, 'UNIMARC title search');
901     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10);
902     is($total_hits, 1, 'UNIMARC target audience = u');
903     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10);
904     is($total_hits, 4, 'UNIMARC target audience = k');
905     ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10);
906     is($total_hits, 3, 'UNIMARC target audience = m');
907     ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10);
908     is($total_hits, 1, 'UNIMARC generic item index (bug 10037)');
909
910     # authority records
911     use_ok('C4::AuthoritiesMarc');
912     $UseQueryParser = 0;
913
914     my ($auths, $count) = SearchAuthorities(
915         ['mainentry'], ['and'], [''], ['contains'],
916         ['wil'], 0, 10, '', '', 1
917     );
918     is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"');
919     ($auths, $count) = SearchAuthorities(
920         ['match'], ['and'], [''], ['contains'],
921         ['wil'], 0, 10, '', '', 1
922     );
923     is($count, 11, 'UNIMARC authorities: hits on match contains "wil"');
924     ($auths, $count) = SearchAuthorities(
925         ['mainentry'], ['and'], [''], ['contains'],
926         ['michel'], 0, 20, '', '', 1
927     );
928     is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"');
929     ($auths, $count) = SearchAuthorities(
930         ['mainmainentry'], ['and'], [''], ['exact'],
931         ['valley'], 0, 20, '', '', 1
932     );
933     is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"');
934     ($auths, $count) = SearchAuthorities(
935         ['mainmainentry'], ['and'], [''], ['exact'],
936         ['vall'], 0, 20, '', '', 1
937     );
938     is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"');
939     ($auths, $count) = SearchAuthorities(
940         ['Any'], ['and'], [''], ['starts'],
941         ['jean'], 0, 30, '', '', 1
942     );
943     is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"');
944
945     # Test _get_facets_info
946     my $facets      = C4::Koha::getFacets();
947     my $facets_info = C4::Search::_get_facets_info( $facets );
948     my $expected_facets_info_unimarc = {
949                    'au' => { 'expanded'    => undef,
950                              'label_value' => "Authors" },
951                 'ccode' => { 'expanded'    => undef,
952                              'label_value' => "CollectionCodes" },
953         'holdingbranch' => { 'expanded'    => undef,
954                              'label_value' => "HoldingLibrary" },
955              'location' => { 'expanded'    => undef,
956                              'label_value' => "Location" },
957                    'se' => { 'expanded'    => undef,
958                              'label_value' => "Series" },
959                'su-geo' => { 'expanded'    => undef,
960                              'label_value' => "Places" },
961                 'su-to' => { 'expanded'    => undef,
962                              'label_value' => "Topics" },
963                 'su-ut' => { 'expanded'    => undef,
964                              'label_value' => "Titles" }
965     };
966     delete $expected_facets_info_unimarc->{holdingbranch}
967         if Koha::Libraries->count == 1;
968     is_deeply( $facets_info, $expected_facets_info_unimarc,
969         "_get_facets_info returns the correct data");
970
971     cleanup();
972 }
973
974 subtest 'MARC21 + DOM' => sub {
975     plan tests => 109;
976     run_marc21_search_tests();
977 };
978
979 subtest 'UNIMARC + DOM' => sub {
980     plan tests => 14;
981     run_unimarc_search_tests();
982 };
983
984 # Make sure that following tests are not using our config settings
985 Koha::Caches->get_instance('config')->flush_all;
986