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