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