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