Bug 25757: Add unit tests for item relation
[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
234     my $isbn = '0590353403';
235     my $title = 'Foundation';
236     my $subtitle1 = 'Research';
237     my $subtitle2 = 'Conclusions';
238     my $medium = 'Medium';
239     my $part_number = '123';
240     my $part_name = 'First years';
241
242     # Generate a record with just the ISBN
243     my $marc_record = MARC::Record->new;
244     $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
245
246     # Add the record to the DB
247     my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
248     my $data = GetBiblioData( $biblionumber );
249     is( $data->{ isbn }, $isbn,
250         '(GetBiblioData) ISBN correctly retireved.');
251     is( $data->{ title }, undef,
252         '(GetBiblioData) Title field is empty in fresh biblio.');
253
254     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
255     my $marc = GetMarcBiblio({ biblionumber => $biblionumber });
256     is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
257
258     # Add title
259     my $field = create_title_field( $title, $marcflavour );
260     $marc_record->append_fields( $field );
261     ModBiblio( $marc_record, $biblionumber ,'' );
262     $data = GetBiblioData( $biblionumber );
263     is( $data->{ title }, $title,
264         'ModBiblio correctly added the title field, and GetBiblioData.');
265     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
266     $marc = GetMarcBiblio({ biblionumber => $biblionumber });
267     my ( $title_field, $title_subfield ) = get_title_field();
268     is( $marc->subfield( $title_field, $title_subfield ), $title, );
269
270     # Add other fields
271     $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) );
272     $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) );
273     $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) );
274     $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) );
275     $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) );
276
277     ModBiblio( $marc_record, $biblionumber ,'' );
278     $data = GetBiblioData( $biblionumber );
279     is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' );
280     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' );
281
282     is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' );
283     is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' );
284     is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' );
285     is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' );
286
287     my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber );
288     is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now
289         'Do not know if this makes sense - compare result of previous two GetBiblioData tests.');
290     is( $biblioitem->isbn, $isbn,
291         'Second test checking it returns the correct isbn.');
292
293     my $success = 0;
294     $field = MARC::Field->new(
295             655, ' ', ' ',
296             'a' => 'Auction catalogs',
297             '9' => '1'
298             );
299     eval {
300         $marc_record->append_fields($field);
301         $success = ModBiblio($marc_record,$biblionumber,'');
302     } or do {
303         diag($@);
304         $success = 0;
305     };
306     ok($success, "ModBiblio handles authority-linked 655");
307
308     eval {
309         $field->delete_subfields('a');
310         $marc_record->append_fields($field);
311         $success = ModBiblio($marc_record,$biblionumber,'');
312     } or do {
313         diag($@);
314         $success = 0;
315     };
316     ok($success, "ModBiblio handles 655 with authority link but no heading");
317
318     eval {
319         $field->delete_subfields('9');
320         $marc_record->append_fields($field);
321         $success = ModBiblio($marc_record,$biblionumber,'');
322     } or do {
323         diag($@);
324         $success = 0;
325     };
326     ok($success, "ModBiblio handles 655 with no subfields");
327
328     ## Testing GetMarcISSN
329     my $issns;
330     $issns = GetMarcISSN( $marc_record, $marcflavour );
331     is( $issns->[0], undef,
332         'GetMarcISSN handles records without the ISSN field (list is empty)' );
333     is( scalar @$issns, 0,
334         'GetMarcISSN handles records without the ISSN field (count is 0)' );
335     # Add an ISSN field
336     my $issn = '1234-1234';
337     $field = create_issn_field( $issn, $marcflavour );
338     $marc_record->append_fields($field);
339     $issns = GetMarcISSN( $marc_record, $marcflavour );
340     is( $issns->[0], $issn,
341         'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
342     is( scalar @$issns, 1,
343         'GetMARCISSN handles records with a single ISSN field (count is 1)');
344     # Add multiple ISSN field
345     my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
346     foreach (@more_issns) {
347         $field = create_issn_field( $_, $marcflavour );
348         $marc_record->append_fields($field);
349     }
350     $issns = GetMarcISSN( $marc_record, $marcflavour );
351     is( scalar @$issns, 4,
352         'GetMARCISSN handles records with multiple ISSN fields (count correct)');
353     # Create an empty ISSN
354     $field = create_issn_field( "", $marcflavour );
355     $marc_record->append_fields($field);
356     $issns = GetMarcISSN( $marc_record, $marcflavour );
357     is( scalar @$issns, 4,
358         'GetMARCISSN skips empty ISSN fields (Bug 12674)');
359
360     ## Testing GetMarcControlnumber
361     my $controlnumber;
362     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
363     is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
364
365     $field = MARC::Field->new( '001', '' );
366     $marc_record->append_fields($field);
367     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
368     is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
369
370     $field = $marc_record->field('001');
371     $field->update('123456789X');
372     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
373     is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
374
375     ## Testing GetMarcISBN
376     my $record_for_isbn = MARC::Record->new();
377     my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
378     is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
379
380     # We add one ISBN
381     $isbn_field = create_isbn_field( $isbn, $marcflavour );
382     $record_for_isbn->append_fields( $isbn_field );
383     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
384     is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
385     is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
386
387     # We add 3 more ISBNs
388     $record_for_isbn = MARC::Record->new();
389     my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
390     foreach (@more_isbns) {
391         $field = create_isbn_field( $_, $marcflavour );
392         $record_for_isbn->append_fields($field);
393     }
394     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
395     is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
396     for my $i (0 .. $#more_isbns) {
397         is( $isbns->[$i], $more_isbns[$i],
398             "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
399     }
400
401     is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
402         "GetMarcPrice returns the correct value");
403     my $newincbiblioitemnumber=$biblioitemnumber+1;
404     $dbh->do("UPDATE biblioitems SET biblioitemnumber = ? WHERE biblionumber = ?;", undef, $newincbiblioitemnumber, $biblionumber );
405     my $updatedrecord = GetMarcBiblio({
406         biblionumber => $biblionumber,
407         embed_items  => 0 });
408     my $frameworkcode = GetFrameworkCode($biblionumber);
409     my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
410     die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
411     my $biblioitemnumbertotest;
412     if ( $biblioitem_tag < 10 ) {
413         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
414     } else {
415         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
416     }
417     is ($newincbiblioitemnumber, $biblioitemnumbertotest, 'Check newincbiblioitemnumber');
418
419     # test for GetMarcNotes
420     my $a1= GetMarcNotes( $marc_record, $marcflavour );
421     my $field2 = MARC::Field->new( $marcflavour eq 'UNIMARC'? 300: 555, 0, '', a=> 'Some text', u=> 'http://url-1.com', u=> 'nohttp://something_else' );
422     $marc_record->append_fields( $field2 );
423     my $a2= GetMarcNotes( $marc_record, $marcflavour );
424     is( ( $marcflavour eq 'UNIMARC' && @$a2 == @$a1 + 1 ) ||
425         ( $marcflavour ne 'UNIMARC' && @$a2 == @$a1 + 3 ), 1,
426         'Check the number of returned notes of GetMarcNotes' );
427
428     # test for GetMarcUrls
429     $marc_record->append_fields(
430         MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
431         MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
432     );
433     my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
434     is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
435     like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
436     ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
437         'GetMarcUrls prefixed a MARC21 URL with http://' );
438
439     # Automatic authority creation
440     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 1);
441     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1);
442     my $authorities_mod = Test::MockModule->new( 'C4::Heading' );
443     $authorities_mod->mock(
444         'authorities',
445         sub {
446             my @results;
447             return \@results;
448         }
449     );
450     $success = 0;
451     $field = create_author_field('Author Name');
452     eval {
453         $marc_record->append_fields($field);
454         $success = ModBiblio($marc_record,$biblionumber,'');
455     } or do {
456         diag($@);
457         $success = 0;
458     };
459     ok($success, "ModBiblio handles authority addition for author");
460
461     my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field();
462     $field = $marc_record->field($author_field);
463     ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact");
464
465     my $authid = $field->subfield('9');
466     ok($authid, 'ModBiblio adds authority id');
467
468     use_ok('C4::AuthoritiesMarc');
469     my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid);
470     ok($auth_record, 'Authority record successfully retrieved');
471
472
473     my ($auth_author_field, $auth_author_subfield) = get_auth_author_field();
474     $field = $auth_record->field($auth_author_field);
475     ok($field, "Authority record contains field $auth_author_field");
476     is(
477         $field->subfield($auth_author_subfield),
478         'Author Name',
479         'Authority $auth_author_field$auth_author_subfield contains author name'
480     );
481     is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield');
482
483     # Reset settings
484     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 0);
485     t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0);
486 }
487
488 sub get_title_field {
489     my $marc_flavour = C4::Context->preference('marcflavour');
490     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
491 }
492
493 sub get_medium_field {
494     my $marc_flavour = C4::Context->preference('marcflavour');
495     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'b' ) : ( '245', 'h' );
496 }
497
498 sub get_subtitle_field {
499     my $marc_flavour = C4::Context->preference('marcflavour');
500     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'e' ) : ( '245', 'b' );
501 }
502
503 sub get_part_number_field {
504     my $marc_flavour = C4::Context->preference('marcflavour');
505     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'h' ) : ( '245', 'n' );
506 }
507
508 sub get_part_name_field {
509     my $marc_flavour = C4::Context->preference('marcflavour');
510     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'i' ) : ( '245', 'p' );
511 }
512
513 sub get_isbn_field {
514     my $marc_flavour = C4::Context->preference('marcflavour');
515     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
516 }
517
518 sub get_issn_field {
519     my $marc_flavour = C4::Context->preference('marcflavour');
520     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
521 }
522
523 sub get_itemnumber_field {
524     my $marc_flavour = C4::Context->preference('marcflavour');
525     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
526 }
527
528 sub get_author_field {
529     my $marc_flavour = C4::Context->preference('marcflavour');
530     return ( $marc_flavour eq 'UNIMARC' ) ? ( '700', 'a', '4' ) : ( '100', 'a', 'e' );
531 }
532
533 sub get_auth_author_field {
534     my $marc_flavour = C4::Context->preference('marcflavour');
535     return ( $marc_flavour eq 'UNIMARC' ) ? ( '106', 'a' ) : ( '100', 'a' );
536 }
537
538 sub create_title_field {
539     my ( $title, $marcflavour ) = @_;
540
541     my ( $title_field, $title_subfield ) = get_title_field();
542     my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
543
544     return $field;
545 }
546
547 sub create_field {
548     my ( $content, $marcflavour, $field, $subfield ) = @_;
549
550     return MARC::Field->new( $field, '', '', $subfield => $content );
551 }
552
553 sub create_isbn_field {
554     my ( $isbn, $marcflavour ) = @_;
555
556     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
557     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
558
559     # Add the price subfield
560     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
561     $field->add_subfields( $price_subfield => '$100' );
562
563     return $field;
564 }
565
566 sub create_issn_field {
567     my ( $issn, $marcflavour ) = @_;
568
569     my ( $issn_field, $issn_subfield ) = get_issn_field();
570     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
571
572     return $field;
573 }
574
575 sub create_author_field {
576     my ( $author ) = @_;
577
578     my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field();
579     my $field = MARC::Field->new(
580         $author_field, '', '',
581         $author_subfield => $author,
582         $author_relator_subfield => 'aut'
583     );
584
585     return $field;
586 }
587
588 subtest 'MARC21' => sub {
589     plan tests => 48;
590     run_tests('MARC21');
591     $schema->storage->txn_rollback;
592     $schema->storage->txn_begin;
593 };
594
595 subtest 'UNIMARC' => sub {
596     plan tests => 48;
597
598     # Mock the auth type data for UNIMARC
599     $dbh->do("UPDATE auth_types SET auth_tag_to_report = '106' WHERE auth_tag_to_report = '100'") or die $dbh->errstr;
600
601     run_tests('UNIMARC');
602     $schema->storage->txn_rollback;
603     $schema->storage->txn_begin;
604 };
605
606 subtest 'NORMARC' => sub {
607     plan tests => 48;
608     run_tests('NORMARC');
609     $schema->storage->txn_rollback;
610     $schema->storage->txn_begin;
611 };
612
613 subtest 'IsMarcStructureInternal' => sub {
614     plan tests => 9;
615     my $tagslib = GetMarcStructure();
616     my @internals;
617     for my $tag ( sort keys %$tagslib ) {
618         next unless $tag;
619         for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
620             push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
621         }
622     }
623     @internals = uniq @internals;
624     is( scalar(@internals), 7, 'expect 7 internals');
625     is( grep( /^lib$/, @internals ), 1, 'check lib' );
626     is( grep( /^tab$/, @internals ), 1, 'check tab' );
627     is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
628     is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
629     is( grep( /^important$/, @internals ), 1, 'check important' );
630     is( grep( /^a$/, @internals ), 0, 'no subfield a' );
631     is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' );
632     is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' );
633 };
634
635 subtest 'deletedbiblio_metadata' => sub {
636     plan tests => 2;
637
638     my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
639     my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
640     C4::Biblio::DelBiblio( $biblionumber );
641     my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
642     is( $moved, $biblionumber, 'Found in deletedbiblio' );
643     ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
644     is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
645 };
646
647 subtest 'DelBiblio' => sub {
648     plan tests => 5;
649
650     my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, '');
651     my $deleted = C4::Biblio::DelBiblio( $biblionumber );
652     is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead!
653
654     $deleted = C4::Biblio::DelBiblio( $biblionumber );
655     is( $deleted, undef, 'DelBiblo should return undef is the record did not exist');
656
657     my $biblio       = $builder->build_sample_biblio;
658     my $subscription = $builder->build_object(
659         {
660             class => 'Koha::Subscriptions',
661             value => { biblionumber => $biblio->biblionumber }
662         }
663     );
664     my $serial = $builder->build_object(
665         {
666             class => 'Koha::Serials',
667             value => {
668                 biblionumber   => $biblio->biblionumber,
669                 subscriptionid => $subscription->subscriptionid
670             }
671         }
672     );
673     my $subscription_history = $builder->build_object(
674         {
675             class => 'Koha::Subscription::Histories',
676             value => {
677                 biblionumber   => $biblio->biblionumber,
678                 subscriptionid => $subscription->subscriptionid
679             }
680         }
681     );
682     C4::Biblio::DelBiblio($biblio->biblionumber); # Or $biblio->delete
683     is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' );
684     is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' );
685     is( $subscription_history->get_from_storage, undef, 'subscription history should be deleted on biblio deletion' );
686 };
687
688 subtest 'MarcFieldForCreatorAndModifier' => sub {
689     plan tests => 8;
690
691     t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a');
692     t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b');
693     t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c');
694     t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d');
695     my $c4_context = Test::MockModule->new('C4::Context');
696     $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; });
697
698     my $record = MARC::Record->new();
699     my ($biblionumber) = C4::Biblio::AddBiblio($record, '');
700
701     $record = GetMarcBiblio({biblionumber => $biblionumber});
702     is($record->subfield('998', 'a'), 123, '998$a = 123');
703     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
704     is($record->subfield('998', 'c'), 123, '998$c = 123');
705     is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe');
706
707     $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; });
708     C4::Biblio::ModBiblio($record, $biblionumber, '');
709
710     $record = GetMarcBiblio({biblionumber => $biblionumber});
711     is($record->subfield('998', 'a'), 123, '998$a = 123');
712     is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe');
713     is($record->subfield('998', 'c'), 321, '998$c = 321');
714     is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe');
715 };
716
717 subtest 'ModBiblio called from linker test' => sub {
718     plan tests => 2;
719     my $called = 0;
720     t::lib::Mocks::mock_preference('BiblioAddsAuthorities', 1);
721     my $biblio_mod = Test::MockModule->new( 'C4::Biblio' );
722     $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub {
723         $called = 1;
724     });
725     my $record = MARC::Record->new();
726     my ($biblionumber) = C4::Biblio::AddBiblio($record,'');
727     C4::Biblio::ModBiblio($record,$biblionumber,'');
728     is($called,1,"We called to link bibs because not from linker");
729     $called = 0;
730     C4::Biblio::ModBiblio($record,$biblionumber,'',1);
731     is($called,0,"We didn't call to link bibs because from linker");
732 };
733
734 subtest "LinkBibHeadingsToAuthorities record generation tests" => sub {
735     plan tests => 12;
736
737     # Set up mocks to ensure authorities are generated
738     my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' );
739     $biblio_mod->mock( 'get_link', sub {
740         return (undef,undef);
741     });
742     # UNIMARC valid headings are built from the marc_subfield_structure for bibs and
743     # include all subfields as valid, testing with MARC21 should be sufficient for now
744     t::lib::Mocks::mock_preference('marcflavour', 'MARC21');
745     t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1');
746
747     my $linker = C4::Linker::Default->new();
748     my $biblio = $builder->build_sample_biblio();
749     my $record = $biblio->metadata->record;
750
751     # Generate a record including all valid subfields and an invalid one 'e'
752     my $field = MARC::Field->new('650','','','a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted');
753
754     $record->append_fields($field);
755     my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650);
756
757     is( $num_headings_changed, 1, 'We changed the one we passed' );
758     is_deeply( $results->{added},
759         {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 },
760         "We added an authority record for the heading"
761     );
762
763     # Now we check the authority record itself
764     my $authority = GetAuthority( $record->subfield('650','9') );
765     is( $authority->field('150')->as_string(),
766         "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
767         "The generated record contains the correct subfields"
768     );
769
770     #Add test for this case using verbose
771     $record->field('650')->delete_subfield('9');
772     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 650, 1);
773     is( $num_headings_changed, 1, 'We changed the one we passed' );
774     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
775
776     # Now we check the authority record itself
777     $authority = GetAuthority($results->{details}->[0]->{authid});
778
779     is( $authority->field('150')->as_string(),
780          "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza",
781          "The generated record contains the correct subfields when using verbose"
782     );
783
784     # Example series link with volume and punctuation
785     $field = MARC::Field->new('800','','','a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1');
786     $record->append_fields($field);
787
788     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800);
789
790     is( $num_headings_changed, 1, 'We changed the one we passed' );
791     is_deeply( $results->{added},
792         {"Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 },
793         "We added an authority record for the heading"
794     );
795
796     # Now we check the authority record itself
797     $authority = GetAuthority( $record->subfield('800','9') );
798     is( $authority->field('100')->as_string(),
799         "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
800         "The generated record contains the correct subfields"
801     );
802
803     # The same example With verbose
804     $record->field('800')->delete_subfield('9');
805     ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800, 1);
806     is( $num_headings_changed, 1, 'We changed the one we passed' );
807     is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose");
808
809     # Now we check the authority record itself
810     $authority = GetAuthority($results->{details}->[0]->{authid});
811     is( $authority->field('100')->as_string(),
812          "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings",
813          "The generated record contains the correct subfields"
814     );
815 };
816
817 # Cleanup
818 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
819 $schema->storage->txn_rollback;