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