201614b9afd9bc103ef8cf1466cf467e89ae953d
[koha.git] / t / Koha / SearchEngine / Elasticsearch.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 Test::More tests => 4;
21 use Test::Exception;
22
23 use t::lib::Mocks;
24
25 use Test::MockModule;
26
27 use MARC::Record;
28 use Try::Tiny;
29
30 use Koha::SearchEngine::Elasticsearch;
31 use Koha::SearchEngine::Elasticsearch::Search;
32
33 subtest '_read_configuration() tests' => sub {
34
35     plan tests => 10;
36
37     my $configuration;
38     t::lib::Mocks::mock_config( 'elasticsearch', undef );
39
40     # 'elasticsearch' missing in configuration
41     throws_ok {
42         $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration;
43     }
44     'Koha::Exceptions::Config::MissingEntry',
45       'Configuration problem, exception thrown';
46     is(
47         $@->message,
48         "Missing 'elasticsearch' block in config file",
49         'Exception message is correct'
50     );
51
52     # 'elasticsearch' present but no 'server' entry
53     t::lib::Mocks::mock_config( 'elasticsearch', {} );
54     throws_ok {
55         $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration;
56     }
57     'Koha::Exceptions::Config::MissingEntry',
58       'Configuration problem, exception thrown';
59     is(
60         $@->message,
61         "Missing 'server' entry in config file for elasticsearch",
62         'Exception message is correct'
63     );
64
65     # 'elasticsearch' and 'server' entries present, but no 'index_name'
66     t::lib::Mocks::mock_config( 'elasticsearch', { server => 'a_server' } );
67     throws_ok {
68         $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration;
69     }
70     'Koha::Exceptions::Config::MissingEntry',
71       'Configuration problem, exception thrown';
72     is(
73         $@->message,
74         "Missing 'index_name' entry in config file for elasticsearch",
75         'Exception message is correct'
76     );
77
78     # Correct configuration, only one server
79     t::lib::Mocks::mock_config( 'elasticsearch',  { server => 'a_server', index_name => 'index' } );
80
81     $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration;
82     is( $configuration->{index_name}, 'index', 'Index configuration parsed correctly' );
83     is_deeply( $configuration->{nodes}, ['a_server'], 'Server configuration parsed correctly' );
84
85     # Correct configuration, two servers
86     my @servers = ('a_server', 'another_server');
87     t::lib::Mocks::mock_config( 'elasticsearch', { server => \@servers, index_name => 'index' } );
88
89     $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration;
90     is( $configuration->{index_name}, 'index', 'Index configuration parsed correctly' );
91     is_deeply( $configuration->{nodes}, \@servers , 'Server configuration parsed correctly' );
92 };
93
94 subtest 'get_elasticsearch_settings() tests' => sub {
95
96     plan tests => 1;
97
98     my $settings;
99
100     # test reading index settings
101     my $es = Koha::SearchEngine::Elasticsearch->new( {index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX} );
102     $settings = $es->get_elasticsearch_settings();
103     is( $settings->{index}{analysis}{analyzer}{analyser_phrase}{tokenizer}, 'keyword', 'Index settings parsed correctly' );
104 };
105
106 subtest 'get_elasticsearch_mappings() tests' => sub {
107
108     plan tests => 1;
109
110     my $mappings;
111
112     # test reading mappings
113     my $es = Koha::SearchEngine::Elasticsearch->new( {index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX} );
114     $mappings = $es->get_elasticsearch_mappings();
115     is( $mappings->{data}{_all}{type}, 'string', 'Field mappings parsed correctly' );
116 };
117
118 subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' => sub {
119
120     plan tests => 45;
121
122     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
123
124     my @mappings = (
125         {
126             name => 'control_number',
127             type => 'string',
128             facet => 0,
129             suggestible => 0,
130             sort => undef,
131             marc_type => 'marc21',
132             marc_field => '001',
133         },
134         {
135             name => 'author',
136             type => 'string',
137             facet => 1,
138             suggestible => 1,
139             sort => undef,
140             marc_type => 'marc21',
141             marc_field => '100a',
142         },
143         {
144             name => 'author',
145             type => 'string',
146             facet => 1,
147             suggestible => 1,
148             sort => 1,
149             marc_type => 'marc21',
150             marc_field => '110a',
151         },
152         {
153             name => 'title',
154             type => 'string',
155             facet => 0,
156             suggestible => 1,
157             sort => 1,
158             marc_type => 'marc21',
159             marc_field => '245(ab)ab',
160         },
161         {
162             name => 'unimarc_title',
163             type => 'string',
164             facet => 0,
165             suggestible => 1,
166             sort => 1,
167             marc_type => 'unimarc',
168             marc_field => '245a',
169         },
170         {
171             name => 'title',
172             type => 'string',
173             facet => 0,
174             suggestible => undef,
175             sort => 0,
176             marc_type => 'marc21',
177             marc_field => '220',
178         },
179         {
180             name => 'title_wildcard',
181             type => 'string',
182             facet => 0,
183             suggestible => 0,
184             sort => undef,
185             marc_type => 'marc21',
186             marc_field => '245',
187         },
188         {
189             name => 'sum_item_price',
190             type => 'sum',
191             facet => 0,
192             suggestible => 0,
193             sort => 0,
194             marc_type => 'marc21',
195             marc_field => '952g',
196         },
197         {
198             name => 'items_withdrawn_status',
199             type => 'boolean',
200             facet => 0,
201             suggestible => 0,
202             sort => 0,
203             marc_type => 'marc21',
204             marc_field => '9520',
205         },
206         {
207             name => 'type_of_record',
208             type => 'string',
209             facet => 0,
210             suggestible => 0,
211             sort => 0,
212             marc_type => 'marc21',
213             marc_field => 'leader_/6',
214         },
215         {
216             name => 'type_of_record_and_bib_level',
217             type => 'string',
218             facet => 0,
219             suggestible => 0,
220             sort => 0,
221             marc_type => 'marc21',
222             marc_field => 'leader_/6-7',
223         },
224     );
225
226     my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch');
227     $se->mock('_foreach_mapping', sub {
228         my ($self, $sub) = @_;
229
230         foreach my $map (@mappings) {
231             $sub->(
232                 $map->{name},
233                 $map->{type},
234                 $map->{facet},
235                 $map->{suggestible},
236                 $map->{sort},
237                 $map->{marc_type},
238                 $map->{marc_field}
239             );
240         }
241     });
242
243     my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX });
244
245     my $marc_record_1 = MARC::Record->new();
246     $marc_record_1->leader('     cam  22      a 4500');
247     $marc_record_1->append_fields(
248         MARC::Field->new('001', '123'),
249         MARC::Field->new('100', '', '', a => 'Author 1'),
250         MARC::Field->new('110', '', '', a => 'Corp Author'),
251         MARC::Field->new('210', '', '', a => 'Title 1'),
252         MARC::Field->new('245', '', '', a => 'Title:', b => 'first record'),
253         MARC::Field->new('999', '', '', c => '1234567'),
254         # '  ' for testing trimming of white space in boolean value callback:
255         MARC::Field->new('952', '', '', 0 => '  ', g => '123.30'),
256         MARC::Field->new('952', '', '', 0 => 0, g => '127.20'),
257     );
258     my $marc_record_2 = MARC::Record->new();
259     $marc_record_2->leader('     cam  22      a 4500');
260     $marc_record_2->append_fields(
261         MARC::Field->new('100', '', '', a => 'Author 2'),
262         # MARC::Field->new('210', '', '', a => 'Title 2'),
263         # MARC::Field->new('245', '', '', a => 'Title: second record'),
264         MARC::Field->new('999', '', '', c => '1234568'),
265         MARC::Field->new('952', '', '', 0 => 1, g => 'string where should be numeric'),
266     );
267     my $records = [$marc_record_1, $marc_record_2];
268
269     $see->get_elasticsearch_mappings(); #sort_fields will call this and use the actual db values unless we call it first
270
271     my $docs = $see->marc_records_to_documents($records);
272
273     # First record:
274
275     is(scalar @{$docs}, 2, 'Two records converted to documents');
276
277     is($docs->[0][0], '1234567', 'First document biblionumber should be set as first element in document touple');
278
279     is_deeply($docs->[0][1]->{control_number}, ['123'], 'First record control number should be set correctly');
280
281     is(scalar @{$docs->[0][1]->{author}}, 2, 'First document author field should contain two values');
282     is_deeply($docs->[0][1]->{author}, ['Author 1', 'Corp Author'], 'First document author field should be set correctly');
283
284     is(scalar @{$docs->[0][1]->{author__sort}}, 2, 'First document author__sort field should have two values');
285     is_deeply($docs->[0][1]->{author__sort}, ['Author 1', 'Corp Author'], 'First document author__sort field should be set correctly');
286
287     is(scalar @{$docs->[0][1]->{title__sort}}, 3, 'First document title__sort field should have three values');
288     is_deeply($docs->[0][1]->{title__sort}, ['Title:', 'first record', 'Title: first record'], 'First document title__sort field should be set correctly');
289
290     is(scalar @{$docs->[0][1]->{title_wildcard}}, 2, 'First document title_wildcard field should have two values');
291     is_deeply($docs->[0][1]->{title_wildcard}, ['Title:', 'first record'], 'First document title_wildcard field should be set correctly');
292
293     is(scalar @{$docs->[0][1]->{author__suggestion}}, 2, 'First document author__suggestion field should contain two values');
294     is_deeply(
295         $docs->[0][1]->{author__suggestion},
296         [
297             {
298                 'input' => 'Author 1'
299             },
300             {
301                 'input' => 'Corp Author'
302             }
303         ],
304         'First document author__suggestion field should be set correctly'
305     );
306
307     is(scalar @{$docs->[0][1]->{title__suggestion}}, 3, 'First document title__suggestion field should contain three values');
308     is_deeply(
309         $docs->[0][1]->{title__suggestion},
310         [
311             { 'input' => 'Title:' },
312             { 'input' => 'first record' },
313             { 'input' => 'Title: first record' }
314         ],
315         'First document title__suggestion field should be set correctly'
316     );
317
318     ok(!(defined $docs->[0][1]->{title__facet}), 'First document should have no title__facet field');
319
320     is(scalar @{$docs->[0][1]->{author__facet}}, 2, 'First document author__facet field should have two values');
321     is_deeply(
322         $docs->[0][1]->{author__facet},
323         ['Author 1', 'Corp Author'],
324         'First document author__facet field should be set correctly'
325     );
326
327     is(scalar @{$docs->[0][1]->{items_withdrawn_status}}, 2, 'First document items_withdrawn_status field should have two values');
328     is_deeply(
329         $docs->[0][1]->{items_withdrawn_status},
330         ['false', 'false'],
331         'First document items_withdrawn_status field should be set correctly'
332     );
333
334     is(
335         $docs->[0][1]->{sum_item_price},
336         '250.5',
337         'First document sum_item_price field should be set correctly'
338     );
339
340     ok(defined $docs->[0][1]->{marc_data}, 'First document marc_data field should be set');
341     ok(defined $docs->[0][1]->{marc_format}, 'First document marc_format field should be set');
342     is($docs->[0][1]->{marc_format}, 'base64ISO2709', 'First document marc_format should be set correctly');
343
344     my $decoded_marc_record = $see->decode_record_from_result($docs->[0][1]);
345
346     ok($decoded_marc_record->isa('MARC::Record'), "base64ISO2709 record successfully decoded from result");
347     is($decoded_marc_record->as_usmarc(), $marc_record_1->as_usmarc(), "Decoded base64ISO2709 record has same data as original record");
348
349     is(scalar @{$docs->[0][1]->{type_of_record}}, 1, 'First document type_of_record field should have one value');
350     is_deeply(
351         $docs->[0][1]->{type_of_record},
352         ['a'],
353         'First document type_of_record field should be set correctly'
354     );
355
356     is(scalar @{$docs->[0][1]->{type_of_record_and_bib_level}}, 1, 'First document type_of_record_and_bib_level field should have one value');
357     is_deeply(
358         $docs->[0][1]->{type_of_record_and_bib_level},
359         ['am'],
360         'First document type_of_record_and_bib_level field should be set correctly'
361     );
362
363     # Second record:
364
365     is(scalar @{$docs->[1][1]->{author}}, 1, 'Second document author field should contain one value');
366     is_deeply($docs->[1][1]->{author}, ['Author 2'], 'Second document author field should be set correctly');
367
368     is(scalar @{$docs->[1][1]->{items_withdrawn_status}}, 1, 'Second document items_withdrawn_status field should have one value');
369     is_deeply(
370         $docs->[1][1]->{items_withdrawn_status},
371         ['true'],
372         'Second document items_withdrawn_status field should be set correctly'
373     );
374
375     is(
376         $docs->[1][1]->{sum_item_price},
377         0,
378         'Second document sum_item_price field should be set correctly'
379     );
380
381     # Mappings marc_type:
382
383     ok(!(defined $docs->[0][1]->{unimarc_title}), "No mapping when marc_type doesn't match marc flavour");
384
385     # Marc serialization format fallback for records exceeding ISO2709 max record size
386
387     my $large_marc_record = MARC::Record->new();
388     $large_marc_record->leader('     cam  22      a 4500');
389
390     $large_marc_record->append_fields(
391         MARC::Field->new('100', '', '', a => 'Author 1'),
392         MARC::Field->new('110', '', '', a => 'Corp Author'),
393         MARC::Field->new('210', '', '', a => 'Title 1'),
394         MARC::Field->new('245', '', '', a => 'Title:', b => 'large record'),
395         MARC::Field->new('999', '', '', c => '1234567'),
396     );
397
398     my $item_field = MARC::Field->new('952', '', '', o => '123456789123456789123456789', p => '123456789', z => 'test');
399     my $items_count = 1638;
400     while(--$items_count) {
401         $large_marc_record->append_fields($item_field);
402     }
403
404     $docs = $see->marc_records_to_documents([$large_marc_record]);
405
406     is($docs->[0][1]->{marc_format}, 'MARCXML', 'For record exceeding max record size marc_format should be set correctly');
407
408     $decoded_marc_record = $see->decode_record_from_result($docs->[0][1]);
409
410     ok($decoded_marc_record->isa('MARC::Record'), "MARCXML record successfully decoded from result");
411     is($decoded_marc_record->as_xml_record(), $large_marc_record->as_xml_record(), "Decoded MARCXML record has same data as original record");
412
413     push @mappings, {
414         name => 'title',
415         type => 'string',
416         facet => 0,
417         suggestible => 1,
418         sort => 1,
419         marc_type => 'marc21',
420         marc_field => '245((ab)ab',
421     };
422
423     my $exception = try {
424         $see->marc_records_to_documents($records);
425     }
426     catch {
427         return $_;
428     };
429
430     ok(defined $exception, "Exception has been thrown when processing mapping with unmatched opening parenthesis");
431     ok($exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class");
432     ok($exception->message =~ /Unmatched opening parenthesis/, "Exception has the correct message");
433
434     pop @mappings;
435     push @mappings, {
436         name => 'title',
437         type => 'string',
438         facet => 0,
439         suggestible => 1,
440         sort => 1,
441         marc_type => 'marc21',
442         marc_field => '245(ab))ab',
443     };
444
445     $exception = try {
446         $see->marc_records_to_documents($records);
447     }
448     catch {
449         return $_;
450     };
451
452     ok(defined $exception, "Exception has been thrown when processing mapping with unmatched closing parenthesis");
453     ok($exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class");
454     ok($exception->message =~ /Unmatched closing parenthesis/, "Exception has the correct message");
455 };