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