Bug 35979: (follow-up) Add check in ->enqueue
[koha.git] / t / db_dependent / Biblio.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 => 21;
21 use Test::MockModule;
22 use Test::Warn;
23 use List::MoreUtils qw( uniq );
24 use MARC::Record;
25
26 use t::lib::Mocks qw( mock_preference );
27 use t::lib::TestBuilder;
28
29 use Koha::ActionLogs;
30 use Koha::Database;
31 use Koha::Caches;
32 use Koha::MarcSubfieldStructures;
33
34 use C4::Linker::Default qw( get_link );
35
36 BEGIN {
37     use_ok('C4::Biblio', qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcControlnumber GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio ));
38 }
39
40 my $schema = Koha::Database->new->schema;
41 $schema->storage->txn_begin;
42 my $dbh = C4::Context->dbh;
43 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
44
45 my $builder = t::lib::TestBuilder->new;
46
47 subtest 'AddBiblio' => sub {
48     plan tests => 9;
49
50     my $marcflavour = 'MARC21';
51     t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour );
52
53     my ( $f, $sf ) = GetMarcFromKohaField('biblioitems.cn_item');
54     my $cn_item_field = MARC::Field->new( $f, ' ', ' ',
55         $sf => 'Thisisgoingtobetoomanycharactersforthe.cn_item.field' );
56     my $record = MARC::Record->new();
57     $record->append_fields($cn_item_field);
58
59     my $nb_biblios = Koha::Biblios->count;
60     my ( $biblionumber, $biblioitemnumber );
61     warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
62         [ qr/Data too long for column 'cn_item'/, qr/Data too long for column 'cn_item'/ ],
63         "expected warnings when adding too long cn_item";
64     is( $biblionumber, undef,
65         'AddBiblio returns undef for biblionumber if something went wrong' );
66     is( $biblioitemnumber, undef,
67         'AddBiblio returns undef for biblioitemnumber if something went wrong'
68     );
69     is( Koha::Biblios->count, $nb_biblios,
70         'No biblio should have been added if something went wrong' );
71
72     ( $f, $sf ) = GetMarcFromKohaField('biblioitems.lccn');
73     my $lccn_field = MARC::Field->new( $f, ' ', ' ',
74         $sf => 'ThisisNOTgoingtobetoomanycharactersfortheLCCNfield' );
75     $record = MARC::Record->new();
76     $record->append_fields($lccn_field);
77
78     warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
79         [],
80         "No warning expected when adding a long LCCN";
81     isnt( $biblionumber, undef,
82         'AddBiblio returns the biblionumber' );
83     isnt( $biblioitemnumber, undef,
84         'AddBiblio returns the biblioitemnumber'
85     );
86     is( Koha::Biblios->count, $nb_biblios + 1,
87         'The biblio should have been added if nothing went wrong' );
88
89     t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour );
90     t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', $marcflavour );
91     t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" );
92
93     my $mock_biblio = Test::MockModule->new("C4::Biblio");
94     $mock_biblio->mock( BiblioAutoLink => sub {
95         my $record = shift;
96         my $frameworkcode = shift;
97         warn "My biblionumber is ".$record->subfield('999','c')." and my frameworkcode is $frameworkcode";
98     });
99     warning_like { $builder->build_sample_biblio(); }
100         qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink";
101
102 };
103
104 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
105     plan tests => 25;
106
107     my @columns = qw(
108         tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
109         authorised_value authtypecode value_builder isurl hidden frameworkcode
110         seealso link defaultvalue maxlength
111     );
112
113     # biblio.biblionumber must be mapped so this should return something
114     my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
115
116     ok(defined $marc_subfield_structure, "There is a result");
117     is(ref $marc_subfield_structure, "HASH", "Result is a hashref");
118     foreach my $col (@columns) {
119         ok(exists $marc_subfield_structure->{$col}, "Hashref contains key '$col'");
120     }
121     is($marc_subfield_structure->{kohafield}, 'biblio.biblionumber', "Result is the good result");
122     like($marc_subfield_structure->{tagfield}, qr/^\d{3}$/, "tagfield is a valid tagfield");
123
124     # Add a test for list context (BZ 10306)
125     my @results = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
126     is( @results, 1, 'We expect only one mapping' );
127     is_deeply( $results[0], $marc_subfield_structure,
128         'The first entry should be the same hashref as we had before' );
129
130     # foo.bar does not exist so this should return undef
131     $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar');
132     is($marc_subfield_structure, undef, "invalid kohafield returns undef");
133
134 };
135
136 subtest "GetMarcSubfieldStructure" => sub {
137     plan tests => 5;
138
139     # Add multiple Koha to Marc mappings
140     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete;
141     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store;
142     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store;
143     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
144     my $structure = C4::Biblio::GetMarcSubfieldStructure('');
145
146     is( @{ $structure->{"mytable.nicepages"} }, 2,
147         'GetMarcSubfieldStructure should return two entries for nicepages' );
148     is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399',
149         'Check tagfield for first entry' );
150     is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a',
151         'Check tagsubfield for first entry' );
152     is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399',
153         'Check tagfield for second entry' );
154     is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b',
155         'Check tagsubfield for second entry' );
156 };
157
158 subtest "GetMarcFromKohaField" => sub {
159     plan tests => 8;
160
161     #NOTE: We are building on data from the previous subtest
162     # With: field 399 / mytable.nicepages
163
164     # Check call in list context for multiple mappings
165     my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages');
166     is( @retval, 4, 'Should return two tags and subfields' );
167     is( $retval[0], '399', 'Check first tag' );
168     is( $retval[1], 'a', 'Check first subfield' );
169     is( $retval[2], '399', 'Check second tag' );
170     is( $retval[3], 'b', 'Check second subfield' );
171
172     # Check same call in scalar context
173     is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
174         'GetMarcFromKohaField returns first tag in scalar context' );
175
176     # Bug 19096 Default is authoritative
177     # If we add a new empty framework, we should still get the mappings
178     # from Default. CAUTION: This test passes intentionally the obsoleted
179     # framework parameter.
180     my $new_fw = t::lib::TestBuilder->new->build({source => 'BiblioFramework'});
181     @retval = C4::Biblio::GetMarcFromKohaField(
182         'mytable.nicepages', $new_fw->{frameworkcode},
183     );
184     is( @retval, 4, 'Still got two pairs of tags/subfields' );
185     is( $retval[0].$retval[1], '399a', 'Including 399a' );
186 };
187
188 subtest "Authority creation with default linker" => sub {
189     plan tests => 4;
190     # Automatic authority creation
191     t::lib::Mocks::mock_preference('LinkerModule', 'Default');
192     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
193     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
194     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
195     my $linker = C4::Linker::Default->new({});
196     my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
197     $authorities_mod->mock(
198         'authorities',
199         sub {
200             my $results = [{ authid => 'original' },{ authid => 'duplicate' }];
201             return $results;
202         }
203     );
204     my $marc_record = MARC::Record->new();
205     my $field = MARC::Field->new(655, ' ', ' ','a' => 'Magical realism');
206     $marc_record->append_fields( $field );
207     my ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
208     is( $num_changed, 0, "We shouldn't link or create a new record");
209     ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record");
210
211     ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
212     is( $num_changed, 0, "We shouldn't link or create a new record using cached result");
213     ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record on second instance");
214 };
215
216
217
218 # Mocking variables
219 my $biblio_module = Test::MockModule->new('C4::Biblio');
220 $biblio_module->mock(
221     'GetMarcSubfieldStructure',
222     sub {
223         my ($self) = shift;
224
225         my ( $title_field,            $title_subfield )            = get_title_field();
226         my ( $subtitle_field,         $subtitle_subfield )         = get_subtitle_field();
227         my ( $medium_field,           $medium_subfield )           = get_medium_field();
228         my ( $part_number_field,      $part_number_subfield )      = get_part_number_field();
229         my ( $part_name_field,        $part_name_subfield )        = get_part_name_field();
230         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
231         my ( $issn_field,             $issn_subfield )             = get_issn_field();
232         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
233         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
234         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
235
236         return {
237             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
238             'biblio.subtitle'              => [ { tagfield => $subtitle_field,         tagsubfield => $subtitle_subfield } ],
239             'biblio.medium'                => [ { tagfield => $medium_field,           tagsubfield => $medium_subfield } ],
240             'biblio.part_number'           => [ { tagfield => $part_number_field,      tagsubfield => $part_number_subfield } ],
241             'biblio.part_name'             => [ { tagfield => $part_name_field,        tagsubfield => $part_name_subfield } ],
242             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
243             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
244             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
245             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
246             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
247         };
248       }
249 );
250
251 my $currency = Test::MockModule->new('Koha::Acquisition::Currencies');
252 $currency->mock(
253     'get_active',
254     sub {
255         return Koha::Acquisition::Currency->new(
256             {   symbol   => '$',
257                 isocode  => 'USD',
258                 currency => 'USD',
259                 active   => 1,
260             }
261         );
262     }
263 );
264
265 sub run_tests {
266
267     my $marcflavour = shift;
268     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
269     # Authority tests don't interact well with Elasticsearch at the moment due to the fact that there's currently no way to
270     # roll back ES index changes.
271     t::lib::Mocks::mock_preference('SearchEngine', 'Zebra');
272     t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
273
274     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
275
276     my $isbn = '0590353403';
277     my $title = 'Foundation';
278     my $subtitle1 = 'Research';
279     my $subtitle2 = 'Conclusions';
280     my $medium = 'Medium';
281     my $part_number = '123';
282     my $part_name = 'First years';
283
284     # Generate a record with just the ISBN
285     my $marc_record = MARC::Record->new;
286     $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
287
288     # Add the record to the DB
289     my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
290     my $data = GetBiblioData( $biblionumber );
291     is( $data->{ isbn }, $isbn,
292         '(GetBiblioData) ISBN correctly retireved.');
293     is( $data->{ title }, undef,
294         '(GetBiblioData) Title field is empty in fresh biblio.');
295
296     my $biblio = Koha::Biblios->find($biblionumber);
297
298     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
299     my $marc = $biblio->metadata->record;
300     is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
301
302     # Add title
303     my $field = create_title_field( $title, $marcflavour );
304     $marc_record->append_fields( $field );
305     ModBiblio( $marc_record, $biblionumber ,'' );
306     $data = GetBiblioData( $biblionumber );
307     is( $data->{ title }, $title,
308         'ModBiblio correctly added the title field, and GetBiblioData.');
309     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
310     $marc = $biblio->get_from_storage->metadata->record;
311     my ( $title_field, $title_subfield ) = get_title_field();
312     is( $marc->subfield( $title_field, $title_subfield ), $title, );
313
314     # Add other fields
315     $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) );
316     $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) );
317     $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) );
318     $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) );
319     $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) );
320
321     ModBiblio( $marc_record, $biblionumber ,'' );
322     $data = GetBiblioData( $biblionumber );
323     is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' );
324     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' );
325
326     is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' );
327     is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' );
328     is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' );
329     is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' );
330
331     my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber );
332     is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now
333         'Do not know if this makes sense - compare result of previous two GetBiblioData tests.');
334     is( $biblioitem->isbn, $isbn,
335         'Second test checking it returns the correct isbn.');
336
337     my $success = 0;
338     $field = MARC::Field->new(
339             655, ' ', ' ',
340             'a' => 'Auction catalogs',
341             '9' => '1'
342             );
343     eval {
344         $marc_record->append_fields($field);
345         $success = ModBiblio($marc_record,$biblionumber,'');
346     } or do {
347         diag($@);
348         $success = 0;
349     };
350     ok($success, "ModBiblio handles authority-linked 655");
351
352     eval {
353         $field->delete_subfields('a');
354         $marc_record->append_fields($field);
355         $success = ModBiblio($marc_record,$biblionumber,'');
356     } or do {
357         diag($@);
358         $success = 0;
359     };
360     ok($success, "ModBiblio handles 655 with authority link but no heading");
361
362     eval {
363         $field->delete_subfields('9');
364         $marc_record->append_fields($field);
365         $success = ModBiblio($marc_record,$biblionumber,'');
366     } or do {
367         diag($@);
368         $success = 0;
369     };
370     ok($success, "ModBiblio handles 655 with no subfields");
371
372     ## Testing GetMarcISSN
373     my $issns;
374     $issns = GetMarcISSN( $marc_record, $marcflavour );
375     is( $issns->[0], undef,
376         'GetMarcISSN handles records without the ISSN field (list is empty)' );
377     is( scalar @$issns, 0,
378         'GetMarcISSN handles records without the ISSN field (count is 0)' );
379     # Add an ISSN field
380     my $issn = '1234-1234';
381     $field = create_issn_field( $issn, $marcflavour );
382     $marc_record->append_fields($field);
383     $issns = GetMarcISSN( $marc_record, $marcflavour );
384     is( $issns->[0], $issn,
385         'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
386     is( scalar @$issns, 1,
387         'GetMARCISSN handles records with a single ISSN field (count is 1)');
388     # Add multiple ISSN field
389     my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
390     foreach (@more_issns) {
391         $field = create_issn_field( $_, $marcflavour );
392         $marc_record->append_fields($field);
393     }
394     $issns = GetMarcISSN( $marc_record, $marcflavour );
395     is( scalar @$issns, 4,
396         'GetMARCISSN handles records with multiple ISSN fields (count correct)');
397     # Create an empty ISSN
398     $field = create_issn_field( "", $marcflavour );
399     $marc_record->append_fields($field);
400     $issns = GetMarcISSN( $marc_record, $marcflavour );
401     is( scalar @$issns, 4,
402         'GetMARCISSN skips empty ISSN fields (Bug 12674)');
403
404     ## Testing GetMarcControlnumber
405     my $controlnumber;
406     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
407     is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
408
409     $field = MARC::Field->new( '001', '' );
410     $marc_record->append_fields($field);
411     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
412     is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
413
414     $field = $marc_record->field('001');
415     $field->update('123456789X');
416     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
417     is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
418
419     ## Testing GetMarcISBN
420     my $record_for_isbn = MARC::Record->new();
421     my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
422     is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
423
424     # We add one ISBN
425     $isbn_field = create_isbn_field( $isbn, $marcflavour );
426     $record_for_isbn->append_fields( $isbn_field );
427     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
428     is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
429     is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
430
431     # We add 3 more ISBNs
432     $record_for_isbn = MARC::Record->new();
433     my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
434     foreach (@more_isbns) {
435         $field = create_isbn_field( $_, $marcflavour );
436         $record_for_isbn->append_fields($field);
437     }
438     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
439     is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
440     for my $i (0 .. $#more_isbns) {
441         is( $isbns->[$i], $more_isbns[$i],
442             "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
443     }
444
445     is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
446         "GetMarcPrice returns the correct value");
447     my $frameworkcode = GetFrameworkCode($biblionumber);
448     my $updatedrecord = $biblio->metadata->record;
449     my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
450     die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
451     my $biblioitemnumbertotest;
452     if ( $biblioitem_tag < 10 ) {
453         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
454     } else {
455         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
456     }
457
458     # test for GetMarcUrls
459     $marc_record->append_fields(
460         MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
461         MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
462     );
463     my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
464     is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
465     like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
466     ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
467         'GetMarcUrls prefixed a MARC21 URL with http://' );
468
469     # Automatic authority creation
470     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
471     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
472     my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
473     $authorities_mod->mock(
474         'authorities',
475         sub {
476             my @results;
477             return \@results;
478         }
479     );
480     $success = 0;
481     $field = create_author_field('Author Name');
482     eval {
483         $marc_record->append_fields($field);
484         $success = ModBiblio($marc_record,$biblionumber,'');
485     } or do {
486         diag($@);
487         $success = 0;
488     };
489     ok($success, "ModBiblio handles authority addition for author");
490
491     my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field();
492     $field = $marc_record->field($author_field);
493     ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact");
494
495     my $authid = $field->subfield('9');
496     ok($authid, 'ModBiblio adds authority id');
497
498     use_ok('C4::AuthoritiesMarc', qw( GetAuthority ));
499     my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
500     ok($auth_record, 'Authority record successfully retrieved');
501
502
503     my ($auth_author_field, $auth_author_subfield) = get_auth_author_field();
504     $field = $auth_record->field($auth_author_field);
505     ok($field, "Authority record contains field $auth_author_field");
506     is(
507         $field->subfield($auth_author_subfield),
508         'Author Name',
509         'Authority $auth_author_field$auth_author_subfield contains author name'
510     );
511     is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
512
513     # Reset settings
514     t::lib::Mocks::mock_preference('AutoLinkBiblios', 0);
515     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
516 }
517
518 sub get_title_field {
519     my $marc_flavour = C4::Context->preference('marcflavour');
520     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
521 }
522
523 sub get_medium_field {
524     my $marc_flavour = C4::Context->preference('marcflavour');
525     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
526 }
527
528 sub get_subtitle_field {
529     my $marc_flavour = C4::Context->preference('marcflavour');
530     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
531 }
532
533 sub get_part_number_field {
534     my $marc_flavour = C4::Context->preference('marcflavour');
535     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
536 }
537
538 sub get_part_name_field {
539     my $marc_flavour = C4::Context->preference('marcflavour');
540     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
541 }
542
543 sub get_isbn_field {
544     my $marc_flavour = C4::Context->preference('marcflavour');
545     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
546 }
547
548 sub get_issn_field {
549     my $marc_flavour = C4::Context->preference('marcflavour');
550     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
551 }
552
553 sub get_itemnumber_field {
554     my $marc_flavour = C4::Context->preference('marcflavour');
555     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
556 }
557
558 sub get_author_field {
559     my $marc_flavour = C4::Context->preference('marcflavour');
560     return ( $marc_flavour eq 'UNIMARC' ) ? ( '700', 'a', '4' ) : ( '100', 'a', 'e' );
561 }
562
563 sub get_auth_author_field {
564     my $marc_flavour = C4::Context->preference('marcflavour');
565     return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
566 }
567
568 sub create_title_field {
569     my ( $title, $marcflavour ) = @_;
570
571     my ( $title_field, $title_subfield ) = get_title_field();
572     my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
573
574     return $field;
575 }
576
577 sub create_field {
578     my ( $content, $marcflavour, $field, $subfield ) = @_;
579
580     return MARC::Field->new( $field, '', '', $subfield => $content );
581 }
582
583 sub create_isbn_field {
584     my ( $isbn, $marcflavour ) = @_;
585
586     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
587     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
588
589     # Add the price subfield
590     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
591     $field->add_subfields( $price_subfield => '$100' );
592
593     return $field;
594 }
595
596 sub create_issn_field {
597     my ( $issn, $marcflavour ) = @_;
598
599     my ( $issn_field, $issn_subfield ) = get_issn_field();
600     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
601
602     return $field;
603 }
604
605 sub create_author_field {
606     my ( $author ) = @_;
607
608     my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field();
609     my $field = MARC::Field->new(
610         $author_field, '', '',
611         $author_subfield => $author,
612         $author_relator_subfield => 'aut'
613     );
614
615     return $field;
616 }
617
618 subtest 'MARC21' => sub {
619     plan tests => 46;
620     run_tests('MARC21');
621     $schema->storage->txn_rollback;
622     $schema->storage->txn_begin;
623 };
624
625 subtest 'UNIMARC' => sub {
626     plan tests => 46;
627
628     # Mock the auth type data for UNIMARC
629     $dbh->do("UPDATE auth_types SET auth_tag_to_report = '106' WHERE auth_tag_to_report = '100'") or die $dbh->errstr;
630
631     run_tests('UNIMARC');
632     $schema->storage->txn_rollback;
633     $schema->storage->txn_begin;
634 };
635
636 subtest 'IsMarcStructureInternal' => sub {
637     plan tests => 9;
638     my $tagslib = GetMarcStructure();
639     my @internals;
640     for my $tag ( sort keys %$tagslib ) {
641         next unless $tag;
642         for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
643             push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
644         }
645     }
646     @internals = uniq @internals;
647     is( scalar(@internals), 7, 'expect 7 internals');
648     is( grep( /^lib$/, @internals ), 1, 'check lib' );
649     is( grep( /^tab$/, @internals ), 1, 'check tab' );
650     is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
651     is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
652     is( grep( /^important$/, @internals ), 1, 'check important' );
653     is( grep( /^a$/, @internals ), 0, 'no subfield a' );
654     is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' );
655     is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' );
656 };
657
658 subtest 'deletedbiblio_metadata' => sub {
659     plan tests => 2;
660
661     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
662
663     my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
664     my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
665     C4::Biblio::DelBiblio( $biblionumber );
666     my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
667     is( $moved, $biblionumber, 'Found in deletedbiblio' );
668     ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
669     is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
670 };
671
672 subtest 'DelBiblio' => sub {
673
674     plan tests => 10;
675
676     t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
677
678     my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, '');
679     my $deleted = C4::Biblio::DelBiblio( $biblionumber );
680     is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead!
681
682     $deleted = C4::Biblio::DelBiblio( $biblionumber );
683     is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
684
685     my $biblio       = $builder->build_sample_biblio;
686     my $subscription = $builder->build_object(
687         {
688             class => 'Koha::Subscriptions',
689             value => { biblionumber => $biblio->biblionumber }
690         }
691     );
692     my $serial = $builder->build_object(
693         {
694             class => 'Koha::Serials',
695             value => {
696                 biblionumber   => $biblio->biblionumber,
697                 subscriptionid => $subscription->subscriptionid
698             }
699         }
700     );
701     my $subscription_history = $builder->build_object(
702         {
703             class => 'Koha::Subscription::Histories',
704             value => {
705                 biblionumber   => $biblio->biblionumber,
706                 subscriptionid => $subscription->subscriptionid
707             }
708         }
709     );
710
711     my $order_basket = $builder->build( { source => 'Aqbasket' } );
712
713     my $orderinfo = {
714         biblionumber => $biblio->biblionumber,
715         basketno     => $order_basket->{basketno},
716     };
717     my $order = $builder->build_object(
718         { class => 'Koha::Acquisition::Orders', value => $orderinfo } );
719
720     # Add some ILL requests
721     my $ill_req_1 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
722     my $ill_req_2 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
723
724     C4::Biblio::DelBiblio($biblio->biblionumber); # Or $biblio->delete
725     is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' );
726     is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' );
727     is( $subscription_history->get_from_storage, undef, 'subscription history should be deleted on biblio deletion' );
728     is( $order->get_from_storage->deleted_biblionumber, $biblio->biblionumber, 'biblionumber of order has been moved to deleted_biblionumber column' );
729
730     $ill_req_1 = $ill_req_1->get_from_storage;
731     $ill_req_2 = $ill_req_2->get_from_storage;
732     is( $ill_req_1->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
733     is( $ill_req_1->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
734     is( $ill_req_2->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
735     is( $ill_req_2->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
736 };
737
738 subtest 'MarcFieldForCreatorAndModifier' => sub {
739     plan tests => 8;
740
741     t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a');
742     t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b');
743     t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c');
744     t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d');
745     my $c4_context = Test::MockModule->new('C4::Context');
746     $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; });
747
748     my $record = MARC::Record->new();
749     my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
750
751     my $biblio = Koha::Biblios->find($biblionumber);
752     $record = $biblio->metadata->record;
753     is($record->subfield('998', 'a'), 123, '998$a = 123');
754     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
755     is($record->subfield('998', 'c'), 123, '998$c = 123');
756     is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe');
757
758     $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
759     C4::Biblio::ModBiblio($record, $biblionumber, '');
760
761     $record = $biblio->get_from_storage->metadata->record;
762     is($record->subfield('998', 'a'), 123, '998$a = 123');
763     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
764     is($record->subfield('998', 'c'), 321, '998$c = 321');
765     is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe');
766 };
767
768 subtest 'ModBiblio called from linker test' => sub {
769     plan tests => 2;
770     my $called = 0;
771     t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
772     my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
773     $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
774         $called = 1;
775     });
776     my $record = MARC::Record->new();
777     my ($biblionumber) = C4::Biblio::AddBiblio($record,'');
778     C4::Biblio::ModBiblio($record,$biblionumber,'');
779     is($called,1,"We called to link bibs because not from linker");
780     $called = 0;
781     C4::Biblio::ModBiblio($record,$biblionumber,'',{ disable_autolink => 1 });
782     is($called,0,"We didn't call to link bibs because from linker");
783 };
784
785 subtest "LinkBibHeadingsToAuthorities tests" => sub {
786     plan tests => 5;
787
788     # Set up mocks to return more than 1 match
789     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
790     $biblio_mod->mock( 'get_link', sub {
791         return (undef, undef, 2);
792     });
793     # UNIMARC return values should be consistent with MARC21
794     # testing with MARC21 should be sufficient for now
795     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
796     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '0');
797
798     my $linker = C4::Linker::Default->new();
799     my $biblio = $builder->build_sample_biblio();
800     my $record = $biblio->metadata->record;
801
802     # Generate a field, no current link
803     my $field = MARC::Field->new('650','','','a' => 'Duplicated' );
804
805     $record->append_fields($field);
806     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
807     is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
808     is_deeply( $results->{unlinked},
809         {"Duplicated" => 1 },
810         "The heading was not linked"
811     );
812     is_deeply( $results->{details}[0],
813         {
814             tag => 650,
815             authid => undef,
816             status => 'MULTIPLE_MATCH',
817             auth_type => 'TOPIC_TERM',
818             tag_to_report => 150
819         },
820         "The heading was not linked"
821     );
822
823     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
824     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
825     is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
826     is_deeply( $results->{details}[0],
827         {
828             tag => 650,
829             authid => undef,
830             status => 'MULTIPLE_MATCH',
831             auth_type => 'TOPIC_TERM',
832             tag_to_report => 150
833         },
834         "When AutoCreateAuthorities is enabled, multiple results are reported"
835     );
836
837 };
838
839 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
840     plan tests => 12;
841
842     # Set up mocks to ensure authorities are generated
843     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
844     $biblio_mod->mock( 'get_link', sub {
845         return (undef,undef);
846     });
847     # UNIMARC valid headings are built from the marc_subfield_structure for bibs and
848     # include all subfields as valid, testing with MARC21 should be sufficient for now
849     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
850     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
851
852     my $linker = C4::Linker::Default->new();
853     my $biblio = $builder->build_sample_biblio();
854     my $record = $biblio->metadata->record;
855
856     # Generate a record including all valid subfields and an invalid one 'e'
857     my $field = MARC::Field->new('650','','','a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted');
858
859     $record->append_fields($field);
860     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650);
861
862     is( $num_headings_changed, 1, 'We changed the one we passed' );
863     is_deeply( $results->{added},
864         {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 },
865         "We added an authority record for the heading"
866     );
867
868     # Now we check the authority record itself
869     my $authority = GetAuthority( $record->subfield('650','9') );
870     is( $authority->field('150')->as_string(),
871         "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
872         "The generated record contains the correct subfields"
873     );
874
875     #Add test for this case using verbose
876     $record->field('650')->delete_subfield('9');
877     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 650, 1);
878     is( $num_headings_changed, 1, 'We changed the one we passed' );
879     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
880
881     # Now we check the authority record itself
882     $authority = GetAuthority($results->{details}->[0]->{authid});
883
884     is( $authority->field('150')->as_string(),
885          "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
886          "The generated record contains the correct subfields when using verbose"
887     );
888
889     # Example series link with volume and punctuation
890     $field = MARC::Field->new('800','','','a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1');
891     $record->append_fields($field);
892
893     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800);
894
895     is( $num_headings_changed, 1, 'We changed the one we passed' );
896     is_deeply( $results->{added},
897         {"Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 },
898         "We added an authority record for the heading"
899     );
900
901     # Now we check the authority record itself
902     $authority = GetAuthority( $record->subfield('800','9') );
903     is( $authority->field('100')->as_string(),
904         "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
905         "The generated record contains the correct subfields"
906     );
907
908     # The same example With verbose
909     $record->field('800')->delete_subfield('9');
910     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800, 1);
911     is( $num_headings_changed, 1, 'We changed the one we passed' );
912     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
913
914     # Now we check the authority record itself
915     $authority = GetAuthority($results->{details}->[0]->{authid});
916     is( $authority->field('100')->as_string(),
917          "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
918          "The generated record contains the correct subfields"
919     );
920 };
921
922 subtest 'autoControlNumber tests' => sub {
923
924     plan tests => 3;
925
926     t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
927
928     my $record = MARC::Record->new();
929     my ($biblio_id) = C4::Biblio::AddBiblio($record, '');
930     my $biblio = Koha::Biblios->find($biblio_id);
931
932     $record = $biblio->metadata->record;
933     is($record->field('001'), undef, '001 not set when pref is off');
934
935     t::lib::Mocks::mock_preference('autoControlNumber', 'biblionumber');
936     C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
937     $biblio->discard_changes;
938     $record = $biblio->metadata->record;
939     is($record->field('001')->as_string(), $biblio_id, '001 set to biblionumber when pref set and field is blank');
940
941     $record->field('001')->update('Not biblionumber');
942     C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
943     $biblio->discard_changes;
944     $record = $biblio->metadata->record;
945     is($record->field('001')->as_string(), 'Not biblionumber', '001 not set to biblionumber when pref set and field exists');
946
947 };
948
949 subtest 'record test' => sub {
950     plan tests => 1;
951
952     my $marc_record = MARC::Record->new;
953     $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
954
955     my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
956
957     my $biblio = Koha::Biblios->find($biblionumber);
958
959     is( $biblio->record->as_formatted,
960         $biblio->metadata->record->as_formatted );
961 };
962
963 subtest 'record_schema test' => sub {
964     plan tests => 1;
965
966     my $marc_record = MARC::Record->new;
967     $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
968
969     my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
970
971     my $biblio = Koha::Biblios->find($biblionumber);
972
973     is( $biblio->record_schema,
974         $biblio->metadata->schema );
975 };
976
977
978 subtest 'GetFrameworkCode' => sub {
979     plan tests => 4;
980
981     my $biblio = $builder->build_sample_biblio({ frameworkcode => 'OBP' });
982
983     is(GetFrameworkCode($biblio->biblionumber), 'OBP', 'GetFrameworkCode returns correct frameworkcode');
984
985     my $cache = Koha::Cache::Memory::Lite->get_instance();
986     my $cache_key = "FrameworkCode-" . $biblio->biblionumber;
987     my $frameworkcode = $cache->get_from_cache($cache_key);
988     is($frameworkcode, 'OBP', 'Cache has been set in GetFrameworkCode');
989
990     # Set new value directly in cache to make sure it's actually being used
991     $cache->set_in_cache($cache_key, 'OD');
992     is(GetFrameworkCode($biblio->biblionumber), 'OD', 'GetFrameworkCode returns correct frameworkcode, using cache');
993
994     # Test cache invalidation
995     ModBiblio($biblio->metadata->record, $biblio->biblionumber, 'OGR');
996     is(GetFrameworkCode($biblio->biblionumber), 'OGR', 'GetFrameworkCode returns correct frameworkcode after setting a new one though ModBiblio');
997
998 };
999
1000 subtest 'ModBiblio on invalid record' => sub {
1001     plan tests => 3;
1002
1003     t::lib::Mocks::mock_preference( "CataloguingLog", 1 );
1004
1005     # We create a record with an onvalid control character in the MARC
1006     my $record = MARC::Record->new();
1007     my $field  = MARC::Field->new( '650', '', '', 'a' => '00\1faD000015937' );
1008     $record->append_fields($field);
1009
1010     my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' );
1011
1012     warning_like { C4::Biblio::ModBiblio( $record, $biblionumber, '' ); }
1013     qr/parser error : PCDATA invalid Char value 31/,
1014         'Modding the biblio warns about the encoding issues';
1015     my $action_logs =
1016         Koha::ActionLogs->search( { object => $biblionumber, module => 'Cataloguing', action => 'MODIFY' } );
1017     is( $action_logs->count, 1, "Modification of biblio was successful and recorded" );
1018     my $action_log = $action_logs->next;
1019     like(
1020         $action_log->info, qr/parser error : PCDATA invalid Char value 31/,
1021         "Metadata issue successfully logged in action logs"
1022     );
1023 };
1024
1025 subtest 'UpdateTotalIssues on Invalid record' => sub {
1026     plan tests => 2;
1027
1028     my $return_record = Test::MockModule->new('Koha::Biblio::Metadata');
1029     $return_record->mock( 'record', sub {
1030         my $self = shift;
1031         Koha::Exceptions::Metadata::Invalid->throw(
1032             id             => $self->id,
1033             biblionumber   => $self->biblionumber,
1034             format         => $self->format,
1035             schema         => $self->schema,
1036             decoding_error => "Error goes here",
1037         );
1038     } );
1039
1040     my $biblio             = $builder->build_sample_biblio;
1041     my $biblionumber       = $biblio->biblionumber;
1042     my $biblio_metadata_id = $biblio->metadata->id;
1043
1044     my $increase = 1;
1045
1046     my $success;
1047     warnings_like {
1048         $success = C4::Biblio::UpdateTotalIssues( $biblio->biblionumber, $increase, '' );
1049     }
1050     [
1051         qr/Invalid data, cannot decode metadata object/,
1052         qr/UpdateTotalIssues could not get bibliographic record for biblionumber $biblionumber/
1053     ],
1054         "Expected warning found";
1055
1056     ok( !$success, 'UpdateTotalIssues fails gracefully for invalid record' );
1057
1058 };
1059
1060
1061 # Cleanup
1062 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
1063 $schema->storage->txn_rollback;