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