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