Bug 15572: Add tests for TransformHtmlToMarc
[koha.git] / t / db_dependent / Koha.t
1 #!/usr/bin/perl
2 #
3 # This is to test C4/Koha
4 # It requires a working Koha database with the sample data
5
6 use strict;
7 use warnings;
8 use C4::Context;
9 use Koha::DateUtils qw(dt_from_string);
10
11 use Test::More tests => 10;
12 use DateTime::Format::MySQL;
13
14 BEGIN {
15     use_ok('C4::Koha', qw( :DEFAULT GetDailyQuote GetItemTypesByCategory GetItemTypesCategorized));
16     use_ok('C4::Members');
17 }
18
19 my $dbh = C4::Context->dbh;
20 $dbh->{AutoCommit} = 0;
21 $dbh->{RaiseError} = 1;
22
23 subtest 'Authorized Values Tests' => sub {
24     plan tests => 8;
25
26     my $data = {
27         category            => 'CATEGORY',
28         authorised_value    => 'AUTHORISED_VALUE',
29         lib                 => 'LIB',
30         lib_opac            => 'LIBOPAC',
31         imageurl            => 'IMAGEURL'
32     };
33
34
35 # Insert an entry into authorised_value table
36     my $insert_success = AddAuthorisedValue($data->{category}, $data->{authorised_value}, $data->{lib}, $data->{lib_opac}, $data->{imageurl});
37     ok($insert_success, "Insert data in database");
38
39
40 # Tests
41     SKIP: {
42         skip "INSERT failed", 5 unless $insert_success;
43
44         is ( GetAuthorisedValueByCode($data->{category}, $data->{authorised_value}), $data->{lib}, "GetAuthorisedValueByCode" );
45         is ( GetKohaImageurlFromAuthorisedValues($data->{category}, $data->{lib}), $data->{imageurl}, "GetKohaImageurlFromAuthorisedValues" );
46
47         my $sortdet=C4::Members::GetSortDetails("lost", "3");
48         is ($sortdet, "Lost and Paid For", "lost and paid works");
49
50         my $sortdet2=C4::Members::GetSortDetails("loc", "child");
51         is ($sortdet2, "Children's Area", "Child area works");
52
53         my $sortdet3=C4::Members::GetSortDetails("withdrawn", "1");
54         is ($sortdet3, "Withdrawn", "Withdrawn works");
55     }
56
57 # Clean up
58     if($insert_success){
59         my $query = "DELETE FROM authorised_values WHERE category=? AND authorised_value=? AND lib=? AND lib_opac=? AND imageurl=?;";
60         my $sth = $dbh->prepare($query);
61         $sth->execute($data->{category}, $data->{authorised_value}, $data->{lib}, $data->{lib_opac}, $data->{imageurl});
62     }
63
64     SKIP: {
65         eval { require Test::Deep; import Test::Deep; };
66         skip "Test::Deep required to run the GetAuthorisedValues() tests.", 2 if $@;
67         AddAuthorisedValue('BUG10656', 'ZZZ', 'Z_STAFF', 'A_PUBLIC', '');
68         AddAuthorisedValue('BUG10656', 'AAA', 'A_STAFF', 'Z_PUBLIC', '');
69         # the next one sets lib_opac to NULL; in that case, the staff
70         # display value is meant to be used.
71         AddAuthorisedValue('BUG10656', 'DDD', 'D_STAFF', undef, '');
72         my $authvals = GetAuthorisedValues('BUG10656');
73         cmp_deeply(
74             $authvals,
75             [
76                 {
77                     id => ignore(),
78                     category => 'BUG10656',
79                     authorised_value => 'AAA',
80                     selected => 0,
81                     lib => 'A_STAFF',
82                     lib_opac => 'Z_PUBLIC',
83                     imageurl => '',
84                 },
85                 {
86                     id => ignore(),
87                     category => 'BUG10656',
88                     authorised_value => 'DDD',
89                     selected => 0,
90                     lib => 'D_STAFF',
91                     lib_opac => undef,
92                     imageurl => '',
93                 },
94                 {
95                     id => ignore(),
96                     category => 'BUG10656',
97                     authorised_value => 'ZZZ',
98                     selected => 0,
99                     lib => 'Z_STAFF',
100                     lib_opac => 'A_PUBLIC',
101                     imageurl => '',
102                 },
103             ],
104             'list of authorised values in staff mode sorted by staff label (bug 10656)'
105         );
106         $authvals = GetAuthorisedValues('BUG10656', '', 1);
107         cmp_deeply(
108             $authvals,
109             [
110                 {
111                     id => ignore(),
112                     category => 'BUG10656',
113                     authorised_value => 'ZZZ',
114                     selected => 0,
115                     lib => 'A_PUBLIC',
116                     lib_opac => 'A_PUBLIC',
117                     imageurl => '',
118                 },
119                 {
120                     id => ignore(),
121                     category => 'BUG10656',
122                     authorised_value => 'DDD',
123                     selected => 0,
124                     lib => 'D_STAFF',
125                     lib_opac => undef,
126                     imageurl => '',
127                 },
128                 {
129                     id => ignore(),
130                     category => 'BUG10656',
131                     authorised_value => 'AAA',
132                     selected => 0,
133                     lib => 'Z_PUBLIC',
134                     lib_opac => 'Z_PUBLIC',
135                     imageurl => '',
136                 },
137             ],
138             'list of authorised values in OPAC mode sorted by OPAC label (bug 10656)'
139         );
140     }
141
142 };
143
144 subtest 'Itemtype info Tests' => sub {
145     like ( getitemtypeinfo('BK')->{'imageurl'}, qr/intranet-tmpl/, 'getitemtypeinfo on unspecified interface returns intranet imageurl (legacy behavior)' );
146     like ( getitemtypeinfo('BK', 'intranet')->{'imageurl'}, qr/intranet-tmpl/, 'getitemtypeinfo on "intranet" interface returns intranet imageurl' );
147     like ( getitemtypeinfo('BK', 'opac')->{'imageurl'}, qr/opac-tmpl/, 'getitemtypeinfo on "opac" interface returns opac imageurl' );
148 };
149
150 ### test for C4::Koha->GetDailyQuote()
151 SKIP:
152     {
153         eval { require Test::Deep; import Test::Deep; };
154         skip "Test::Deep required to run the GetDailyQuote tests.", 1 if $@;
155
156         subtest 'Daily Quotes Test' => sub {
157             plan tests => 4;
158
159             SKIP: {
160
161                 skip "C4::Koha can't \'GetDailyQuote\'!", 3 unless can_ok('C4::Koha','GetDailyQuote');
162
163 # Fill the quote table with the default needed and a spare
164 $dbh->do("DELETE FROM quotes WHERE id=3 OR id=25;");
165 my $sql = "INSERT INTO quotes (id,source,text,timestamp) VALUES
166 (25,'Richard Nixon','When the President does it, that means that it is not illegal.','0000-00-00 00:00:00'),
167 (3,'Abraham Lincoln','Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.','0000-00-00 00:00:00');";
168 $dbh->do($sql);
169
170                 my $expected_quote = {
171                     id          => 3,
172                     source      => 'Abraham Lincoln',
173                     text        => 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.',
174                     timestamp   => re('\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}'),   #'0000-00-00 00:00:00',
175                 };
176
177 # test quote retrieval based on id
178
179                 my $quote = GetDailyQuote('id'=>3);
180                 cmp_deeply ($quote, $expected_quote, "Got a quote based on id.") or
181                     diag('Be sure to run this test on a clean install of sample data.');
182
183 # test quote retrieval based on today's date
184
185                 my $query = 'UPDATE quotes SET timestamp = ? WHERE id = ?';
186                 my $sth = C4::Context->dbh->prepare($query);
187                 $sth->execute(DateTime::Format::MySQL->format_datetime( dt_from_string() ), $expected_quote->{'id'});
188
189                 DateTime::Format::MySQL->format_datetime( dt_from_string() ) =~ m/(\d{4}-\d{2}-\d{2})/;
190                 $expected_quote->{'timestamp'} = re("^$1");
191
192 #        $expected_quote->{'timestamp'} = DateTime::Format::MySQL->format_datetime( dt_from_string() );   # update the timestamp of expected quote data
193
194                 $quote = GetDailyQuote(); # this is the "default" mode of selection
195                 cmp_deeply ($quote, $expected_quote, "Got a quote based on today's date.") or
196                     diag('Be sure to run this test on a clean install of sample data.');
197
198 # test random quote retrieval
199
200                 $quote = GetDailyQuote('random'=>1);
201                 ok ($quote, "Got a random quote.");
202             }
203         };
204 }
205
206
207 #
208 # test that &slashifyDate returns correct (non-US) date
209 #
210 subtest 'Date and ISBN tests' => sub {
211     plan tests => 7;
212
213     my $date    = "01/01/2002";
214     my $newdate = &slashifyDate("2002-01-01");
215     my $isbn13  = "9780330356473";
216     my $isbn13D = "978-0-330-35647-3";
217     my $isbn10  = "033035647X";
218     my $isbn10D = "0-330-35647-X";
219     ok( $date eq $newdate, 'slashifyDate' );
220     my $undef = undef;
221     is( xml_escape($undef), '',
222         'xml_escape() returns empty string on undef input' );
223     my $str = q{'"&<>'};
224     is(
225         xml_escape($str),
226         '&apos;&quot;&amp;&lt;&gt;&apos;',
227         'xml_escape() works as expected'
228     );
229     is( $str, q{'"&<>'}, '... and does not change input in place' );
230     is( C4::Koha::_isbn_cleanup('0-590-35340-3'),
231         '0590353403', '_isbn_cleanup removes hyphens' );
232     is( C4::Koha::_isbn_cleanup('0590353403 (pbk.)'),
233         '0590353403', '_isbn_cleanup removes parenthetical' );
234     is( C4::Koha::_isbn_cleanup('978-0-321-49694-2'),
235         '0321496949', '_isbn_cleanup converts ISBN-13 to ISBN-10' );
236
237 };
238
239 subtest 'getFacets() tests' => sub {
240     plan tests => 2;
241
242     C4::Context->set_preference('singleBranchMode', 0);
243     my $facets = C4::Koha::getFacets();
244     is(
245         scalar( grep { defined $_->{idx} && $_->{idx} eq 'location' } @$facets ),
246         1,
247         'location facet present with singleBranchMode off (bug 10078)'
248     );
249     C4::Context->set_preference('singleBranchMode', 1);
250     $facets = C4::Koha::getFacets();
251     is(
252         scalar( grep { defined $_->{idx} && $_->{idx} eq 'location' } @$facets ),
253         1,
254         'location facet present with singleBranchMode on (bug 10078)'
255     );
256 };
257
258 subtest 'GetFrameworksLoop() tests' => sub {
259     plan tests => 6;
260
261     $dbh->do("DELETE FROM biblio_framework");
262
263     my $frameworksloop = GetFrameworksLoop();
264     is ( scalar(@$frameworksloop), 0, 'No frameworks' );
265
266     $dbh->do("INSERT INTO biblio_framework ( frameworkcode, frameworktext ) VALUES ( 'A', 'Third framework'  )");
267     $dbh->do("INSERT INTO biblio_framework ( frameworkcode, frameworktext ) VALUES ( 'B', 'Second framework' )");
268     $dbh->do("INSERT INTO biblio_framework ( frameworkcode, frameworktext ) VALUES ( 'C', 'First framework'  )");
269
270     $frameworksloop = GetFrameworksLoop();
271     is ( scalar(@$frameworksloop), 3, 'All frameworks' );
272     is ( scalar ( grep { defined $_->{'selected'} } @$frameworksloop ), 0, 'None selected' );
273
274     $frameworksloop = GetFrameworksLoop( 'B' );
275     is ( scalar ( grep { defined $_->{'selected'} } @$frameworksloop ), 1, 'One selected' );
276     my @descriptions = map { $_->{'description'} } @$frameworksloop;
277     is ( $descriptions[0], 'First framework', 'Ordered result' );
278     cmp_deeply(
279         $frameworksloop,
280         [
281             {
282                 'value' => 'C',
283                 'description' => 'First framework',
284                 'selected' => undef,
285             },
286             {
287                 'value' => 'B',
288                 'description' => 'Second framework',
289                 'selected' => 1,                # selected
290             },
291             {
292                 'value' => 'A',
293                 'description' => 'Third framework',
294                 'selected' => undef,
295             }
296         ],
297         'Full check, sorted by description with selected val (Bug 12675)'
298     );
299 };
300
301 subtest 'GetItemTypesByCategory GetItemTypesCategorized test' => sub{
302     plan tests => 7;
303
304     my $insertGroup = AddAuthorisedValue('ITEMTYPECAT', 'Qwertyware');
305     ok($insertGroup, "Create group Qwertyware");
306
307     my $query = "INSERT into itemtypes (itemtype, description, searchcategory, hideinopac) values (?,?,?,?)";
308     my $insertSth = C4::Context->dbh->prepare($query);
309     $insertSth->execute('BKghjklo1', 'One type of book', '', 0);
310     $insertSth->execute('BKghjklo2', 'Another type of book', 'Qwertyware', 0);
311     $insertSth->execute('BKghjklo3', 'Yet another type of book', 'Qwertyware', 0);
312
313     # Azertyware should not exist.
314     my @results = GetItemTypesByCategory('Azertyware');
315     is(scalar @results, 0, 'GetItemTypesByCategory: Invalid category returns nothing');
316
317     @results = GetItemTypesByCategory('Qwertyware');
318     my @expected = ( 'BKghjklo2', 'BKghjklo3' );
319     is_deeply(\@results,\@expected,'GetItemTypesByCategory: valid category returns itemtypes');
320
321     # add more data since GetItemTypesCategorized's search is more subtle
322     $insertGroup = AddAuthorisedValue('ITEMTYPECAT', 'Veryheavybook');
323     $insertSth->execute('BKghjklo4', 'Another hidden book', 'Veryheavybook', 1);
324
325     my $hrCat = GetItemTypesCategorized();
326     ok(exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: fully visible category exists');
327     ok($hrCat->{Veryheavybook} &&
328        $hrCat->{Veryheavybook}->{hideinopac}==1, 'GetItemTypesCategorized: non-visible category hidden' );
329
330     $insertSth->execute('BKghjklo5', 'An hidden book', 'Qwertyware', 1);
331     $hrCat = GetItemTypesCategorized();
332     ok(exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: partially visible category exists');
333
334     my @only = ( 'BKghjklo1', 'BKghjklo2', 'BKghjklo3', 'BKghjklo4', 'BKghjklo5', 'Qwertyware', 'Veryheavybook' );
335     @results = ();
336     foreach my $key (@only) {
337         push @results, $key if exists $hrCat->{$key};
338     }
339     @expected = ( 'BKghjklo1', 'Qwertyware', 'Veryheavybook' );
340     is_deeply(\@results,\@expected, 'GetItemTypesCategorized: grouped and ungrouped items returned as expected.');
341 };
342
343 subtest 'GetItemTypes test' => sub {
344     plan tests => 1;
345     $dbh->do(q|DELETE FROM itemtypes|);
346     $dbh->do(q|INSERT INTO itemtypes(itemtype, description) VALUES ('a', 'aa desc'), ('b', 'zz desc'), ('d', 'dd desc'), ('c', 'yy desc')|);
347     my $itemtypes = C4::Koha::GetItemTypes( style => 'array' );
348     $itemtypes = [ map { $_->{itemtype} } @$itemtypes ];
349     is_deeply( $itemtypes, [ 'a', 'd', 'c', 'b' ], 'GetItemTypes(array) should return itemtypes ordered by description');
350 };
351
352 $dbh->rollback();