3 # This file is part of Koha.
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.
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.
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>.
20 use Test::More tests => 21;
23 use List::MoreUtils qw( uniq );
26 use t::lib::Mocks qw( mock_preference );
27 use t::lib::TestBuilder;
32 use Koha::MarcSubfieldStructures;
34 use C4::Linker::Default qw( get_link );
37 use_ok('C4::Biblio', qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcControlnumber GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio ));
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-" );
45 my $builder = t::lib::TestBuilder->new;
47 subtest 'AddBiblio' => sub {
50 my $marcflavour = 'MARC21';
51 t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour );
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);
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'
69 is( Koha::Biblios->count, $nb_biblios,
70 'No biblio should have been added if something went wrong' );
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);
78 warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
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'
86 is( Koha::Biblios->count, $nb_biblios + 1,
87 'The biblio should have been added if nothing went wrong' );
89 t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour );
90 t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', $marcflavour );
91 t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" );
93 my $mock_biblio = Test::MockModule->new("C4::Biblio");
94 $mock_biblio->mock( BiblioAutoLink => sub {
96 my $frameworkcode = shift;
97 warn "My biblionumber is ".$record->subfield('999','c')." and my frameworkcode is $frameworkcode";
99 warning_like { $builder->build_sample_biblio(); }
100 qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink";
104 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
108 tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
109 authorised_value authtypecode value_builder isurl hidden frameworkcode
110 seealso link defaultvalue maxlength
113 # biblio.biblionumber must be mapped so this should return something
114 my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
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'");
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");
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' );
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");
136 subtest "GetMarcSubfieldStructure" => sub {
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('');
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' );
158 subtest "GetMarcFromKohaField" => sub {
161 #NOTE: We are building on data from the previous subtest
162 # With: field 399 / mytable.nicepages
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' );
172 # Check same call in scalar context
173 is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
174 'GetMarcFromKohaField returns first tag in scalar context' );
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},
184 is( @retval, 4, 'Still got two pairs of tags/subfields' );
185 is( $retval[0].$retval[1], '399a', 'Including 399a' );
188 subtest "Authority creation with default linker" => sub {
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(
200 my $results = [{ authid => 'original' },{ authid => 'duplicate' }];
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");
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");
219 my $biblio_module = Test::MockModule->new('C4::Biblio');
220 $biblio_module->mock(
221 'GetMarcSubfieldStructure',
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();
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 } ],
251 my $currency = Test::MockModule->new('Koha::Acquisition::Currencies');
255 return Koha::Acquisition::Currency->new(
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');
274 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
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';
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 ) );
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.');
296 my $biblio = Koha::Biblios->find($biblionumber);
298 my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
299 my $marc = $biblio->metadata->record;
300 is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
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, );
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() ) );
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.' );
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.' );
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.');
338 $field = MARC::Field->new(
340 'a' => 'Auction catalogs',
344 $marc_record->append_fields($field);
345 $success = ModBiblio($marc_record,$biblionumber,'');
350 ok($success, "ModBiblio handles authority-linked 655");
353 $field->delete_subfields('a');
354 $marc_record->append_fields($field);
355 $success = ModBiblio($marc_record,$biblionumber,'');
360 ok($success, "ModBiblio handles 655 with authority link but no heading");
363 $field->delete_subfields('9');
364 $marc_record->append_fields($field);
365 $success = ModBiblio($marc_record,$biblionumber,'');
370 ok($success, "ModBiblio handles 655 with no subfields");
372 ## Testing GetMarcISSN
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)' );
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);
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)');
404 ## Testing GetMarcControlnumber
406 $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
407 is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
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' );
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' );
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');
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');
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);
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));
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();
455 $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
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' ),
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://' );
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(
481 $field = create_author_field('Author Name');
483 $marc_record->append_fields($field);
484 $success = ModBiblio($marc_record,$biblionumber,'');
489 ok($success, "ModBiblio handles authority addition for author");
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");
495 my $authid = $field->subfield('9');
496 ok($authid, 'ModBiblio adds authority id');
498 use_ok('C4::AuthoritiesMarc', qw( GetAuthority ));
499 my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
500 ok($auth_record, 'Authority record successfully retrieved');
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");
507 $field->subfield($auth_author_subfield),
509 'Authority $auth_author_field$auth_author_subfield contains author name'
511 is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
514 t::lib::Mocks::mock_preference('AutoLinkBiblios', 0);
515 t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
518 sub get_title_field {
519 my $marc_flavour = C4::Context->preference('marcflavour');
520 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
523 sub get_medium_field {
524 my $marc_flavour = C4::Context->preference('marcflavour');
525 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
528 sub get_subtitle_field {
529 my $marc_flavour = C4::Context->preference('marcflavour');
530 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
533 sub get_part_number_field {
534 my $marc_flavour = C4::Context->preference('marcflavour');
535 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
538 sub get_part_name_field {
539 my $marc_flavour = C4::Context->preference('marcflavour');
540 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
544 my $marc_flavour = C4::Context->preference('marcflavour');
545 return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
549 my $marc_flavour = C4::Context->preference('marcflavour');
550 return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
553 sub get_itemnumber_field {
554 my $marc_flavour = C4::Context->preference('marcflavour');
555 return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
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' );
563 sub get_auth_author_field {
564 my $marc_flavour = C4::Context->preference('marcflavour');
565 return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
568 sub create_title_field {
569 my ( $title, $marcflavour ) = @_;
571 my ( $title_field, $title_subfield ) = get_title_field();
572 my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
578 my ( $content, $marcflavour, $field, $subfield ) = @_;
580 return MARC::Field->new( $field, '', '', $subfield => $content );
583 sub create_isbn_field {
584 my ( $isbn, $marcflavour ) = @_;
586 my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
587 my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
589 # Add the price subfield
590 my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
591 $field->add_subfields( $price_subfield => '$100' );
596 sub create_issn_field {
597 my ( $issn, $marcflavour ) = @_;
599 my ( $issn_field, $issn_subfield ) = get_issn_field();
600 my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
605 sub create_author_field {
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'
618 subtest 'MARC21' => sub {
621 $schema->storage->txn_rollback;
622 $schema->storage->txn_begin;
625 subtest 'UNIMARC' => sub {
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;
631 run_tests('UNIMARC');
632 $schema->storage->txn_rollback;
633 $schema->storage->txn_begin;
636 subtest 'IsMarcStructureInternal' => sub {
638 my $tagslib = GetMarcStructure();
640 for my $tag ( sort keys %$tagslib ) {
642 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
643 push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
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' );
658 subtest 'deletedbiblio_metadata' => sub {
661 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
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' );
672 subtest 'DelBiblio' => sub {
676 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
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!
682 $deleted = C4::Biblio::DelBiblio( $biblionumber );
683 is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
685 my $biblio = $builder->build_sample_biblio;
686 my $subscription = $builder->build_object(
688 class => 'Koha::Subscriptions',
689 value => { biblionumber => $biblio->biblionumber }
692 my $serial = $builder->build_object(
694 class => 'Koha::Serials',
696 biblionumber => $biblio->biblionumber,
697 subscriptionid => $subscription->subscriptionid
701 my $subscription_history = $builder->build_object(
703 class => 'Koha::Subscription::Histories',
705 biblionumber => $biblio->biblionumber,
706 subscriptionid => $subscription->subscriptionid
711 my $order_basket = $builder->build( { source => 'Aqbasket' } );
714 biblionumber => $biblio->biblionumber,
715 basketno => $order_basket->{basketno},
717 my $order = $builder->build_object(
718 { class => 'Koha::Acquisition::Orders', value => $orderinfo } );
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 } });
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' );
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' );
738 subtest 'MarcFieldForCreatorAndModifier' => sub {
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'}; });
748 my $record = MARC::Record->new();
749 my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
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');
758 $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
759 C4::Biblio::ModBiblio($record, $biblionumber, '');
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');
768 subtest 'ModBiblio called from linker test' => sub {
771 t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
772 my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
773 $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
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");
781 C4::Biblio::ModBiblio($record,$biblionumber,'',{ disable_autolink => 1 });
782 is($called,0,"We didn't call to link bibs because from linker");
785 subtest "LinkBibHeadingsToAuthorities tests" => sub {
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);
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');
798 my $linker = C4::Linker::Default->new();
799 my $biblio = $builder->build_sample_biblio();
800 my $record = $biblio->metadata->record;
802 # Generate a field, no current link
803 my $field = MARC::Field->new('650','','','a' => 'Duplicated' );
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"
812 is_deeply( $results->{details}[0],
816 status => 'MULTIPLE_MATCH',
817 auth_type => 'TOPIC_TERM',
820 "The heading was not linked"
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],
830 status => 'MULTIPLE_MATCH',
831 auth_type => 'TOPIC_TERM',
834 "When AutoCreateAuthorities is enabled, multiple results are reported"
839 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
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);
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');
852 my $linker = C4::Linker::Default->new();
853 my $biblio = $builder->build_sample_biblio();
854 my $record = $biblio->metadata->record;
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');
859 $record->append_fields($field);
860 my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650);
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"
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"
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");
881 # Now we check the authority record itself
882 $authority = GetAuthority($results->{details}->[0]->{authid});
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"
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);
893 ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800);
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"
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"
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");
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"
922 subtest 'autoControlNumber tests' => sub {
926 t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
928 my $record = MARC::Record->new();
929 my ($biblio_id) = C4::Biblio::AddBiblio($record, '');
930 my $biblio = Koha::Biblios->find($biblio_id);
932 $record = $biblio->metadata->record;
933 is($record->field('001'), undef, '001 not set when pref is off');
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');
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');
949 subtest 'record test' => sub {
952 my $marc_record = MARC::Record->new;
953 $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
955 my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
957 my $biblio = Koha::Biblios->find($biblionumber);
959 is( $biblio->record->as_formatted,
960 $biblio->metadata->record->as_formatted );
963 subtest 'record_schema test' => sub {
966 my $marc_record = MARC::Record->new;
967 $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
969 my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
971 my $biblio = Koha::Biblios->find($biblionumber);
973 is( $biblio->record_schema,
974 $biblio->metadata->schema );
978 subtest 'GetFrameworkCode' => sub {
981 my $biblio = $builder->build_sample_biblio({ frameworkcode => 'OBP' });
983 is(GetFrameworkCode($biblio->biblionumber), 'OBP', 'GetFrameworkCode returns correct frameworkcode');
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');
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');
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');
1000 subtest 'ModBiblio on invalid record' => sub {
1003 t::lib::Mocks::mock_preference( "CataloguingLog", 1 );
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);
1010 my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' );
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';
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;
1020 $action_log->info, qr/parser error : PCDATA invalid Char value 31/,
1021 "Metadata issue successfully logged in action logs"
1025 subtest 'UpdateTotalIssues on Invalid record' => sub {
1028 my $return_record = Test::MockModule->new('Koha::Biblio::Metadata');
1029 $return_record->mock( 'record', sub {
1031 Koha::Exceptions::Metadata::Invalid->throw(
1033 biblionumber => $self->biblionumber,
1034 format => $self->format,
1035 schema => $self->schema,
1036 decoding_error => "Error goes here",
1040 my $biblio = $builder->build_sample_biblio;
1041 my $biblionumber = $biblio->biblionumber;
1042 my $biblio_metadata_id = $biblio->metadata->id;
1048 $success = C4::Biblio::UpdateTotalIssues( $biblio->biblionumber, $increase, '' );
1051 qr/Invalid data, cannot decode metadata object/,
1052 qr/UpdateTotalIssues could not get bibliographic record for biblionumber $biblionumber/
1054 "Expected warning found";
1056 ok( !$success, 'UpdateTotalIssues fails gracefully for invalid record' );
1062 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
1063 $schema->storage->txn_rollback;