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