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 => 19;
23 use List::MoreUtils qw( uniq );
26 use t::lib::Mocks qw( mock_preference );
27 use t::lib::TestBuilder;
31 use Koha::MarcSubfieldStructures;
33 use C4::Linker::Default qw( get_link );
36 use_ok('C4::Biblio', qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcControlnumber GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio ));
39 my $schema = Koha::Database->new->schema;
40 $schema->storage->txn_begin;
41 my $dbh = C4::Context->dbh;
42 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
44 my $builder = t::lib::TestBuilder->new;
46 subtest 'AddBiblio' => sub {
49 my $marcflavour = 'MARC21';
50 t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour );
52 my ( $f, $sf ) = GetMarcFromKohaField('biblioitems.cn_item');
53 my $cn_item_field = MARC::Field->new( $f, ' ', ' ',
54 $sf => 'Thisisgoingtobetoomanycharactersforthe.cn_item.field' );
55 my $record = MARC::Record->new();
56 $record->append_fields($cn_item_field);
58 my $nb_biblios = Koha::Biblios->count;
59 my ( $biblionumber, $biblioitemnumber );
60 warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
61 [ qr/Data too long for column 'cn_item'/, qr/Data too long for column 'cn_item'/ ],
62 "expected warnings when adding too long cn_item";
63 is( $biblionumber, undef,
64 'AddBiblio returns undef for biblionumber if something went wrong' );
65 is( $biblioitemnumber, undef,
66 'AddBiblio returns undef for biblioitemnumber if something went wrong'
68 is( Koha::Biblios->count, $nb_biblios,
69 'No biblio should have been added if something went wrong' );
71 ( $f, $sf ) = GetMarcFromKohaField('biblioitems.lccn');
72 my $lccn_field = MARC::Field->new( $f, ' ', ' ',
73 $sf => 'ThisisNOTgoingtobetoomanycharactersfortheLCCNfield' );
74 $record = MARC::Record->new();
75 $record->append_fields($lccn_field);
77 warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) }
79 "No warning expected when adding a long LCCN";
80 isnt( $biblionumber, undef,
81 'AddBiblio returns the biblionumber' );
82 isnt( $biblioitemnumber, undef,
83 'AddBiblio returns the biblioitemnumber'
85 is( Koha::Biblios->count, $nb_biblios + 1,
86 'The biblio should have been added if nothing went wrong' );
88 t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour );
89 t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', $marcflavour );
90 t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" );
92 my $mock_biblio = Test::MockModule->new("C4::Biblio");
93 $mock_biblio->mock( BiblioAutoLink => sub {
95 my $frameworkcode = shift;
96 warn "My biblionumber is ".$record->subfield('999','c')." and my frameworkcode is $frameworkcode";
98 warning_like { $builder->build_sample_biblio(); }
99 qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink";
103 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
107 tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
108 authorised_value authtypecode value_builder isurl hidden frameworkcode
109 seealso link defaultvalue maxlength
112 # biblio.biblionumber must be mapped so this should return something
113 my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
115 ok(defined $marc_subfield_structure, "There is a result");
116 is(ref $marc_subfield_structure, "HASH", "Result is a hashref");
117 foreach my $col (@columns) {
118 ok(exists $marc_subfield_structure->{$col}, "Hashref contains key '$col'");
120 is($marc_subfield_structure->{kohafield}, 'biblio.biblionumber', "Result is the good result");
121 like($marc_subfield_structure->{tagfield}, qr/^\d{3}$/, "tagfield is a valid tagfield");
123 # Add a test for list context (BZ 10306)
124 my @results = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
125 is( @results, 1, 'We expect only one mapping' );
126 is_deeply( $results[0], $marc_subfield_structure,
127 'The first entry should be the same hashref as we had before' );
129 # foo.bar does not exist so this should return undef
130 $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar');
131 is($marc_subfield_structure, undef, "invalid kohafield returns undef");
135 subtest "GetMarcSubfieldStructure" => sub {
138 # Add multiple Koha to Marc mappings
139 Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete;
140 Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store;
141 Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store;
142 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
143 my $structure = C4::Biblio::GetMarcSubfieldStructure('');
145 is( @{ $structure->{"mytable.nicepages"} }, 2,
146 'GetMarcSubfieldStructure should return two entries for nicepages' );
147 is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399',
148 'Check tagfield for first entry' );
149 is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a',
150 'Check tagsubfield for first entry' );
151 is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399',
152 'Check tagfield for second entry' );
153 is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b',
154 'Check tagsubfield for second entry' );
157 subtest "GetMarcFromKohaField" => sub {
160 #NOTE: We are building on data from the previous subtest
161 # With: field 399 / mytable.nicepages
163 # Check call in list context for multiple mappings
164 my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages');
165 is( @retval, 4, 'Should return two tags and subfields' );
166 is( $retval[0], '399', 'Check first tag' );
167 is( $retval[1], 'a', 'Check first subfield' );
168 is( $retval[2], '399', 'Check second tag' );
169 is( $retval[3], 'b', 'Check second subfield' );
171 # Check same call in scalar context
172 is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
173 'GetMarcFromKohaField returns first tag in scalar context' );
175 # Bug 19096 Default is authoritative
176 # If we add a new empty framework, we should still get the mappings
177 # from Default. CAUTION: This test passes intentionally the obsoleted
178 # framework parameter.
179 my $new_fw = t::lib::TestBuilder->new->build({source => 'BiblioFramework'});
180 @retval = C4::Biblio::GetMarcFromKohaField(
181 'mytable.nicepages', $new_fw->{frameworkcode},
183 is( @retval, 4, 'Still got two pairs of tags/subfields' );
184 is( $retval[0].$retval[1], '399a', 'Including 399a' );
187 subtest "Authority creation with default linker" => sub {
189 # Automatic authority creation
190 t::lib::Mocks::mock_preference('LinkerModule', 'Default');
191 t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
192 t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
193 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
194 my $linker = C4::Linker::Default->new({});
195 my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
196 $authorities_mod->mock(
199 my $results = [{ authid => 'original' },{ authid => 'duplicate' }];
203 my $marc_record = MARC::Record->new();
204 my $field = MARC::Field->new(655, ' ', ' ','a' => 'Magical realism');
205 $marc_record->append_fields( $field );
206 my ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
207 is( $num_changed, 0, "We shouldn't link or create a new record");
208 ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record");
210 ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef);
211 is( $num_changed, 0, "We shouldn't link or create a new record using cached result");
212 ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record on second instance");
218 my $biblio_module = Test::MockModule->new('C4::Biblio');
219 $biblio_module->mock(
220 'GetMarcSubfieldStructure',
224 my ( $title_field, $title_subfield ) = get_title_field();
225 my ( $subtitle_field, $subtitle_subfield ) = get_subtitle_field();
226 my ( $medium_field, $medium_subfield ) = get_medium_field();
227 my ( $part_number_field, $part_number_subfield ) = get_part_number_field();
228 my ( $part_name_field, $part_name_subfield ) = get_part_name_field();
229 my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
230 my ( $issn_field, $issn_subfield ) = get_issn_field();
231 my ( $biblionumber_field, $biblionumber_subfield ) = ( '999', 'c' );
232 my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
233 my ( $itemnumber_field, $itemnumber_subfield ) = get_itemnumber_field();
236 'biblio.title' => [ { tagfield => $title_field, tagsubfield => $title_subfield } ],
237 'biblio.subtitle' => [ { tagfield => $subtitle_field, tagsubfield => $subtitle_subfield } ],
238 'biblio.medium' => [ { tagfield => $medium_field, tagsubfield => $medium_subfield } ],
239 'biblio.part_number' => [ { tagfield => $part_number_field, tagsubfield => $part_number_subfield } ],
240 'biblio.part_name' => [ { tagfield => $part_name_field, tagsubfield => $part_name_subfield } ],
241 'biblio.biblionumber' => [ { tagfield => $biblionumber_field, tagsubfield => $biblionumber_subfield } ],
242 'biblioitems.isbn' => [ { tagfield => $isbn_field, tagsubfield => $isbn_subfield } ],
243 'biblioitems.issn' => [ { tagfield => $issn_field, tagsubfield => $issn_subfield } ],
244 'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
245 'items.itemnumber' => [ { tagfield => $itemnumber_subfield, tagsubfield => $itemnumber_subfield } ],
250 my $currency = Test::MockModule->new('Koha::Acquisition::Currencies');
254 return Koha::Acquisition::Currency->new(
266 my $marcflavour = shift;
267 t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
268 # Authority tests don't interact well with Elasticsearch at the moment due to the fact that there's currently no way to
269 # roll back ES index changes.
270 t::lib::Mocks::mock_preference('SearchEngine', 'Zebra');
271 t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
273 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
275 my $isbn = '0590353403';
276 my $title = 'Foundation';
277 my $subtitle1 = 'Research';
278 my $subtitle2 = 'Conclusions';
279 my $medium = 'Medium';
280 my $part_number = '123';
281 my $part_name = 'First years';
283 # Generate a record with just the ISBN
284 my $marc_record = MARC::Record->new;
285 $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
287 # Add the record to the DB
288 my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
289 my $data = GetBiblioData( $biblionumber );
290 is( $data->{ isbn }, $isbn,
291 '(GetBiblioData) ISBN correctly retireved.');
292 is( $data->{ title }, undef,
293 '(GetBiblioData) Title field is empty in fresh biblio.');
295 my $biblio = Koha::Biblios->find($biblionumber);
297 my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
298 my $marc = $biblio->metadata->record;
299 is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
302 my $field = create_title_field( $title, $marcflavour );
303 $marc_record->append_fields( $field );
304 ModBiblio( $marc_record, $biblionumber ,'' );
305 $data = GetBiblioData( $biblionumber );
306 is( $data->{ title }, $title,
307 'ModBiblio correctly added the title field, and GetBiblioData.');
308 is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
309 $marc = $biblio->get_from_storage->metadata->record;
310 my ( $title_field, $title_subfield ) = get_title_field();
311 is( $marc->subfield( $title_field, $title_subfield ), $title, );
314 $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) );
315 $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) );
316 $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) );
317 $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) );
318 $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) );
320 ModBiblio( $marc_record, $biblionumber ,'' );
321 $data = GetBiblioData( $biblionumber );
322 is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' );
323 is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' );
325 is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' );
326 is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' );
327 is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' );
328 is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' );
330 my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber );
331 is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now
332 'Do not know if this makes sense - compare result of previous two GetBiblioData tests.');
333 is( $biblioitem->isbn, $isbn,
334 'Second test checking it returns the correct isbn.');
337 $field = MARC::Field->new(
339 'a' => 'Auction catalogs',
343 $marc_record->append_fields($field);
344 $success = ModBiblio($marc_record,$biblionumber,'');
349 ok($success, "ModBiblio handles authority-linked 655");
352 $field->delete_subfields('a');
353 $marc_record->append_fields($field);
354 $success = ModBiblio($marc_record,$biblionumber,'');
359 ok($success, "ModBiblio handles 655 with authority link but no heading");
362 $field->delete_subfields('9');
363 $marc_record->append_fields($field);
364 $success = ModBiblio($marc_record,$biblionumber,'');
369 ok($success, "ModBiblio handles 655 with no subfields");
371 ## Testing GetMarcISSN
373 $issns = GetMarcISSN( $marc_record, $marcflavour );
374 is( $issns->[0], undef,
375 'GetMarcISSN handles records without the ISSN field (list is empty)' );
376 is( scalar @$issns, 0,
377 'GetMarcISSN handles records without the ISSN field (count is 0)' );
379 my $issn = '1234-1234';
380 $field = create_issn_field( $issn, $marcflavour );
381 $marc_record->append_fields($field);
382 $issns = GetMarcISSN( $marc_record, $marcflavour );
383 is( $issns->[0], $issn,
384 'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
385 is( scalar @$issns, 1,
386 'GetMARCISSN handles records with a single ISSN field (count is 1)');
387 # Add multiple ISSN field
388 my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
389 foreach (@more_issns) {
390 $field = create_issn_field( $_, $marcflavour );
391 $marc_record->append_fields($field);
393 $issns = GetMarcISSN( $marc_record, $marcflavour );
394 is( scalar @$issns, 4,
395 'GetMARCISSN handles records with multiple ISSN fields (count correct)');
396 # Create an empty ISSN
397 $field = create_issn_field( "", $marcflavour );
398 $marc_record->append_fields($field);
399 $issns = GetMarcISSN( $marc_record, $marcflavour );
400 is( scalar @$issns, 4,
401 'GetMARCISSN skips empty ISSN fields (Bug 12674)');
403 ## Testing GetMarcControlnumber
405 $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
406 is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
408 $field = MARC::Field->new( '001', '' );
409 $marc_record->append_fields($field);
410 $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
411 is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
413 $field = $marc_record->field('001');
414 $field->update('123456789X');
415 $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
416 is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
418 ## Testing GetMarcISBN
419 my $record_for_isbn = MARC::Record->new();
420 my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
421 is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
424 $isbn_field = create_isbn_field( $isbn, $marcflavour );
425 $record_for_isbn->append_fields( $isbn_field );
426 $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
427 is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
428 is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
430 # We add 3 more ISBNs
431 $record_for_isbn = MARC::Record->new();
432 my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
433 foreach (@more_isbns) {
434 $field = create_isbn_field( $_, $marcflavour );
435 $record_for_isbn->append_fields($field);
437 $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
438 is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
439 for my $i (0 .. $#more_isbns) {
440 is( $isbns->[$i], $more_isbns[$i],
441 "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
444 is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
445 "GetMarcPrice returns the correct value");
446 my $frameworkcode = GetFrameworkCode($biblionumber);
447 my $updatedrecord = $biblio->metadata->record;
448 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
449 die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
450 my $biblioitemnumbertotest;
451 if ( $biblioitem_tag < 10 ) {
452 $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
454 $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
457 # test for GetMarcUrls
458 $marc_record->append_fields(
459 MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
460 MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
462 my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
463 is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
464 like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
465 ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
466 'GetMarcUrls prefixed a MARC21 URL with http://' );
468 # Automatic authority creation
469 t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
470 t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
471 my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
472 $authorities_mod->mock(
480 $field = create_author_field('Author Name');
482 $marc_record->append_fields($field);
483 $success = ModBiblio($marc_record,$biblionumber,'');
488 ok($success, "ModBiblio handles authority addition for author");
490 my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field();
491 $field = $marc_record->field($author_field);
492 ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact");
494 my $authid = $field->subfield('9');
495 ok($authid, 'ModBiblio adds authority id');
497 use_ok('C4::AuthoritiesMarc', qw( GetAuthority ));
498 my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
499 ok($auth_record, 'Authority record successfully retrieved');
502 my ($auth_author_field, $auth_author_subfield) = get_auth_author_field();
503 $field = $auth_record->field($auth_author_field);
504 ok($field, "Authority record contains field $auth_author_field");
506 $field->subfield($auth_author_subfield),
508 'Authority $auth_author_field$auth_author_subfield contains author name'
510 is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
513 t::lib::Mocks::mock_preference('AutoLinkBiblios', 0);
514 t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
517 sub get_title_field {
518 my $marc_flavour = C4::Context->preference('marcflavour');
519 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
522 sub get_medium_field {
523 my $marc_flavour = C4::Context->preference('marcflavour');
524 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
527 sub get_subtitle_field {
528 my $marc_flavour = C4::Context->preference('marcflavour');
529 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
532 sub get_part_number_field {
533 my $marc_flavour = C4::Context->preference('marcflavour');
534 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
537 sub get_part_name_field {
538 my $marc_flavour = C4::Context->preference('marcflavour');
539 return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
543 my $marc_flavour = C4::Context->preference('marcflavour');
544 return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
548 my $marc_flavour = C4::Context->preference('marcflavour');
549 return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
552 sub get_itemnumber_field {
553 my $marc_flavour = C4::Context->preference('marcflavour');
554 return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
557 sub get_author_field {
558 my $marc_flavour = C4::Context->preference('marcflavour');
559 return ( $marc_flavour eq 'UNIMARC' ) ? ( '700', 'a', '4' ) : ( '100', 'a', 'e' );
562 sub get_auth_author_field {
563 my $marc_flavour = C4::Context->preference('marcflavour');
564 return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
567 sub create_title_field {
568 my ( $title, $marcflavour ) = @_;
570 my ( $title_field, $title_subfield ) = get_title_field();
571 my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
577 my ( $content, $marcflavour, $field, $subfield ) = @_;
579 return MARC::Field->new( $field, '', '', $subfield => $content );
582 sub create_isbn_field {
583 my ( $isbn, $marcflavour ) = @_;
585 my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
586 my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
588 # Add the price subfield
589 my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
590 $field->add_subfields( $price_subfield => '$100' );
595 sub create_issn_field {
596 my ( $issn, $marcflavour ) = @_;
598 my ( $issn_field, $issn_subfield ) = get_issn_field();
599 my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
604 sub create_author_field {
607 my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field();
608 my $field = MARC::Field->new(
609 $author_field, '', '',
610 $author_subfield => $author,
611 $author_relator_subfield => 'aut'
617 subtest 'MARC21' => sub {
620 $schema->storage->txn_rollback;
621 $schema->storage->txn_begin;
624 subtest 'UNIMARC' => sub {
627 # Mock the auth type data for UNIMARC
628 $dbh->do("UPDATE auth_types SET auth_tag_to_report = '106' WHERE auth_tag_to_report = '100'") or die $dbh->errstr;
630 run_tests('UNIMARC');
631 $schema->storage->txn_rollback;
632 $schema->storage->txn_begin;
635 subtest 'IsMarcStructureInternal' => sub {
637 my $tagslib = GetMarcStructure();
639 for my $tag ( sort keys %$tagslib ) {
641 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
642 push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
645 @internals = uniq @internals;
646 is( scalar(@internals), 7, 'expect 7 internals');
647 is( grep( /^lib$/, @internals ), 1, 'check lib' );
648 is( grep( /^tab$/, @internals ), 1, 'check tab' );
649 is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
650 is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
651 is( grep( /^important$/, @internals ), 1, 'check important' );
652 is( grep( /^a$/, @internals ), 0, 'no subfield a' );
653 is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' );
654 is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' );
657 subtest 'deletedbiblio_metadata' => sub {
660 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
662 my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
663 my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
664 C4::Biblio::DelBiblio( $biblionumber );
665 my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
666 is( $moved, $biblionumber, 'Found in deletedbiblio' );
667 ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
668 is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
671 subtest 'DelBiblio' => sub {
675 t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 );
677 my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, '');
678 my $deleted = C4::Biblio::DelBiblio( $biblionumber );
679 is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead!
681 $deleted = C4::Biblio::DelBiblio( $biblionumber );
682 is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
684 my $biblio = $builder->build_sample_biblio;
685 my $subscription = $builder->build_object(
687 class => 'Koha::Subscriptions',
688 value => { biblionumber => $biblio->biblionumber }
691 my $serial = $builder->build_object(
693 class => 'Koha::Serials',
695 biblionumber => $biblio->biblionumber,
696 subscriptionid => $subscription->subscriptionid
700 my $subscription_history = $builder->build_object(
702 class => 'Koha::Subscription::Histories',
704 biblionumber => $biblio->biblionumber,
705 subscriptionid => $subscription->subscriptionid
710 my $order_basket = $builder->build( { source => 'Aqbasket' } );
713 biblionumber => $biblio->biblionumber,
714 basketno => $order_basket->{basketno},
716 my $order = $builder->build_object(
717 { class => 'Koha::Acquisition::Orders', value => $orderinfo } );
719 # Add some ILL requests
720 my $ill_req_1 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
721 my $ill_req_2 = $builder->build_object({ class => 'Koha::Illrequests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } });
723 C4::Biblio::DelBiblio($biblio->biblionumber); # Or $biblio->delete
724 is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' );
725 is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' );
726 is( $subscription_history->get_from_storage, undef, 'subscription history should be deleted on biblio deletion' );
727 is( $order->get_from_storage->deleted_biblionumber, $biblio->biblionumber, 'biblionumber of order has been moved to deleted_biblionumber column' );
729 $ill_req_1 = $ill_req_1->get_from_storage;
730 $ill_req_2 = $ill_req_2->get_from_storage;
731 is( $ill_req_1->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
732 is( $ill_req_1->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
733 is( $ill_req_2->biblio_id, undef, 'biblio_id cleared on biblio deletion' );
734 is( $ill_req_2->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' );
737 subtest 'MarcFieldForCreatorAndModifier' => sub {
740 t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a');
741 t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b');
742 t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c');
743 t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d');
744 my $c4_context = Test::MockModule->new('C4::Context');
745 $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; });
747 my $record = MARC::Record->new();
748 my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
750 my $biblio = Koha::Biblios->find($biblionumber);
751 $record = $biblio->metadata->record;
752 is($record->subfield('998', 'a'), 123, '998$a = 123');
753 is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
754 is($record->subfield('998', 'c'), 123, '998$c = 123');
755 is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe');
757 $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
758 C4::Biblio::ModBiblio($record, $biblionumber, '');
760 $record = $biblio->get_from_storage->metadata->record;
761 is($record->subfield('998', 'a'), 123, '998$a = 123');
762 is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
763 is($record->subfield('998', 'c'), 321, '998$c = 321');
764 is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe');
767 subtest 'ModBiblio called from linker test' => sub {
770 t::lib::Mocks::mock_preference('AutoLinkBiblios', 1);
771 my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
772 $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
775 my $record = MARC::Record->new();
776 my ($biblionumber) = C4::Biblio::AddBiblio($record,'');
777 C4::Biblio::ModBiblio($record,$biblionumber,'');
778 is($called,1,"We called to link bibs because not from linker");
780 C4::Biblio::ModBiblio($record,$biblionumber,'',{ disable_autolink => 1 });
781 is($called,0,"We didn't call to link bibs because from linker");
784 subtest "LinkBibHeadingsToAuthorities tests" => sub {
787 # Set up mocks to return more than 1 match
788 my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
789 $biblio_mod->mock( 'get_link', sub {
790 return (undef, undef, 2);
792 # UNIMARC return values should be consistent with MARC21
793 # testing with MARC21 should be sufficient for now
794 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
795 t::lib::Mocks::mock_preference('AutoCreateAuthorities', '0');
797 my $linker = C4::Linker::Default->new();
798 my $biblio = $builder->build_sample_biblio();
799 my $record = $biblio->metadata->record;
801 # Generate a field, no current link
802 my $field = MARC::Field->new('650','','','a' => 'Duplicated' );
804 $record->append_fields($field);
805 my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
806 is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
807 is_deeply( $results->{unlinked},
808 {"Duplicated" => 1 },
809 "The heading was not linked"
811 is_deeply( $results->{details}[0],
815 status => 'MULTIPLE_MATCH',
816 auth_type => 'TOPIC_TERM',
819 "The heading was not linked"
822 t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
823 ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 );
824 is( $num_headings_changed, 0, 'We did not make any changes because we found 2' );
825 is_deeply( $results->{details}[0],
829 status => 'MULTIPLE_MATCH',
830 auth_type => 'TOPIC_TERM',
833 "When AutoCreateAuthorities is enabled, multiple results are reported"
838 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
841 # Set up mocks to ensure authorities are generated
842 my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
843 $biblio_mod->mock( 'get_link', sub {
844 return (undef,undef);
846 # UNIMARC valid headings are built from the marc_subfield_structure for bibs and
847 # include all subfields as valid, testing with MARC21 should be sufficient for now
848 t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
849 t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
851 my $linker = C4::Linker::Default->new();
852 my $biblio = $builder->build_sample_biblio();
853 my $record = $biblio->metadata->record;
855 # Generate a record including all valid subfields and an invalid one 'e'
856 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 $record->append_fields($field);
859 my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650);
861 is( $num_headings_changed, 1, 'We changed the one we passed' );
862 is_deeply( $results->{added},
863 {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 },
864 "We added an authority record for the heading"
867 # Now we check the authority record itself
868 my $authority = GetAuthority( $record->subfield('650','9') );
869 is( $authority->field('150')->as_string(),
870 "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
871 "The generated record contains the correct subfields"
874 #Add test for this case using verbose
875 $record->field('650')->delete_subfield('9');
876 ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 650, 1);
877 is( $num_headings_changed, 1, 'We changed the one we passed' );
878 is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
880 # Now we check the authority record itself
881 $authority = GetAuthority($results->{details}->[0]->{authid});
883 is( $authority->field('150')->as_string(),
884 "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
885 "The generated record contains the correct subfields when using verbose"
888 # Example series link with volume and punctuation
889 $field = MARC::Field->new('800','','','a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1');
890 $record->append_fields($field);
892 ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800);
894 is( $num_headings_changed, 1, 'We changed the one we passed' );
895 is_deeply( $results->{added},
896 {"Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 },
897 "We added an authority record for the heading"
900 # Now we check the authority record itself
901 $authority = GetAuthority( $record->subfield('800','9') );
902 is( $authority->field('100')->as_string(),
903 "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
904 "The generated record contains the correct subfields"
907 # The same example With verbose
908 $record->field('800')->delete_subfield('9');
909 ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800, 1);
910 is( $num_headings_changed, 1, 'We changed the one we passed' );
911 is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
913 # Now we check the authority record itself
914 $authority = GetAuthority($results->{details}->[0]->{authid});
915 is( $authority->field('100')->as_string(),
916 "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
917 "The generated record contains the correct subfields"
921 subtest 'autoControlNumber tests' => sub {
925 t::lib::Mocks::mock_preference('autoControlNumber', 'OFF');
927 my $record = MARC::Record->new();
928 my ($biblio_id) = C4::Biblio::AddBiblio($record, '');
929 my $biblio = Koha::Biblios->find($biblio_id);
931 $record = $biblio->metadata->record;
932 is($record->field('001'), undef, '001 not set when pref is off');
934 t::lib::Mocks::mock_preference('autoControlNumber', 'biblionumber');
935 C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
936 $biblio->discard_changes;
937 $record = $biblio->metadata->record;
938 is($record->field('001')->as_string(), $biblio_id, '001 set to biblionumber when pref set and field is blank');
940 $record->field('001')->update('Not biblionumber');
941 C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 });
942 $biblio->discard_changes;
943 $record = $biblio->metadata->record;
944 is($record->field('001')->as_string(), 'Not biblionumber', '001 not set to biblionumber when pref set and field exists');
948 subtest 'record test' => sub {
951 my $marc_record = MARC::Record->new;
952 $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
954 my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
956 my $biblio = Koha::Biblios->find($biblionumber);
958 is( $biblio->record->as_formatted,
959 $biblio->metadata->record->as_formatted );
962 subtest 'record_schema test' => sub {
965 my $marc_record = MARC::Record->new;
966 $marc_record->append_fields( create_isbn_field( '0590353403', 'MARC21' ) );
968 my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record, '' );
970 my $biblio = Koha::Biblios->find($biblionumber);
972 is( $biblio->record_schema,
973 $biblio->metadata->schema );
977 subtest 'GetFrameworkCode' => sub {
980 my $biblio = $builder->build_sample_biblio({ frameworkcode => 'OBP' });
982 is(GetFrameworkCode($biblio->biblionumber), 'OBP', 'GetFrameworkCode returns correct frameworkcode');
984 my $cache = Koha::Cache::Memory::Lite->get_instance();
985 my $cache_key = "FrameworkCode-" . $biblio->biblionumber;
986 my $frameworkcode = $cache->get_from_cache($cache_key);
987 is($frameworkcode, 'OBP', 'Cache has been set in GetFrameworkCode');
989 # Set new value directly in cache to make sure it's actually being used
990 $cache->set_in_cache($cache_key, 'OD');
991 is(GetFrameworkCode($biblio->biblionumber), 'OD', 'GetFrameworkCode returns correct frameworkcode, using cache');
993 # Test cache invalidation
994 ModBiblio($biblio->metadata->record, $biblio->biblionumber, 'OGR');
995 is(GetFrameworkCode($biblio->biblionumber), 'OGR', 'GetFrameworkCode returns correct frameworkcode after setting a new one though ModBiblio');
1000 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
1001 $schema->storage->txn_rollback;