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