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