Bug 19809: Re-allow to call Koha::Objects::find in list context
[koha.git] / t / db_dependent / Koha / Objects.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 20;
23 use Test::Exception;
24 use Test::Warn;
25
26 use Koha::Authority::Types;
27 use Koha::Cities;
28 use Koha::IssuingRules;
29 use Koha::Patron::Category;
30 use Koha::Patron::Categories;
31 use Koha::Patrons;
32 use Koha::Database;
33
34 use t::lib::TestBuilder;
35
36 use Try::Tiny;
37
38 my $schema = Koha::Database->new->schema;
39 $schema->storage->txn_begin;
40 my $builder = t::lib::TestBuilder->new;
41
42 is( ref(Koha::Authority::Types->find('')), 'Koha::Authority::Type', 'Koha::Objects->find should work if the primary key is an empty string' );
43
44 my @columns = Koha::Patrons->columns;
45 my $borrowernumber_exists = grep { /^borrowernumber$/ } @columns;
46 is( $borrowernumber_exists, 1, 'Koha::Objects->columns should return the table columns' );
47
48 subtest 'find' => sub {
49     plan tests => 6;
50     my $patron = $builder->build({source => 'Borrower'});
51     my $patron_object = Koha::Patrons->find( $patron->{borrowernumber} );
52     is( $patron_object->borrowernumber, $patron->{borrowernumber}, '->find should return the correct object' );
53
54     my @patrons = Koha::Patrons->find( $patron->{borrowernumber} );
55     is(scalar @patrons, 1, '->find in list context returns a value');
56     is($patrons[0]->borrowernumber, $patron->{borrowernumber}, '->find in list context returns the same value as in scalar context');
57
58     my $patrons = {
59         foo => Koha::Patrons->find('foo'),
60         bar => 'baz',
61     };
62     is ($patrons->{foo}, undef, '->find in list context returns undef when no record is found');
63
64     # Test sending undef to find; should not generate a warning
65     warning_is { $patron = Koha::Patrons->find( undef ); }
66         "", "Sending undef does not trigger a DBIx warning";
67     warning_is { $patron = Koha::Patrons->find( undef, undef ); }
68         "", "Sending two undefs does not trigger a DBIx warning too";
69 };
70
71 subtest 'update' => sub {
72     plan tests => 2;
73
74     $builder->build( { source => 'City', value => { city_country => 'UK' } } );
75     $builder->build( { source => 'City', value => { city_country => 'UK' } } );
76     $builder->build( { source => 'City', value => { city_country => 'UK' } } );
77     $builder->build( { source => 'City', value => { city_country => 'France' } } );
78     $builder->build( { source => 'City', value => { city_country => 'France' } } );
79     $builder->build( { source => 'City', value => { city_country => 'Germany' } } );
80     Koha::Cities->search( { city_country => 'UK' } )->update( { city_country => 'EU' } );
81     is( Koha::Cities->search( { city_country => 'EU' } )->count, 3, 'Koha::Objects->update should have updated the 3 rows' );
82     is( Koha::Cities->search( { city_country => 'UK' } )->count, 0, 'Koha::Objects->update should have updated the 3 rows' );
83 };
84
85 subtest 'reset' => sub {
86     plan tests => 3;
87
88     my $patrons = Koha::Patrons->search;
89     my $first_borrowernumber = $patrons->next->borrowernumber;
90     my $second_borrowernumber = $patrons->next->borrowernumber;
91     is( ref( $patrons->reset ), 'Koha::Patrons', 'Koha::Objects->reset should allow chaining' );
92     is( ref( $patrons->reset->next ), 'Koha::Patron', 'Koha::Objects->reset should allow chaining' );
93     is( $patrons->reset->next->borrowernumber, $first_borrowernumber, 'Koha::Objects->reset should work as expected');
94 };
95
96 subtest 'delete' => sub {
97     plan tests => 2;
98
99     my $patron_1 = $builder->build({source => 'Borrower'});
100     my $patron_2 = $builder->build({source => 'Borrower'});
101     is( Koha::Patrons->search({ -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}]}})->delete, 2, '');
102     is( Koha::Patrons->search({ -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}]}})->count, 0, '');
103 };
104
105 subtest 'new' => sub {
106     plan tests => 2;
107     my $a_cat_code = 'A_CAT_CODE';
108     my $patron_category = Koha::Patron::Category->new( { categorycode => $a_cat_code } )->store;
109     is( Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', 'Koha::Object->new should set the default value' );
110     Koha::Patron::Categories->find($a_cat_code)->delete;
111     $patron_category = Koha::Patron::Category->new( { categorycode => $a_cat_code, category_type => undef } )->store;
112     is( Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', 'Koha::Object->new should set the default value even if the argument exists but is not defined' );
113     Koha::Patron::Categories->find($a_cat_code)->delete;
114 };
115
116 subtest 'find' => sub {
117     plan tests => 5;
118
119     # check find on a single PK
120     my $patron = $builder->build({ source => 'Borrower' });
121     is( Koha::Patrons->find($patron->{borrowernumber})->surname,
122         $patron->{surname}, "Checking an arbitrary patron column after find"
123     );
124     # check find with unique column
125     my $obj = Koha::Patrons->find($patron->{cardnumber}, { key => 'cardnumber' });
126     is( $obj->borrowernumber, $patron->{borrowernumber},
127         'Find with unique column and key specified' );
128     # check find with an additional where clause in the attrs hash
129     # we do not expect to find something now
130     is( Koha::Patrons->find(
131         $patron->{borrowernumber},
132         { where => { surname => { '!=', $patron->{surname} }}},
133     ), undef, 'Additional where clause in find call' );
134
135     # check find with a composite FK
136     my $rule = $builder->build({ source => 'Issuingrule' });
137     my @pk = ( $rule->{branchcode}, $rule->{categorycode}, $rule->{itemtype} );
138     is( ref(Koha::IssuingRules->find(@pk)), "Koha::IssuingRule",
139         'Find returned a Koha object for composite primary key' );
140
141     is( Koha::Patrons->find(), undef, 'Find returns undef if no params passed' );
142 };
143
144 subtest 'search_related' => sub {
145     plan tests => 8;
146     my $builder   = t::lib::TestBuilder->new;
147     my $patron_1  = $builder->build( { source => 'Borrower' } );
148     my $patron_2  = $builder->build( { source => 'Borrower' } );
149     my $libraries = Koha::Patrons->search( { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } )->search_related('branchcode');
150     is( ref( $libraries ), 'Koha::Libraries', 'Koha::Objects->search_related should return an instanciated Koha::Objects-based object' );
151     is( $libraries->count,            2,                       'Koha::Objects->search_related should work as expected' );
152     is( $libraries->next->branchcode, $patron_1->{branchcode}, 'Koha::Objects->search_related should work as expected' );
153     is( $libraries->next->branchcode, $patron_2->{branchcode}, 'Koha::Objects->search_related should work as expected' );
154
155     my @libraries = Koha::Patrons->search( { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } )->search_related('branchcode');
156     is( ref( $libraries[0] ),      'Koha::Library',         'Koha::Objects->search_related should return a list of Koha::Object-based objects' );
157     is( scalar(@libraries),        2,                       'Koha::Objects->search_related should work as expected' );
158     is( $libraries[0]->branchcode, $patron_1->{branchcode}, 'Koha::Objects->search_related should work as expected' );
159     is( $libraries[1]->branchcode, $patron_2->{branchcode}, 'Koha::Objects->search_related should work as expected' );
160 };
161
162 subtest 'single' => sub {
163     plan tests => 2;
164     my $builder   = t::lib::TestBuilder->new;
165     my $patron_1  = $builder->build( { source => 'Borrower' } );
166     my $patron_2  = $builder->build( { source => 'Borrower' } );
167     my $patron = Koha::Patrons->search({}, { rows => 1 })->single;
168     is(ref($patron), 'Koha::Patron', 'Koha::Objects->single returns a single Koha::Patron object.');
169     warning_like { Koha::Patrons->search->single } qr/SQL that returns multiple rows/,
170     "Warning is presented if single is used for a result with multiple rows.";
171 };
172
173 subtest 'last' => sub {
174     plan tests => 3;
175     my $builder = t::lib::TestBuilder->new;
176     my $patron_1  = $builder->build( { source => 'Borrower' } );
177     my $patron_2  = $builder->build( { source => 'Borrower' } );
178     my $last_patron = Koha::Patrons->search->last;
179     is( $last_patron->borrowernumber, $patron_2->{borrowernumber}, '->last should return the last inserted patron' );
180     $last_patron = Koha::Patrons->search({ borrowernumber => $patron_1->{borrowernumber} })->last;
181     is( $last_patron->borrowernumber, $patron_1->{borrowernumber}, '->last should work even if there is only 1 result' );
182     $last_patron = Koha::Patrons->search({ surname => 'should_not_exist' })->last;
183     is( $last_patron, undef, '->last should return undef if search does not return any results' );
184 };
185
186 subtest 'get_column' => sub {
187     plan tests => 1;
188     my @cities = Koha::Cities->search;
189     my @city_names = map { $_->city_name } @cities;
190     is_deeply( [ Koha::Cities->search->get_column('city_name') ], \@city_names, 'Koha::Objects->get_column should be allowed' );
191 };
192
193 subtest 'Exceptions' => sub {
194     plan tests => 7;
195
196     my $patron_borrowernumber = $builder->build({ source => 'Borrower' })->{ borrowernumber };
197     my $patron = Koha::Patrons->find( $patron_borrowernumber );
198
199     # Koha::Object
200     try {
201         $patron->blah('blah');
202     } catch {
203         ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'),
204             'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' );
205         is( $_->message, 'The method Koha::Patron->blah is not covered by tests!', 'The message raised should contain the package and the method' );
206     };
207
208     try {
209         $patron->set({ blah => 'blah' });
210     } catch {
211         ok( $_->isa('Koha::Exceptions::Object::PropertyNotFound'),
212             'Setting a non-existent property should raise a Koha::Exceptions::Object::PropertyNotFound exception' );
213     };
214
215     # Koha::Objects
216     try {
217         Koha::Patrons->search->not_covered_yet;
218     } catch {
219         ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'),
220             'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' );
221         is( $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', 'The message raised should contain the package and the method' );
222     };
223
224     try {
225         Koha::Patrons->not_covered_yet;
226     } catch {
227         ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'),
228             'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' );
229         is( $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', 'The message raised should contain the package and the method' );
230     };
231 };
232
233 $schema->storage->txn_rollback;
234
235 subtest '->is_paged and ->pager tests' => sub {
236
237     plan tests => 5;
238
239     $schema->storage->txn_begin;
240
241     # Delete existing patrons
242     Koha::Checkouts->delete;
243     Koha::Patrons->delete;
244     # Create 10 patrons
245     foreach (1..10) {
246         $builder->build_object({ class => 'Koha::Patrons' });
247     }
248
249     # Non-paginated search
250     my $patrons = Koha::Patrons->search();
251     is( $patrons->count, 10, 'Search returns all patrons' );
252     ok( !$patrons->is_paged, 'Search is not paged' );
253
254     # Paginated search
255     $patrons = Koha::Patrons->search( undef, { 'page' => 1, 'rows' => 3 } );
256     is( $patrons->count, 3, 'Search returns only one page, 3 patrons' );
257     ok( $patrons->is_paged, 'Search is paged' );
258     my $pager = $patrons->pager;
259     is( ref($patrons->pager), 'DBIx::Class::ResultSet::Pager',
260        'Koha::Objects->pager returns a valid DBIx::Class object' );
261
262     $schema->storage->txn_rollback;
263 };
264
265 subtest '->search() tests' => sub {
266
267     plan tests => 12;
268
269     $schema->storage->txn_begin;
270
271     my $count = Koha::Patrons->search->count;
272
273     # Create 10 patrons
274     foreach (1..10) {
275         $builder->build_object({ class => 'Koha::Patrons' });
276     }
277
278     my $patrons = Koha::Patrons->search();
279     is( ref($patrons), 'Koha::Patrons', 'search in scalar context returns the Koha::Object-based type' );
280     my @patrons = Koha::Patrons->search();
281     is( scalar @patrons, $count + 10, 'search in list context returns a list of objects' );
282     my $i = 0;
283     foreach (1..10) {
284         is( ref($patrons[$i]), 'Koha::Patron', 'Objects in the list have the singular type' );
285         $i++;
286     }
287
288     $schema->storage->txn_rollback;
289 };
290
291 subtest "to_api() tests" => sub {
292
293     plan tests => 18;
294
295     $schema->storage->txn_begin;
296
297     my $city_1 = $builder->build_object( { class => 'Koha::Cities' } );
298     my $city_2 = $builder->build_object( { class => 'Koha::Cities' } );
299
300     my $cities = Koha::Cities->search(
301         {
302             cityid => [ $city_1->cityid, $city_2->cityid ]
303         },
304         { -orderby => { -desc => 'cityid' } }
305     );
306
307     is( $cities->count, 2, 'Count is correct' );
308     my $cities_api = $cities->to_api;
309     is( ref( $cities_api ), 'ARRAY', 'to_api returns an array' );
310     is_deeply( $cities_api->[0], $city_1->to_api, 'to_api returns the individual objects with ->to_api' );
311     is_deeply( $cities_api->[1], $city_2->to_api, 'to_api returns the individual objects with ->to_api' );
312
313     my $biblio_1 = $builder->build_sample_biblio();
314     my $item_1   = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber });
315     my $hold_1   = $builder->build_object(
316         {
317             class => 'Koha::Holds',
318             value => { itemnumber => $item_1->itemnumber }
319         }
320     );
321
322     my $biblio_2 = $builder->build_sample_biblio();
323     my $item_2   = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber });
324     my $hold_2   = $builder->build_object(
325         {
326             class => 'Koha::Holds',
327             value => { itemnumber => $item_2->itemnumber }
328         }
329     );
330
331     my $embed = { 'items' => {} };
332
333     my $i = 0;
334     my @items = ( $item_1, $item_2 );
335     my @holds = ( $hold_1, $hold_2 );
336
337     my $biblios_api = Koha::Biblios->search(
338         {
339             biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ]
340         }
341     )->to_api( { embed => $embed } );
342
343     foreach my $biblio_api ( @{ $biblios_api } ) {
344         ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
345         is($biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item matches');
346         ok(!exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet');
347
348         $i++;
349     }
350
351     # One more level
352     $embed = {
353         'items' => {
354             children => { 'holds' => {} }
355         }
356     };
357
358     $i = 0;
359
360     $biblios_api = Koha::Biblios->search(
361         {
362             biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ]
363         }
364     )->to_api( { embed => $embed } );
365
366     foreach my $biblio_api ( @{ $biblios_api } ) {
367
368         ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
369         is($biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item still matches');
370         ok(exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded');
371         is($biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $holds[$i]->reserve_id, 'Hold matches');
372
373         $i++;
374     }
375
376     $schema->storage->txn_rollback;
377 };
378
379 subtest "TO_JSON() tests" => sub {
380
381     plan tests => 4;
382
383     $schema->storage->txn_begin;
384
385     my $city_1 = $builder->build_object( { class => 'Koha::Cities' } );
386     my $city_2 = $builder->build_object( { class => 'Koha::Cities' } );
387
388     my $cities = Koha::Cities->search(
389         {
390             cityid => [ $city_1->cityid, $city_2->cityid ]
391         },
392         { -orderby => { -desc => 'cityid' } }
393     );
394
395     is( $cities->count, 2, 'Count is correct' );
396     my $cities_json = $cities->TO_JSON;
397     is( ref($cities_json), 'ARRAY', 'to_api returns an array' );
398     is_deeply( $cities_json->[0], $city_1->TO_JSON, 'TO_JSON returns the individual objects with ->TO_JSON' );
399     is_deeply( $cities_json->[1], $city_2->TO_JSON,'TO_JSON returns the individual objects with ->TO_JSON' );
400
401     $schema->storage->txn_rollback;
402 };
403
404 # Koha::Object[s] must behave the same as DBIx::Class
405 subtest 'Return same values as DBIx::Class' => sub {
406     plan tests => 1;
407
408     subtest 'Delete' => sub {
409         plan tests => 2;
410
411         $schema->storage->txn_begin;
412
413         subtest 'Simple Koha::Objects - Koha::Cities' => sub {
414             plan tests => 2;
415
416             subtest 'Koha::Object->delete' => sub {
417
418                 plan tests => 5;
419
420                 my ( $r_us, $e_us, $r_them, $e_them );
421
422                 # CASE 1 - Delete an existing object
423                 my $c = Koha::City->new( { city_name => 'city4test' } )->store;
424                 try { $r_us = $c->delete; } catch { $e_us = $_ };
425                 $c = $schema->resultset('City')->new( { city_name => 'city4test_2' } )->update_or_insert;
426                 try { $r_them = $c->delete; } catch { $e_them = $_ };
427                 ok( ref($r_us) && ref($r_them),
428                     'Successful delete should return the object ' );
429                 ok( !defined $e_us && !defined $e_them,
430                     'Successful delete should not raise an exception' );
431                 is( ref($r_us), 'Koha::City', 'Successful delete should return our Koha::Obect based object' );
432
433                 # CASE 2 - Delete an object that is not in storage
434                 try { $r_us   = $r_us->delete;   } catch { $e_us   = $_ };
435                 try { $r_them = $r_them->delete; } catch { $e_them = $_ };
436                 ok(
437                     defined $e_us && defined $e_them,
438                     'Delete an object that is not in storage should raise an exception'
439                 );
440                 is( ref($e_us), 'DBIx::Class::Exception' )
441                   ; # FIXME This needs adjustement, we want to throw a Koha::Exception
442
443             };
444
445             subtest 'Koha::Objects->delete' => sub {
446
447                 plan tests => 4;
448
449                 my ( $r_us, $e_us, $r_them, $e_them );
450
451                 # CASE 1 - Delete existing objects
452                 my $city_1 = $builder->build_object({ class => 'Koha::Cities' });
453                 my $city_2 = $builder->build_object({ class => 'Koha::Cities' });
454                 my $city_3 = $builder->build_object({ class => 'Koha::Cities' });
455                 my $cities = Koha::Cities->search(
456                     {
457                         cityid => {
458                             -in => [
459                                 $city_1->cityid,
460                                 $city_2->cityid,
461                                 $city_3->cityid,
462                             ]
463                         }
464                     }
465                 );
466
467                 try { $r_us = $cities->delete; } catch { $e_us = $_ };
468
469                 $city_1 = $builder->build_object({ class => 'Koha::Cities' });
470                 $city_2 = $builder->build_object({ class => 'Koha::Cities' });
471                 $city_3 = $builder->build_object({ class => 'Koha::Cities' });
472                 $cities = $schema->resultset('City')->search(
473                     {
474                         cityid => {
475                             -in => [
476                                 $city_1->cityid,
477                                 $city_2->cityid,
478                                 $city_3->cityid,
479                             ]
480                         }
481                     }
482                 );
483
484                 try { $r_them = $cities->delete; } catch { $e_them = $_ };
485
486                 ok( $r_us == 3 && $r_them == 3 );
487                 ok (!defined($e_us) && !defined($e_them));
488
489                 # CASE 2 - One of the object is not in storage
490                 $city_1 = $builder->build_object({ class => 'Koha::Cities' });
491                 $city_2 = $builder->build_object({ class => 'Koha::Cities' });
492                 $city_3 = $builder->build_object({ class => 'Koha::Cities' });
493                 $cities = Koha::Cities->search(
494                     {
495                         cityid => {
496                             -in => [
497                                 $city_1->cityid,
498                                 $city_2->cityid,
499                                 $city_3->cityid,
500                             ]
501                         }
502                     }
503                 );
504
505                 $city_2->delete; # We delete one of the object
506                 try { $r_us = $cities->delete; } catch { $e_us = $_ };
507
508                 $city_1 = $builder->build_object({ class => 'Koha::Cities' });
509                 $city_2 = $builder->build_object({ class => 'Koha::Cities' });
510                 $city_3 = $builder->build_object({ class => 'Koha::Cities' });
511                 $cities = $schema->resultset('City')->search(
512                     {
513                         cityid => {
514                             -in => [
515                                 $city_1->cityid,
516                                 $city_2->cityid,
517                                 $city_3->cityid,
518                             ]
519                         }
520                     }
521                 );
522
523                 $city_2->delete; # We delete one of the object
524                 try { $r_them = $cities->delete; } catch { $e_them = $_ };
525
526                 ok( $r_us == 2 && $r_them == 2 );
527                 ok (!defined($e_us) && !defined($e_them));
528             };
529         };
530
531         subtest 'Overwritten Koha::Objects->delete - Koha::Patrons' => sub {
532
533             plan tests => 2;
534
535             subtest 'Koha::Object->delete' => sub {
536
537                 plan tests => 7;
538
539                 my ( $r_us, $e_us, $r_them, $e_them );
540
541                 # CASE 1 - Delete an existing patron
542                 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
543                 my $patron_data = $patron->unblessed;
544                 $patron->delete;
545
546                 $patron = Koha::Patron->new( $patron_data )->store;
547                 try {$r_us = $patron->delete;} catch { $e_us = $_ };
548                 $patron = $schema->resultset('Borrower')->new( $patron_data )->update_or_insert;
549                 try {$r_them = $patron->delete;} catch { $e_them = $_ };
550                 ok( ref($r_us) && ref($r_them),
551                     'Successful delete should return the patron object' );
552                 ok( !defined $e_us && !defined $e_them,
553                     'Successful delete should not raise an exception' );
554                 is( ref($r_us), 'Koha::Patron',
555                     'Successful delete should return our Koha::Obect based object' );
556
557                 # CASE 2 - Delete a patron that is not in storage
558                 try { $r_us   = $r_us->delete;   } catch { $e_us   = $_ };
559                 try { $r_them = $r_them->delete; } catch { $e_them = $_ };
560                 ok(
561                     defined $e_us && defined $e_them,
562                     'Delete a patron that is not in storage should raise an exception'
563                 );
564                 is( ref($e_us), 'DBIx::Class::Exception' )
565                   ; # FIXME This needs adjustement, we want to throw a Koha::Exception
566
567                 # CASE 3 - Delete a patron that cannot be deleted (as a checkout)
568                 $patron = Koha::Patron->new($patron_data)->store;
569                 $builder->build_object(
570                     {
571                         class => 'Koha::Checkouts',
572                         value => { borrowernumber => $patron->borrowernumber }
573                     }
574                 );
575                 try { $r_us = $r_us->delete; } catch { $e_us = $_ };
576                 $patron = $schema->resultset('Borrower')->find( $patron->borrowernumber );
577                 try { $r_them = $r_them->delete; } catch { $e_them = $_ };
578                 ok(
579                     defined $e_us && defined $e_them,
580                     'Delete a patron that cannot be deleted should raise an exception'
581                 );
582                 is( ref($e_us), 'DBIx::Class::Exception' )
583                   ; # FIXME This needs adjustement, we want to throw a Koha::Exception
584             };
585
586             subtest 'Koha::Objects->delete' => sub {
587
588                 plan tests => 9;
589
590                 my ( $r_us, $e_us, $r_them, $e_them );
591
592                 # CASE 1 - Delete existing objects
593                 my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
594                 my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
595                 my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
596                 my $patrons = Koha::Patrons->search(
597                     {
598                         borrowernumber => {
599                             -in => [
600                                 $patron_1->borrowernumber,
601                                 $patron_2->borrowernumber,
602                                 $patron_3->borrowernumber
603                             ]
604                         }
605                     }
606                 );
607
608                 try { $r_us = $patrons->delete; } catch { $e_us = $_ };
609
610                 $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
611                 $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
612                 $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
613                 $patrons = $schema->resultset('Borrower')->search(
614                     {
615                         borrowernumber => {
616                             -in => [
617                                 $patron_1->borrowernumber,
618                                 $patron_2->borrowernumber,
619                                 $patron_3->borrowernumber
620                             ]
621                         }
622                     }
623                 );
624
625                 try { $r_them = $patrons->delete; } catch { $e_them = $_ };
626
627                 ok( $r_us == 3 && $r_them == 3, '->delete should return the number of deleted patrons' );
628                 ok (!defined($e_us) && !defined($e_them), '->delete should not raise exception if everything went well');
629
630                 # CASE 2 - One of the patrons is not in storage
631                 undef $_ for $r_us, $e_us, $r_them, $e_them;
632                 $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
633                 $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
634                 $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
635                 $patrons = Koha::Patrons->search(
636                     {
637                         borrowernumber => {
638                             -in => [
639                                 $patron_1->borrowernumber,
640                                 $patron_2->borrowernumber,
641                                 $patron_3->borrowernumber
642                             ]
643                         }
644                     }
645                 );
646
647                 $patron_2->delete; # We delete one of the patron
648                 try { $r_us = $patrons->delete; } catch { $e_us = $_ };
649
650                 $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
651                 $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
652                 $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
653                 $patrons = $schema->resultset('Borrower')->search(
654                     {
655                         borrowernumber => {
656                             -in => [
657                                 $patron_1->borrowernumber,
658                                 $patron_2->borrowernumber,
659                                 $patron_3->borrowernumber
660                             ]
661                         }
662                     }
663                 );
664
665                 $patron_2->delete; # We delete one of the patron
666                 try { $r_them = $patrons->delete; } catch { $e_them = $_ };
667
668                 ok( $r_us == 2 && $r_them == 2, 'Delete patrons with one that was not in storage should delete the patrons' );
669                 ok (!defined($e_us) && !defined($e_them), 'no exception should be raised if at least one patron was not in storage');
670
671                 # CASE 3 - Delete a set of patrons with one that that cannot be deleted (as a checkout)
672                 undef $_ for $r_us, $e_us, $r_them, $e_them;
673                 $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
674                 $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
675                 $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
676                 $patrons = Koha::Patrons->search(
677                     {
678                         borrowernumber => {
679                             -in => [
680                                 $patron_1->borrowernumber,
681                                 $patron_2->borrowernumber,
682                                 $patron_3->borrowernumber
683                             ]
684                         }
685                     }
686                 );
687
688                 # Adding a checkout to patron_2
689                 $builder->build_object(
690                     {
691                         class => 'Koha::Checkouts',
692                         value => { borrowernumber => $patron_2->borrowernumber }
693                     }
694                 );
695
696                 warning_like {
697                     try { $r_us = $patrons->delete; } catch { $e_us = $_ };
698                 }
699                 qr{DBD::mysql::st execute failed: Cannot delete or update a parent row: a foreign key constraint fails},
700                   "Foreign key constraint DBI error should be logged";
701                 my $not_deleted_us = $patron_1->in_storage + $patron_2->in_storage + $patron_3->in_storage;
702
703                 $patron_1 = $builder->build_object({ class => 'Koha::Patrons' });
704                 $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
705                 $patron_3 = $builder->build_object({ class => 'Koha::Patrons' });
706                 $patrons = $schema->resultset('Borrower')->search(
707                     {
708                         borrowernumber => {
709                             -in => [
710                                 $patron_1->borrowernumber,
711                                 $patron_2->borrowernumber,
712                                 $patron_3->borrowernumber
713                             ]
714                         }
715                     }
716                 );
717
718                 # Adding a checkout to patron_2
719                 $builder->build_object(
720                     {
721                         class => 'Koha::Checkouts',
722                         value => { borrowernumber => $patron_2->borrowernumber }
723                     }
724                 );
725
726                 warning_like {
727                     try { $r_them = $patrons->delete; } catch { $e_them = $_ };
728                 }
729                 qr{DBD::mysql::st execute failed: Cannot delete or update a parent row: a foreign key constraint fails},
730                   "Foreign key constraint DBI error should be logged";
731
732                 my $not_deleted_them = $patron_1->in_storage + $patron_2->in_storage + $patron_3->in_storage;
733                 ok(
734                     defined $e_us && defined $e_them,
735                     'Delete patrons with one that cannot be deleted should raise an exception'
736                 );
737                 is( ref($e_us), 'DBIx::Class::Exception' )
738                   ; # FIXME This needs adjustement, we want to throw a Koha::Exception
739
740                 ok($not_deleted_us == 3 && $not_deleted_them == 3, 'If one patron cannot be deleted, none should have been deleted');
741             };
742         };
743
744         $schema->storage->txn_rollback;
745
746     };
747 };
748
749 subtest "attributes_from_api() tests" => sub {
750
751     plan tests => 1;
752
753     $schema->storage->txn_begin;
754
755     my $cities_rs = Koha::Cities->new;
756     my $city      = Koha::City->new;
757
758     my $api_attributes = {
759         name        => 'Cordoba',
760         postal_code => 5000
761     };
762
763     is_deeply(
764         $cities_rs->attributes_from_api($api_attributes),
765         $city->attributes_from_api($api_attributes)
766     );
767
768     $schema->storage->txn_rollback;
769 };
770
771 subtest "from_api_mapping() tests" => sub {
772
773     plan tests => 1;
774
775     $schema->storage->txn_begin;
776
777     my $cities_rs = Koha::Cities->new;
778     my $city      = Koha::City->new;
779
780     is_deeply(
781         $cities_rs->from_api_mapping,
782         $city->from_api_mapping
783     );
784
785     $schema->storage->txn_rollback;
786 };