Bug 19096: Adjusts unit tests
[koha.git] / t / db_dependent / Biblio.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 9;
21 use Test::MockModule;
22 use List::MoreUtils qw( uniq );
23 use MARC::Record;
24
25 use t::lib::Mocks qw( mock_preference );
26 use t::lib::TestBuilder;
27
28 use Koha::Database;
29 use Koha::Caches;
30 use Koha::MarcSubfieldStructures;
31
32 BEGIN {
33     use_ok('C4::Biblio');
34 }
35
36 my $schema = Koha::Database->new->schema;
37 $schema->storage->txn_begin;
38 my $dbh = C4::Context->dbh;
39 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
40
41 subtest 'GetMarcSubfieldStructureFromKohaField' => sub {
42     plan tests => 25;
43
44     my @columns = qw(
45         tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab
46         authorised_value authtypecode value_builder isurl hidden frameworkcode
47         seealso link defaultvalue maxlength
48     );
49
50     # biblio.biblionumber must be mapped so this should return something
51     my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
52
53     ok(defined $marc_subfield_structure, "There is a result");
54     is(ref $marc_subfield_structure, "HASH", "Result is a hashref");
55     foreach my $col (@columns) {
56         ok(exists $marc_subfield_structure->{$col}, "Hashref contains key '$col'");
57     }
58     is($marc_subfield_structure->{kohafield}, 'biblio.biblionumber', "Result is the good result");
59     like($marc_subfield_structure->{tagfield}, qr/^\d{3}$/, "tagfield is a valid tagfield");
60
61     # Add a test for list context (BZ 10306)
62     my @results = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber');
63     is( @results, 1, 'We expect only one mapping' );
64     is_deeply( $results[0], $marc_subfield_structure,
65         'The first entry should be the same hashref as we had before' );
66
67     # foo.bar does not exist so this should return undef
68     $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar');
69     is($marc_subfield_structure, undef, "invalid kohafield returns undef");
70
71 };
72
73 subtest "GetMarcSubfieldStructure" => sub {
74     plan tests => 5;
75
76     # Add multiple Koha to Marc mappings
77     Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete;
78     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store;
79     Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store;
80     Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
81     my $structure = C4::Biblio::GetMarcSubfieldStructure('');
82
83     is( @{ $structure->{"mytable.nicepages"} }, 2,
84         'GetMarcSubfieldStructure should return two entries for nicepages' );
85     is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399',
86         'Check tagfield for first entry' );
87     is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a',
88         'Check tagsubfield for first entry' );
89     is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399',
90         'Check tagfield for second entry' );
91     is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b',
92         'Check tagsubfield for second entry' );
93 };
94
95 subtest "GetMarcFromKohaField" => sub {
96     plan tests => 8;
97
98     #NOTE: We are building on data from the previous subtest
99     # With: field 399 / mytable.nicepages
100
101     # Check call in list context for multiple mappings
102     my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages');
103     is( @retval, 4, 'Should return two tags and subfields' );
104     is( $retval[0], '399', 'Check first tag' );
105     is( $retval[1], 'a', 'Check first subfield' );
106     is( $retval[2], '399', 'Check second tag' );
107     is( $retval[3], 'b', 'Check second subfield' );
108
109     # Check same call in scalar context
110     is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), '399',
111         'GetMarcFromKohaField returns first tag in scalar context' );
112
113     # Bug 19096 Default is authoritative
114     # If we add a new empty framework, we should still get the mappings
115     # from Default. CAUTION: This test passes intentionally the obsoleted
116     # framework parameter.
117     my $new_fw = t::lib::TestBuilder->new->build({source => 'BiblioFramework'});
118     @retval = C4::Biblio::GetMarcFromKohaField(
119         'mytable.nicepages', $new_fw->{frameworkcode},
120     );
121     is( @retval, 4, 'Still got two pairs of tags/subfields' );
122     is( $retval[0].$retval[1], '399a', 'Including 399a' );
123 };
124
125 # Mocking variables
126 my $biblio_module = new Test::MockModule('C4::Biblio');
127 $biblio_module->mock(
128     'GetMarcSubfieldStructure',
129     sub {
130         my ($self) = shift;
131
132         my ( $title_field,            $title_subfield )            = get_title_field();
133         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
134         my ( $issn_field,             $issn_subfield )             = get_issn_field();
135         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
136         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
137         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
138
139         return {
140             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
141             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
142             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
143             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
144             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
145             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
146         };
147       }
148 );
149
150 my $currency = new Test::MockModule('Koha::Acquisition::Currencies');
151 $currency->mock(
152     'get_active',
153     sub {
154         return Koha::Acquisition::Currency->new(
155             {   symbol   => '$',
156                 isocode  => 'USD',
157                 currency => 'USD',
158                 active   => 1,
159             }
160         );
161     }
162 );
163
164 sub run_tests {
165
166     my $marcflavour = shift;
167     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
168
169     my $isbn = '0590353403';
170     my $title = 'Foundation';
171
172     # Generate a record with just the ISBN
173     my $marc_record = MARC::Record->new;
174     $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) );
175
176     # Add the record to the DB
177     my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' );
178     my $data = GetBiblioData( $biblionumber );
179     is( $data->{ isbn }, $isbn,
180         '(GetBiblioData) ISBN correctly retireved.');
181     is( $data->{ title }, undef,
182         '(GetBiblioData) Title field is empty in fresh biblio.');
183
184     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
185     my $marc = GetMarcBiblio({ biblionumber => $biblionumber });
186     is( $marc->subfield( $isbn_field, $isbn_subfield ), $isbn, );
187
188     # Add title
189     my $field = create_title_field( $title, $marcflavour );
190     $marc_record->append_fields( $field );
191     ModBiblio( $marc_record, $biblionumber ,'' );
192     $data = GetBiblioData( $biblionumber );
193     is( $data->{ title }, $title,
194         'ModBiblio correctly added the title field, and GetBiblioData.');
195     is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.');
196     $marc = GetMarcBiblio({ biblionumber => $biblionumber });
197     my ( $title_field, $title_subfield ) = get_title_field();
198     is( $marc->subfield( $title_field, $title_subfield ), $title, );
199
200     my $itemdata = GetBiblioItemData( $biblioitemnumber );
201     is( $itemdata->{ title }, $title,
202         'First test of GetBiblioItemData to get same result of previous two GetBiblioData tests.');
203     is( $itemdata->{ isbn }, $isbn,
204         'Second test checking it returns the correct isbn.');
205
206     my $success = 0;
207     $field = MARC::Field->new(
208             655, ' ', ' ',
209             'a' => 'Auction catalogs',
210             '9' => '1'
211             );
212     eval {
213         $marc_record->append_fields($field);
214         $success = ModBiblio($marc_record,$biblionumber,'');
215     } or do {
216         diag($@);
217         $success = 0;
218     };
219     ok($success, "ModBiblio handles authority-linked 655");
220
221     eval {
222         $field->delete_subfields('a');
223         $marc_record->append_fields($field);
224         $success = ModBiblio($marc_record,$biblionumber,'');
225     } or do {
226         diag($@);
227         $success = 0;
228     };
229     ok($success, "ModBiblio handles 655 with authority link but no heading");
230
231     eval {
232         $field->delete_subfields('9');
233         $marc_record->append_fields($field);
234         $success = ModBiblio($marc_record,$biblionumber,'');
235     } or do {
236         diag($@);
237         $success = 0;
238     };
239     ok($success, "ModBiblio handles 655 with no subfields");
240
241     ## Testing GetMarcISSN
242     my $issns;
243     $issns = GetMarcISSN( $marc_record, $marcflavour );
244     is( $issns->[0], undef,
245         'GetMarcISSN handles records without the ISSN field (list is empty)' );
246     is( scalar @$issns, 0,
247         'GetMarcISSN handles records without the ISSN field (count is 0)' );
248     # Add an ISSN field
249     my $issn = '1234-1234';
250     $field = create_issn_field( $issn, $marcflavour );
251     $marc_record->append_fields($field);
252     $issns = GetMarcISSN( $marc_record, $marcflavour );
253     is( $issns->[0], $issn,
254         'GetMarcISSN handles records with a single ISSN field (first element is correct)' );
255     is( scalar @$issns, 1,
256         'GetMARCISSN handles records with a single ISSN field (count is 1)');
257     # Add multiple ISSN field
258     my @more_issns = qw/1111-1111 2222-2222 3333-3333/;
259     foreach (@more_issns) {
260         $field = create_issn_field( $_, $marcflavour );
261         $marc_record->append_fields($field);
262     }
263     $issns = GetMarcISSN( $marc_record, $marcflavour );
264     is( scalar @$issns, 4,
265         'GetMARCISSN handles records with multiple ISSN fields (count correct)');
266     # Create an empty ISSN
267     $field = create_issn_field( "", $marcflavour );
268     $marc_record->append_fields($field);
269     $issns = GetMarcISSN( $marc_record, $marcflavour );
270     is( scalar @$issns, 4,
271         'GetMARCISSN skips empty ISSN fields (Bug 12674)');
272
273     ## Testing GetMarcControlnumber
274     my $controlnumber;
275     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
276     is( $controlnumber, '', 'GetMarcControlnumber handles records without 001' );
277
278     $field = MARC::Field->new( '001', '' );
279     $marc_record->append_fields($field);
280     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
281     is( $controlnumber, '', 'GetMarcControlnumber handles records with empty 001' );
282
283     $field = $marc_record->field('001');
284     $field->update('123456789X');
285     $controlnumber = GetMarcControlnumber( $marc_record, $marcflavour );
286     is( $controlnumber, '123456789X', 'GetMarcControlnumber handles records with 001' );
287
288     ## Testing GetMarcISBN
289     my $record_for_isbn = MARC::Record->new();
290     my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
291     is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN');
292
293     # We add one ISBN
294     $isbn_field = create_isbn_field( $isbn, $marcflavour );
295     $record_for_isbn->append_fields( $isbn_field );
296     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
297     is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN');
298     is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN');
299
300     # We add 3 more ISBNs
301     $record_for_isbn = MARC::Record->new();
302     my @more_isbns = qw/1111111111 2222222222 3333333333 444444444/;
303     foreach (@more_isbns) {
304         $field = create_isbn_field( $_, $marcflavour );
305         $record_for_isbn->append_fields($field);
306     }
307     $isbns = GetMarcISBN( $record_for_isbn, $marcflavour );
308     is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs');
309     for my $i (0 .. $#more_isbns) {
310         is( $isbns->[$i], $more_isbns[$i],
311             "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1));
312     }
313
314     is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100,
315         "GetMarcPrice returns the correct value");
316     my $newincbiblioitemnumber=$biblioitemnumber+1;
317     $dbh->do("UPDATE biblioitems SET biblioitemnumber = ? WHERE biblionumber = ?;", undef, $newincbiblioitemnumber, $biblionumber );
318     my $updatedrecord = GetMarcBiblio({
319         biblionumber => $biblionumber,
320         embed_items  => 0 });
321     my $frameworkcode = GetFrameworkCode($biblionumber);
322     my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
323     die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
324     my $biblioitemnumbertotest;
325     if ( $biblioitem_tag < 10 ) {
326         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->data();
327     } else {
328         $biblioitemnumbertotest = $updatedrecord->field($biblioitem_tag)->subfield($biblioitem_subfield);
329     }
330     is ($newincbiblioitemnumber, $biblioitemnumbertotest, 'Check newincbiblioitemnumber');
331
332     # test for GetMarcNotes
333     my $a1= GetMarcNotes( $marc_record, $marcflavour );
334     my $field2 = MARC::Field->new( $marcflavour eq 'UNIMARC'? 300: 555, 0, '', a=> 'Some text', u=> 'http://url-1.com', u=> 'nohttp://something_else' );
335     $marc_record->append_fields( $field2 );
336     my $a2= GetMarcNotes( $marc_record, $marcflavour );
337     is( ( $marcflavour eq 'UNIMARC' && @$a2 == @$a1 + 1 ) ||
338         ( $marcflavour ne 'UNIMARC' && @$a2 == @$a1 + 3 ), 1,
339         'Check the number of returned notes of GetMarcNotes' );
340
341     # test for GetMarcUrls
342     $marc_record->append_fields(
343         MARC::Field->new( '856', '', '', u => ' https://koha-community.org ' ),
344         MARC::Field->new( '856', '', '', u => 'koha-community.org' ),
345     );
346     my $marcurl = GetMarcUrls( $marc_record, $marcflavour );
347     is( @$marcurl, 2, 'GetMarcUrls returns two URLs' );
348     like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' );
349     ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//,
350         'GetMarcUrls prefixed a MARC21 URL with http://' );
351 }
352
353 sub get_title_field {
354     my $marc_flavour = C4::Context->preference('marcflavour');
355     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
356 }
357
358 sub get_isbn_field {
359     my $marc_flavour = C4::Context->preference('marcflavour');
360     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
361 }
362
363 sub get_issn_field {
364     my $marc_flavour = C4::Context->preference('marcflavour');
365     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
366 }
367
368 sub get_itemnumber_field {
369     my $marc_flavour = C4::Context->preference('marcflavour');
370     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
371 }
372
373 sub create_title_field {
374     my ( $title, $marcflavour ) = @_;
375
376     my ( $title_field, $title_subfield ) = get_title_field();
377     my $field = MARC::Field->new( $title_field, '', '', $title_subfield => $title );
378
379     return $field;
380 }
381
382 sub create_isbn_field {
383     my ( $isbn, $marcflavour ) = @_;
384
385     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
386     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
387
388     # Add the price subfield
389     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
390     $field->add_subfields( $price_subfield => '$100' );
391
392     return $field;
393 }
394
395 sub create_issn_field {
396     my ( $issn, $marcflavour ) = @_;
397
398     my ( $issn_field, $issn_subfield ) = get_issn_field();
399     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
400
401     return $field;
402 }
403
404 subtest 'MARC21' => sub {
405     plan tests => 34;
406     run_tests('MARC21');
407     $schema->storage->txn_rollback;
408     $schema->storage->txn_begin;
409 };
410
411 subtest 'UNIMARC' => sub {
412     plan tests => 34;
413     run_tests('UNIMARC');
414     $schema->storage->txn_rollback;
415     $schema->storage->txn_begin;
416 };
417
418 subtest 'NORMARC' => sub {
419     plan tests => 34;
420     run_tests('NORMARC');
421     $schema->storage->txn_rollback;
422     $schema->storage->txn_begin;
423 };
424
425 subtest 'IsMarcStructureInternal' => sub {
426     plan tests => 6;
427     my $tagslib = GetMarcStructure();
428     my @internals;
429     for my $tag ( sort keys %$tagslib ) {
430         next unless $tag;
431         for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
432             push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
433         }
434     }
435     @internals = uniq @internals;
436     is( scalar(@internals), 4, 'expect four internals');
437     is( grep( /^lib$/, @internals ), 1, 'check lib' );
438     is( grep( /^tab$/, @internals ), 1, 'check tab' );
439     is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' );
440     is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' );
441     is( grep( /^a$/, @internals ), 0, 'no subfield a' );
442 };
443
444 subtest 'deletedbiblio_metadata' => sub {
445     plan tests => 2;
446
447     my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, '');
448     my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber );
449     C4::Biblio::DelBiblio( $biblionumber );
450     my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber);
451     is( $moved, $biblionumber, 'Found in deletedbiblio' );
452     ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber);
453     is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' );
454 };
455
456 # Cleanup
457 Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" );
458 $schema->storage->txn_rollback;