Bug 8643: Fix IsMarcStructureInternal tests
[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 => 13;
21 use Test::MockModule;
22 use List::MoreUtils qw( uniq );
23 use MARC::Record;
24
25 use t::lib::Mocks qw( mock_preference );
26 use t::lib::TestBuilder;
27
28 use Koha::Database;
29 use Koha::Caches;
30 use Koha::MarcSubfieldStructures;
31
32 BEGIN {
33     use_ok('C4::Biblio');
34 }
35
36 my $schema = Koha::Database->new->schema;
37 $schema->storage->txn_begin;
38 my $dbh = C4::Context->dbh;
39 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
40
41 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
42     plan tests => 25;
43
44     my @columns = qw(
45         tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
46         authorised_value authtypecode value_builder isurl hidden frameworkcode
47         seealso link defaultvalue maxlength
48     );
49
50     # biblio.biblionumber must be mapped so this should return something
51     my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
52
53     ok(defined $marc_subfield_structure, "There is a result");
54     is(ref $marc_subfield_structure, "HASH", "Result is a hashref");
55     foreach my $col (@columns) {
56         ok(exists $marc_subfield_structure->{$col}, "Hashref contains key '$col'");
57     }
58     is($marc_subfield_structure->{kohafield}, 'biblio.biblionumber', "Result is the good result");
59     like($marc_subfield_structure->{tagfield}, qr/^\d{3}$/, "tagfield is a valid tagfield");
60
61     # Add a test for list context (BZ 10306)
62     my @results = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
63     is( @results, 1, 'We expect only one mapping' );
64     is_deeply( $results[0], $marc_subfield_structure,
65         'The first entry should be the same hashref as we had before' );
66
67     # foo.bar does not exist so this should return undef
68     $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar');
69     is($marc_subfield_structure, undef, "invalid kohafield returns undef");
70
71 };
72
73 subtest "GetMarcSubfieldStructure" => sub {
74     plan tests => 5;
75
76     # Add multiple Koha to Marc mappings
77     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete;
78     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store;
79     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store;
80     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
81     my $structure = C4::Biblio::GetMarcSubfieldStructure('');
82
83     is( @{ $structure->{"mytable.nicepages"} }, 2,
84         'GetMarcSubfieldStructure should return two entries for nicepages' );
85     is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399',
86         'Check tagfield for first entry' );
87     is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a',
88         'Check tagsubfield for first entry' );
89     is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399',
90         'Check tagfield for second entry' );
91     is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b',
92         'Check tagsubfield for second entry' );
93 };
94
95 subtest "GetMarcFromKohaField" => sub {
96     plan tests => 8;
97
98     #NOTE: We are building on data from the previous subtest
99     # With: field 399 / mytable.nicepages
100
101     # Check call in list context for multiple mappings
102     my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages');
103     is( @retval, 4, 'Should return two tags and subfields' );
104     is( $retval[0], '399', 'Check first tag' );
105     is( $retval[1], 'a', 'Check first subfield' );
106     is( $retval[2], '399', 'Check second tag' );
107     is( $retval[3], 'b', 'Check second subfield' );
108
109     # Check same call in scalar context
110     is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
111         'GetMarcFromKohaField returns first tag in scalar context' );
112
113     # Bug 19096 Default is authoritative
114     # If we add a new empty framework, we should still get the mappings
115     # from Default. CAUTION: This test passes intentionally the obsoleted
116     # framework parameter.
117     my $new_fw = t::lib::TestBuilder->new->build({source => 'BiblioFramework'});
118     @retval = C4::Biblio::GetMarcFromKohaField(
119         'mytable.nicepages', $new_fw->{frameworkcode},
120     );
121     is( @retval, 4, 'Still got two pairs of tags/subfields' );
122     is( $retval[0].$retval[1], '399a', 'Including 399a' );
123 };
124
125 # Mocking variables
126 my $biblio_module = new Test::MockModule('C4::Biblio');
127 $biblio_module->mock(
128     'GetMarcSubfieldStructure',
129     sub {
130         my ($self) = shift;
131
132         my ( $title_field,            $title_subfield )            = get_title_field();
133         my ( $subtitle_field,         $subtitle_subfield )         = get_subtitle_field();
134         my ( $medium_field,           $medium_subfield )           = get_medium_field();
135         my ( $part_number_field,      $part_number_subfield )      = get_part_number_field();
136         my ( $part_name_field,        $part_name_subfield )        = get_part_name_field();
137         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
138         my ( $issn_field,             $issn_subfield )             = get_issn_field();
139         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
140         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
141         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
142
143         return {
144             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
145             'biblio.subtitle'              => [ { tagfield => $subtitle_field,         tagsubfield => $subtitle_subfield } ],
146             'biblio.medium'                => [ { tagfield => $medium_field,           tagsubfield => $medium_subfield } ],
147             'biblio.part_number'           => [ { tagfield => $part_number_field,      tagsubfield => $part_number_subfield } ],
148             'biblio.part_name'             => [ { tagfield => $part_name_field,        tagsubfield => $part_name_subfield } ],
149             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
150             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
151             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
152             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
153             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
154         };
155       }
156 );
157
158 my $currency = new Test::MockModule('Koha::Acquisition::Currencies');
159 $currency->mock(
160     'get_active',
161     sub {
162         return Koha::Acquisition::Currency->new(
163             {   symbol   => '$',
164                 isocode  => 'USD',
165                 currency => 'USD',
166                 active   => 1,
167             }
168         );
169     }
170 );
171
172 sub run_tests {
173
174     my $marcflavour = shift;
175     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
176
177     my $isbn = '0590353403';
178     my $title = 'Foundation';
179     my $subtitle1 = 'Research';
180     my $subtitle2 = 'Conclusions';
181     my $medium = 'Medium';
182     my $part_number = '123';
183     my $part_name = 'First years';
184
185     # Generate a record with just the ISBN
186     my $marc_record = MARC::Record->new;
187     $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
188
189     # Add the record to the DB
190     my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
191     my $data = GetBiblioData( $biblionumber );
192     is( $data->{ isbn }, $isbn,
193         '(GetBiblioData) ISBN correctly retireved.');
194     is( $data->{ title }, undef,
195         '(GetBiblioData) Title field is empty in fresh biblio.');
196
197     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
198     my $marc = GetMarcBiblio({ biblionumber => $biblionumber });
199     is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
200
201     # Add title
202     my $field = create_title_field( $title, $marcflavour );
203     $marc_record->append_fields( $field );
204     ModBiblio( $marc_record, $biblionumber ,'' );
205     $data = GetBiblioData( $biblionumber );
206     is( $data->{ title }, $title,
207         'ModBiblio correctly added the title field, and GetBiblioData.');
208     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
209     $marc = GetMarcBiblio({ biblionumber => $biblionumber });
210     my ( $title_field, $title_subfield ) = get_title_field();
211     is( $marc->subfield( $title_field, $title_subfield ), $title, );
212
213     # Add other fields
214     $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) );
215     $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) );
216     $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) );
217     $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) );
218     $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) );
219
220     ModBiblio( $marc_record, $biblionumber ,'' );
221     $data = GetBiblioData( $biblionumber );
222     is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' );
223     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' );
224
225     is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' );
226     is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' );
227     is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' );
228     is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' );
229
230     my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber );
231     is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now
232         'Do not know if this makes sense - compare result of previous two GetBiblioData tests.');
233     is( $biblioitem->isbn, $isbn,
234         'Second test checking it returns the correct isbn.');
235
236     my $success = 0;
237     $field = MARC::Field->new(
238             655, ' ', ' ',
239             'a' => 'Auction catalogs',
240             '9' => '1'
241             );
242     eval {
243         $marc_record->append_fields($field);
244         $success = ModBiblio($marc_record,$biblionumber,'');
245     } or do {
246         diag($@);
247         $success = 0;
248     };
249     ok($success, "ModBiblio handles authority-linked 655");
250
251     eval {
252         $field->delete_subfields('a');
253         $marc_record->append_fields($field);
254         $success = ModBiblio($marc_record,$biblionumber,'');
255     } or do {
256         diag($@);
257         $success = 0;
258     };
259     ok($success, "ModBiblio handles 655 with authority link but no heading");
260
261     eval {
262         $field->delete_subfields('9');
263         $marc_record->append_fields($field);
264         $success = ModBiblio($marc_record,$biblionumber,'');
265     } or do {
266         diag($@);
267         $success = 0;
268     };
269     ok($success, "ModBiblio handles 655 with no subfields");
270
271     ## Testing GetMarcISSN
272     my $issns;
273     $issns = GetMarcISSN( $marc_record, $marcflavour );
274     is( $issns->[0], undef,
275         'GetMarcISSN handles records without the ISSN field (list is empty)' );
276     is( scalar @$issns, 0,
277         'GetMarcISSN handles records without the ISSN field (count is 0)' );
278     # Add an ISSN field
279     my $issn = '1234-1234';
280     $field = create_issn_field( $issn, $marcflavour );
281     $marc_record->append_fields($field);
282     $issns = GetMarcISSN( $marc_record, $marcflavour );
283     is( $issns->[0], $issn,
284         'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
285     is( scalar @$issns, 1,
286         'GetMARCISSN handles records with a single ISSN field (count is 1)');
287     # Add multiple ISSN field
288     my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
289     foreach (@more_issns) {
290         $field = create_issn_field( $_, $marcflavour );
291         $marc_record->append_fields($field);
292     }
293     $issns = GetMarcISSN( $marc_record, $marcflavour );
294     is( scalar @$issns, 4,
295         'GetMARCISSN handles records with multiple ISSN fields (count correct)');
296     # Create an empty ISSN
297     $field = create_issn_field( "", $marcflavour );
298     $marc_record->append_fields($field);
299     $issns = GetMarcISSN( $marc_record, $marcflavour );
300     is( scalar @$issns, 4,
301         'GetMARCISSN skips empty ISSN fields (Bug 12674)');
302
303     ## Testing GetMarcControlnumber
304     my $controlnumber;
305     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
306     is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
307
308     $field = MARC::Field->new( '001', '' );
309     $marc_record->append_fields($field);
310     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
311     is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
312
313     $field = $marc_record->field('001');
314     $field->update('123456789X');
315     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
316     is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
317
318     ## Testing GetMarcISBN
319     my $record_for_isbn = MARC::Record->new();
320     my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
321     is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
322
323     # We add one ISBN
324     $isbn_field = create_isbn_field( $isbn, $marcflavour );
325     $record_for_isbn->append_fields( $isbn_field );
326     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
327     is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
328     is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
329
330     # We add 3 more ISBNs
331     $record_for_isbn = MARC::Record->new();
332     my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
333     foreach (@more_isbns) {
334         $field = create_isbn_field( $_, $marcflavour );
335         $record_for_isbn->append_fields($field);
336     }
337     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
338     is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
339     for my $i (0 .. $#more_isbns) {
340         is( $isbns->[$i], $more_isbns[$i],
341             "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
342     }
343
344     is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
345         "GetMarcPrice returns the correct value");
346     my $newincbiblioitemnumber=$biblioitemnumber+1;
347     $dbh->do("UPDATE biblioitems SET biblioitemnumber = ? WHERE biblionumber = ?;", undef, $newincbiblioitemnumber, $biblionumber );
348     my $updatedrecord = GetMarcBiblio({
349         biblionumber => $biblionumber,
350         embed_items  => 0 });
351     my $frameworkcode = GetFrameworkCode($biblionumber);
352     my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
353     die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
354     my $biblioitemnumbertotest;
355     if ( $biblioitem_tag < 10 ) {
356         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
357     } else {
358         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
359     }
360     is ($newincbiblioitemnumber, $biblioitemnumbertotest, 'Check newincbiblioitemnumber');
361
362     # test for GetMarcNotes
363     my $a1= GetMarcNotes( $marc_record, $marcflavour );
364     my $field2 = MARC::Field->new( $marcflavour eq 'UNIMARC'? 300: 555, 0, '', a=> 'Some text', u=> 'http://url-1.com', u=> 'nohttp://something_else' );
365     $marc_record->append_fields( $field2 );
366     my $a2= GetMarcNotes( $marc_record, $marcflavour );
367     is( ( $marcflavour eq 'UNIMARC' && @$a2 == @$a1 + 1 ) ||
368         ( $marcflavour ne 'UNIMARC' && @$a2 == @$a1 + 3 ), 1,
369         'Check the number of returned notes of GetMarcNotes' );
370
371     # test for GetMarcUrls
372     $marc_record->append_fields(
373         MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
374         MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
375     );
376     my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
377     is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
378     like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
379     ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
380         'GetMarcUrls prefixed a MARC21 URL with http://' );
381
382     # Automatic authority creation
383     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 1);
384     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
385     my $authorities_mod = Test::MockModule->new( 'C4::AuthoritiesMarc' );
386     $authorities_mod->mock(
387         'SearchAuthorities',
388         sub {
389             my @results;
390             return \@results, 0;
391         }
392     );
393     $success = 0;
394     $field = create_author_field('Author Name');
395     eval {
396         $marc_record->append_fields($field);
397         $success = ModBiblio($marc_record,$biblionumber,'');
398     } or do {
399         diag($@);
400         $success = 0;
401     };
402     ok($success, "ModBiblio handles authority addition for author");
403
404     my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field();
405     $field = $marc_record->field($author_field);
406     ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact");
407
408     my $authid = $field->subfield('9');
409     ok($authid, 'ModBiblio adds authority id');
410
411     use_ok('C4::AuthoritiesMarc');
412     my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
413     ok($auth_record, 'Authority record successfully retrieved');
414
415
416     my ($auth_author_field, $auth_author_subfield) = get_auth_author_field();
417     $field = $auth_record->field($auth_author_field);
418     ok($field, "Authority record contains field $auth_author_field");
419     is(
420         $field->subfield($auth_author_subfield),
421         'Author Name',
422         'Authority $auth_author_field$auth_author_subfield contains author name'
423     );
424     is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
425
426     # Reset settings
427     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 0);
428     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
429 }
430
431 sub get_title_field {
432     my $marc_flavour = C4::Context->preference('marcflavour');
433     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
434 }
435
436 sub get_medium_field {
437     my $marc_flavour = C4::Context->preference('marcflavour');
438     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
439 }
440
441 sub get_subtitle_field {
442     my $marc_flavour = C4::Context->preference('marcflavour');
443     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
444 }
445
446 sub get_part_number_field {
447     my $marc_flavour = C4::Context->preference('marcflavour');
448     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
449 }
450
451 sub get_part_name_field {
452     my $marc_flavour = C4::Context->preference('marcflavour');
453     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
454 }
455
456 sub get_isbn_field {
457     my $marc_flavour = C4::Context->preference('marcflavour');
458     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
459 }
460
461 sub get_issn_field {
462     my $marc_flavour = C4::Context->preference('marcflavour');
463     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
464 }
465
466 sub get_itemnumber_field {
467     my $marc_flavour = C4::Context->preference('marcflavour');
468     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
469 }
470
471 sub get_author_field {
472     my $marc_flavour = C4::Context->preference('marcflavour');
473     return ( $marc_flavour eq 'UNIMARC' ) ? ( '700', 'a', '4' ) : ( '100', 'a', 'e' );
474 }
475
476 sub get_auth_author_field {
477     my $marc_flavour = C4::Context->preference('marcflavour');
478     return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
479 }
480
481 sub create_title_field {
482     my ( $title, $marcflavour ) = @_;
483
484     my ( $title_field, $title_subfield ) = get_title_field();
485     my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
486
487     return $field;
488 }
489
490 sub create_field {
491     my ( $content, $marcflavour, $field, $subfield ) = @_;
492
493     return MARC::Field->new( $field, '', '', $subfield => $content );
494 }
495
496 sub create_isbn_field {
497     my ( $isbn, $marcflavour ) = @_;
498
499     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
500     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
501
502     # Add the price subfield
503     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
504     $field->add_subfields( $price_subfield => '$100' );
505
506     return $field;
507 }
508
509 sub create_issn_field {
510     my ( $issn, $marcflavour ) = @_;
511
512     my ( $issn_field, $issn_subfield ) = get_issn_field();
513     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
514
515     return $field;
516 }
517
518 sub create_author_field {
519     my ( $author ) = @_;
520
521     my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field();
522     my $field = MARC::Field->new(
523         $author_field, '', '',
524         $author_subfield => $author,
525         $author_relator_subfield => 'aut'
526     );
527
528     return $field;
529 }
530
531 subtest 'MARC21' => sub {
532     plan tests => 48;
533     run_tests('MARC21');
534     $schema->storage->txn_rollback;
535     $schema->storage->txn_begin;
536 };
537
538 subtest 'UNIMARC' => sub {
539     plan tests => 48;
540
541     # Mock the auth type data for UNIMARC
542     $dbh->do("UPDATE auth_types SET auth_tag_to_report = '106' WHERE auth_tag_to_report = '100'") or die $dbh->errstr;
543
544     run_tests('UNIMARC');
545     $schema->storage->txn_rollback;
546     $schema->storage->txn_begin;
547 };
548
549 subtest 'NORMARC' => sub {
550     plan tests => 48;
551     run_tests('NORMARC');
552     $schema->storage->txn_rollback;
553     $schema->storage->txn_begin;
554 };
555
556 subtest 'IsMarcStructureInternal' => sub {
557     plan tests => 9;
558     my $tagslib = GetMarcStructure();
559     my @internals;
560     for my $tag ( sort keys %$tagslib ) {
561         next unless $tag;
562         for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
563             push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
564         }
565     }
566     @internals = uniq @internals;
567     is( scalar(@internals), 7, 'expect 7 internals');
568     is( grep( /^lib$/, @internals ), 1, 'check lib' );
569     is( grep( /^tab$/, @internals ), 1, 'check tab' );
570     is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
571     is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
572     is( grep( /^important$/, @internals ), 1, 'check important' );
573     is( grep( /^a$/, @internals ), 0, 'no subfield a' );
574     is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' );
575     is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' );
576 };
577
578 subtest 'deletedbiblio_metadata' => sub {
579     plan tests => 2;
580
581     my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
582     my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
583     C4::Biblio::DelBiblio( $biblionumber );
584     my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
585     is( $moved, $biblionumber, 'Found in deletedbiblio' );
586     ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
587     is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
588 };
589
590 subtest 'DelBiblio' => sub {
591     plan tests => 2;
592
593     my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, '');
594     my $deleted = C4::Biblio::DelBiblio( $biblionumber );
595     is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead!
596
597     $deleted = C4::Biblio::DelBiblio( $biblionumber );
598     is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
599 };
600
601 subtest 'MarcFieldForCreatorAndModifier' => sub {
602     plan tests => 8;
603
604     t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a');
605     t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b');
606     t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c');
607     t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d');
608     my $c4_context = Test::MockModule->new('C4::Context');
609     $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; });
610
611     my $record = MARC::Record->new();
612     my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
613
614     $record = GetMarcBiblio({biblionumber => $biblionumber});
615     is($record->subfield('998', 'a'), 123, '998$a = 123');
616     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
617     is($record->subfield('998', 'c'), 123, '998$c = 123');
618     is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe');
619
620     $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
621     C4::Biblio::ModBiblio($record, $biblionumber, '');
622
623     $record = GetMarcBiblio({biblionumber => $biblionumber});
624     is($record->subfield('998', 'a'), 123, '998$a = 123');
625     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
626     is($record->subfield('998', 'c'), 321, '998$c = 321');
627     is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe');
628 };
629
630 subtest 'ModBiblio called from linker test' => sub {
631     plan tests => 2;
632     my $called = 0;
633     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 1);
634     my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
635     $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
636         $called = 1;
637     });
638     my $record = MARC::Record->new();
639     my ($biblionumber) = C4::Biblio::AddBiblio($record,'');
640     C4::Biblio::ModBiblio($record,$biblionumber,'');
641     is($called,1,"We called to link bibs because not from linker");
642     $called = 0;
643     C4::Biblio::ModBiblio($record,$biblionumber,'',1);
644     is($called,0,"We didn't call to link bibs because from linker");
645 };
646
647 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
648     plan tests => 3;
649
650     # Set up mocks to ensure authorities are generated
651     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
652     $biblio_mod->mock( 'get_link', sub {
653         return (undef,undef);
654     });
655     # UNIMARC valid headings are built from the marc_subfield_structure for bibs and
656     # include all subfields as valid, testing with MARC21 should be sufficient for now
657     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
658     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
659
660     my $linker = C4::Linker::Default->new();
661     my $record = MARC::Record->new();
662
663     # Generate a record including all valid subfields and an invalid one 'e'
664     my $field = MARC::Field->new('650','','','a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted');
665
666     $record->append_fields($field);
667     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef);
668
669     is( $num_headings_changed, 1, 'We changed the one we passed' );
670     is_deeply( $results->{added},
671         {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 },
672         "We added an authority record for the heading"
673     );
674
675     # Now we check the authority record itself
676     my $authority = GetAuthority( $record->subfield('650','9') );
677     is( $authority->field('150')->as_string(),
678         "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
679         "The generated record contains the correct subfields"
680     );
681
682 };
683
684 # Cleanup
685 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
686 $schema->storage->txn_rollback;