Bug 26635: Refined data structure and methods
[koha.git] / t / db_dependent / Koha / Object.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 21;
21 use Test::Exception;
22 use Test::Warn;
23 use DateTime;
24
25 use C4::Context;
26 use C4::Circulation qw( AddIssue );
27 use C4::Biblio qw( AddBiblio );
28
29 use Koha::Database;
30
31 use Koha::Acquisition::Orders;
32 use Koha::ApiKeys;
33 use Koha::AuthorisedValueCategories;
34 use Koha::AuthorisedValues;
35 use Koha::DateUtils qw( dt_from_string );
36 use Koha::Libraries;
37 use Koha::Patrons;
38 use Koha::Library::Groups;
39
40 use JSON;
41 use Scalar::Util qw( isvstring );
42 use Try::Tiny;
43
44 use t::lib::TestBuilder;
45 use t::lib::Mocks;
46
47 BEGIN {
48     use_ok('Koha::Object');
49     use_ok('Koha::Patron');
50 }
51
52 my $schema  = Koha::Database->new->schema;
53 my $builder = t::lib::TestBuilder->new();
54
55 subtest 'is_changed / make_column_dirty' => sub {
56     plan tests => 11;
57
58     $schema->storage->txn_begin;
59
60     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
61     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
62
63     my $object = Koha::Patron->new();
64     $object->categorycode( $categorycode );
65     $object->branchcode( $branchcode );
66     $object->surname("Test Surname");
67     $object->store->discard_changes;
68     is( $object->is_changed(), 0, "Object is unchanged" );
69     $object->surname("Test Surname");
70     is( $object->is_changed(), 0, "Object is still unchanged" );
71     $object->surname("Test Surname 2");
72     is( $object->is_changed(), 1, "Object is changed" );
73
74     $object->store();
75     is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
76
77     $object->set({ firstname => 'Test Firstname' });
78     is( $object->is_changed(), 1, "Object is changed after Set" );
79     $object->store();
80     is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
81
82     # Test make_column_dirty
83     is( $object->make_column_dirty('firstname'), '', 'make_column_dirty returns empty string on success' );
84     is( $object->make_column_dirty('firstname'), 1, 'make_column_dirty returns 1 if already dirty' );
85     is( $object->is_changed, 1, "Object is changed after make dirty" );
86     $object->store;
87     is( $object->is_changed, 0, "Store clears dirty mark" );
88     $object->make_column_dirty('firstname');
89     $object->discard_changes;
90     is( $object->is_changed, 0, "Discard clears dirty mark too" );
91
92     $schema->storage->txn_rollback;
93 };
94
95 subtest 'in_storage' => sub {
96     plan tests => 6;
97
98     $schema->storage->txn_begin;
99
100     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
101     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
102
103     my $object = Koha::Patron->new();
104     is( $object->in_storage, 0, "Object is not in storage" );
105     $object->categorycode( $categorycode );
106     $object->branchcode( $branchcode );
107     $object->surname("Test Surname");
108     $object->store();
109     is( $object->in_storage, 1, "Object is now stored" );
110     $object->surname("another surname");
111     is( $object->in_storage, 1 );
112
113     my $borrowernumber = $object->borrowernumber;
114     my $patron = $schema->resultset('Borrower')->find( $borrowernumber );
115     is( $patron->surname(), "Test Surname", "Object found in database" );
116
117     $object->delete();
118     $patron = $schema->resultset('Borrower')->find( $borrowernumber );
119     ok( ! $patron, "Object no longer found in database" );
120     is( $object->in_storage, 0, "Object is not in storage" );
121
122     $schema->storage->txn_rollback;
123 };
124
125 subtest 'id' => sub {
126     plan tests => 1;
127
128     $schema->storage->txn_begin;
129
130     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
131     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
132
133     my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
134     is( $patron->id, $patron->borrowernumber );
135
136     $schema->storage->txn_rollback;
137 };
138
139 subtest 'get_column' => sub {
140     plan tests => 1;
141
142     $schema->storage->txn_begin;
143
144     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
145     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
146
147     my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
148     is( $patron->get_column('borrowernumber'), $patron->borrowernumber, 'get_column should retrieve the correct value' );
149
150     $schema->storage->txn_rollback;
151 };
152
153 subtest 'discard_changes' => sub {
154     plan tests => 1;
155
156     $schema->storage->txn_begin;
157
158     my $patron = $builder->build( { source => 'Borrower' } );
159     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
160     $patron->dateexpiry(dt_from_string);
161     $patron->discard_changes;
162     is(
163         dt_from_string( $patron->dateexpiry ),
164         dt_from_string->truncate( to => 'day' ),
165         'discard_changes should refresh the object'
166     );
167
168     $schema->storage->txn_rollback;
169 };
170
171 subtest 'TO_JSON tests' => sub {
172
173     plan tests => 9;
174
175     $schema->storage->txn_begin;
176
177     my $dt = dt_from_string();
178     my $borrowernumber = $builder->build(
179         { source => 'Borrower',
180           value => { lost => 1,
181                      sms_provider_id => undef,
182                      gonenoaddress => 0,
183                      updated_on => $dt,
184                      lastseen   => $dt, } })->{borrowernumber};
185
186     my $patron = Koha::Patrons->find($borrowernumber);
187     my $lost = $patron->TO_JSON()->{lost};
188     my $gonenoaddress = $patron->TO_JSON->{gonenoaddress};
189     my $updated_on = $patron->TO_JSON->{updated_on};
190     my $lastseen = $patron->TO_JSON->{lastseen};
191
192     ok( $lost->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
193     is( $lost, 1, 'Boolean attribute value is correct (true)' );
194
195     ok( $gonenoaddress->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
196     is( $gonenoaddress, 0, 'Boolean attribute value is correct (false)' );
197
198     is( $patron->TO_JSON->{sms_provider_id}, undef, 'Undef values should not be casted to 0' );
199
200     ok( !isvstring($patron->borrowernumber), 'Integer values are not coded as strings' );
201
202     my $rfc3999_regex = qr/
203             (?<year>\d{4})
204             -
205             (?<month>\d{2})
206             -
207             (?<day>\d{2})
208             ([Tt\s])
209             (?<hour>\d{2})
210             :
211             (?<minute>\d{2})
212             :
213             (?<second>\d{2})
214             (([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))
215         /xms;
216     like( $updated_on, $rfc3999_regex, "Date-time $updated_on formatted correctly");
217     like( $lastseen, $rfc3999_regex, "Date-time $updated_on formatted correctly");
218
219     # Test JSON doesn't receive strings
220     my $order = $builder->build_object({ class => 'Koha::Acquisition::Orders' });
221     $order = Koha::Acquisition::Orders->find( $order->ordernumber );
222     is_deeply( $order->TO_JSON, decode_json( encode_json( $order->TO_JSON ) ), 'Orders are similar' );
223
224     $schema->storage->txn_rollback;
225 };
226
227 subtest "to_api() tests" => sub {
228
229     plan tests => 30;
230
231     $schema->storage->txn_begin;
232
233     my $city = $builder->build_object({ class => 'Koha::Cities' });
234
235     # THE mapping
236     # cityid       => 'city_id',
237     # city_country => 'country',
238     # city_name    => 'name',
239     # city_state   => 'state',
240     # city_zipcode => 'postal_code'
241
242     my $api_city = $city->to_api;
243
244     is( $api_city->{city_id},     $city->cityid,       'Attribute translated correctly' );
245     is( $api_city->{country},     $city->city_country, 'Attribute translated correctly' );
246     is( $api_city->{name},        $city->city_name,    'Attribute translated correctly' );
247     is( $api_city->{state},       $city->city_state,   'Attribute translated correctly' );
248     is( $api_city->{postal_code}, $city->city_zipcode, 'Attribute translated correctly' );
249
250     # Lets emulate an undef
251     my $city_class = Test::MockModule->new('Koha::City');
252     $city_class->mock( 'to_api_mapping',
253         sub {
254             return {
255                 cityid       => 'city_id',
256                 city_country => 'country',
257                 city_name    => 'name',
258                 city_state   => 'state',
259                 city_zipcode => undef
260             };
261         }
262     );
263
264     $api_city = $city->to_api;
265
266     is( $api_city->{city_id},     $city->cityid,       'Attribute translated correctly' );
267     is( $api_city->{country},     $city->city_country, 'Attribute translated correctly' );
268     is( $api_city->{name},        $city->city_name,    'Attribute translated correctly' );
269     is( $api_city->{state},       $city->city_state,   'Attribute translated correctly' );
270     ok( !exists $api_city->{postal_code}, 'Attribute removed' );
271
272     # Pick a class that won't have a mapping for the API
273     my $illrequest = $builder->build_object({ class => 'Koha::Illrequests' });
274     is_deeply( $illrequest->to_api, $illrequest->TO_JSON, 'If no overloaded to_api_mapping method, return TO_JSON' );
275
276     my $biblio = $builder->build_sample_biblio();
277     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
278     my $hold = $builder->build_object({ class => 'Koha::Holds', value => { itemnumber => $item->itemnumber } });
279
280     my $embeds = { 'items' => {} };
281
282     my $biblio_api = $biblio->to_api({ embed => $embeds });
283
284     ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
285     is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item matches');
286     ok(!exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet');
287
288     $embeds = (
289         {
290             'items' => {
291                 'children' => {
292                     'holds' => {}
293                 }
294             },
295             'biblioitem' => {}
296         }
297     );
298     $biblio_api = $biblio->to_api({ embed => $embeds });
299
300     ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
301     is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item still matches');
302     ok(exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded');
303     is($biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $hold->reserve_id, 'Hold matches');
304     is_deeply($biblio_api->{biblioitem}, $biblio->biblioitem->to_api, 'More than one root');
305
306     my $hold_api = $hold->to_api(
307         {
308             embed => { 'item' => {} }
309         }
310     );
311
312     is( ref($hold_api->{item}), 'HASH', 'Single nested object works correctly' );
313     is( $hold_api->{item}->{item_id}, $item->itemnumber, 'Object embedded correctly' );
314
315     # biblio with no items
316     my $new_biblio = $builder->build_sample_biblio;
317     my $new_biblio_api = $new_biblio->to_api({ embed => $embeds });
318
319     is_deeply( $new_biblio_api->{items}, [], 'Empty list if no items' );
320
321     my $biblio_class = Test::MockModule->new('Koha::Biblio');
322     $biblio_class->mock( 'undef_result', sub { return; } );
323
324     $new_biblio_api = $new_biblio->to_api({ embed => ( { 'undef_result' => {} } ) });
325     ok( exists $new_biblio_api->{undef_result}, 'If a method returns undef, then the attribute is defined' );
326     is( $new_biblio_api->{undef_result}, undef, 'If a method returns undef, then the attribute is undef' );
327
328     $biblio_class->mock( 'items',
329         sub { return [ bless { itemnumber => 1 }, 'Somethings' ]; } );
330
331     throws_ok {
332         $new_biblio_api = $new_biblio->to_api(
333             { embed => { 'items' => { children => { asd => {} } } } } );
334     }
335     'Koha::Exception',
336 "An exception is thrown if a blessed object to embed doesn't implement to_api";
337
338     is(
339         $@->message,
340         "Asked to embed items but its return value doesn't implement to_api",
341         "Exception message correct"
342     );
343
344
345     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
346     $builder->build_object(
347         {
348             class => 'Koha::Holds',
349             value => {
350                 biblionumber   => $biblio->biblionumber,
351                 borrowernumber => $patron->borrowernumber
352             }
353         }
354     );
355     $builder->build_object(
356         {
357             class => 'Koha::Holds',
358             value => {
359                 biblionumber   => $biblio->biblionumber,
360                 borrowernumber => $patron->borrowernumber
361             }
362         }
363     );
364
365     my $patron_api = $patron->to_api(
366         {
367             embed => { holds_count => { is_count => 1 } }
368         }
369     );
370     is( $patron_api->{holds_count}, $patron->holds->count, 'Count embeds are supported and work as expected' );
371
372     throws_ok
373         {
374             $patron->to_api({ embed => { holds_count => {} } });
375         }
376         'Koha::Exceptions::Object::MethodNotCoveredByTests',
377         'Unknown method exception thrown if is_count not specified';
378
379     subtest 'unprivileged request tests' => sub {
380
381         my @all_attrs = Koha::Libraries->columns();
382         my $public_attrs = { map { $_ => 1 } @{ Koha::Library->public_read_list() } };
383         my $mapping = Koha::Library->to_api_mapping;
384
385         plan tests => scalar @all_attrs * 2;
386
387         # Create a sample library
388         my $library = $builder->build_object( { class => 'Koha::Libraries' } );
389
390         my $unprivileged_representation = $library->to_api({ public => 1 });
391         my $privileged_representation   = $library->to_api;
392
393         foreach my $attr (@all_attrs) {
394             my $mapped = exists $mapping->{$attr} ? $mapping->{$attr} : $attr;
395             if ( defined($mapped) ) {
396                 ok(
397                     exists $privileged_representation->{$mapped},
398                     "Attribute '$attr' is present when privileged"
399                 );
400                 if ( exists $public_attrs->{$attr} ) {
401                     ok(
402                         exists $unprivileged_representation->{$mapped},
403                         "Attribute '$attr' is present when public"
404                     );
405                 }
406                 else {
407                     ok(
408                         !exists $unprivileged_representation->{$mapped},
409                         "Attribute '$attr' is not present when public"
410                     );
411                 }
412             }
413             else {
414                 ok(
415                     !exists $privileged_representation->{$attr},
416                     "Unmapped attribute '$attr' is not present when privileged"
417                 );
418                 ok(
419                     !exists $unprivileged_representation->{$attr},
420                     "Unmapped attribute '$attr' is not present when public"
421                 );
422             }
423         }
424     };
425
426     subtest 'Authorised values expansion' => sub {
427
428         plan tests => 4;
429
430         $schema->storage->txn_begin;
431
432         # new category
433         my $category = $builder->build_object({ class => 'Koha::AuthorisedValueCategories' });
434         # add two countries
435         my $argentina = $builder->build_object(
436             {   class => 'Koha::AuthorisedValues',
437                 value => {
438                     category => $category->category_name,
439                     lib      => 'AR (Argentina)',
440                     lib_opac => 'Argentina',
441                 }
442             }
443         );
444         my $france = $builder->build_object(
445             {   class => 'Koha::AuthorisedValues',
446                 value => {
447                     category => $category->category_name,
448                     lib      => 'FR (France)',
449                     lib_opac => 'France',
450                 }
451             }
452         );
453
454         my $city_mock = Test::MockModule->new('Koha::City');
455         $city_mock->mock(
456             'api_av_mapping',
457             sub {
458                 my ( $self, $params ) = @_;
459
460                 my $av = Koha::AuthorisedValues->find(
461                     {
462                         authorised_value => $self->city_country,
463                         category         => $category->category_name,
464                     }
465                 );
466
467                 return {
468                     city_country => {
469                         category => $av->category,
470                         str      => ( $params->{public} ) ? $av->lib_opac : $av->lib,
471                         type     => 'av',
472                     }
473                 };
474             }
475         );
476         $city_mock->mock( 'public_read_list', sub { return [ 'city_id', 'city_country', 'city_name', 'city_state' ] } );
477
478         my $cordoba = $builder->build_object(
479             {   class => 'Koha::Cities',
480                 value => { city_country => $argentina->authorised_value, city_name => 'Cordoba' }
481             }
482         );
483         my $marseille = $builder->build_object(
484             {   class => 'Koha::Cities',
485                 value => { city_country => $france->authorised_value, city_name => 'Marseille' }
486             }
487         );
488
489         my $mobj = $marseille->to_api( { av_expand => 1, public => 1 } );
490         my $cobj = $cordoba->to_api( { av_expand => 1, public => 0 } );
491
492         ok( exists $mobj->{_str}, '_str exists for Marseille' );
493         ok( exists $cobj->{_str}, '_str exists for Córdoba' );
494
495         is_deeply(
496             $mobj->{_str}->{country},
497             {
498                 category => $category->category_name,
499                 str      => $france->lib_opac,
500                 type     => 'av',
501             },
502             'Authorised value for country expanded'
503         );
504         is_deeply(
505             $cobj->{_str}->{country},
506             {
507                 category => $category->category_name,
508                 str      => $argentina->lib,
509                 type     => 'av'
510             },
511             'Authorised value for country expanded'
512         );
513
514         $schema->storage->txn_rollback;
515     };
516
517     $schema->storage->txn_rollback;
518 };
519
520 subtest "to_api_mapping() tests" => sub {
521
522     plan tests => 1;
523
524     $schema->storage->txn_begin;
525
526     my $illrequest = $builder->build_object({ class => 'Koha::Illrequests' });
527     is_deeply( $illrequest->to_api_mapping, {}, 'If no to_api_mapping present, return empty hashref' );
528
529     $schema->storage->txn_rollback;
530 };
531
532 subtest "from_api_mapping() tests" => sub {
533
534     plan tests => 5;
535
536     $schema->storage->txn_begin;
537
538     my $city = $builder->build_object({ class => 'Koha::Cities' });
539
540     # Lets emulate an undef
541     my $city_class = Test::MockModule->new('Koha::City');
542     $city_class->mock( 'to_api_mapping',
543         sub {
544             return {
545                 cityid       => 'city_id',
546                 city_country => 'country',
547                 city_zipcode => undef
548             };
549         }
550     );
551
552     is_deeply(
553         $city->from_api_mapping,
554         {
555             city_id => 'cityid',
556             country => 'city_country'
557         },
558         'Mapping returns correctly, undef ommited'
559     );
560
561     $city_class->unmock( 'to_api_mapping');
562     $city_class->mock( 'to_api_mapping',
563         sub {
564             return {
565                 cityid       => 'city_id',
566                 city_country => 'country',
567                 city_zipcode => 'postal_code'
568             };
569         }
570     );
571
572     is_deeply(
573         $city->from_api_mapping,
574         {
575             city_id => 'cityid',
576             country => 'city_country'
577         },
578         'Reverse mapping is cached'
579     );
580
581     # Get a fresh object
582     $city = $builder->build_object({ class => 'Koha::Cities' });
583     is_deeply(
584         $city->from_api_mapping,
585         {
586             city_id     => 'cityid',
587             country     => 'city_country',
588             postal_code => 'city_zipcode'
589         },
590         'Fresh mapping loaded'
591     );
592
593     $city_class->unmock( 'to_api_mapping');
594     $city_class->mock( 'to_api_mapping', undef );
595
596     # Get a fresh object
597     $city = $builder->build_object({ class => 'Koha::Cities' });
598     is_deeply(
599         $city->from_api_mapping,
600         {},
601         'No to_api_mapping then empty hashref'
602     );
603
604     $city_class->unmock( 'to_api_mapping');
605     $city_class->mock( 'to_api_mapping', sub { return; } );
606
607     # Get a fresh object
608     $city = $builder->build_object({ class => 'Koha::Cities' });
609     is_deeply(
610         $city->from_api_mapping,
611         {},
612         'Empty to_api_mapping then empty hashref'
613     );
614
615     $schema->storage->txn_rollback;
616 };
617
618 subtest 'set_from_api() tests' => sub {
619
620     plan tests => 4;
621
622     $schema->storage->txn_begin;
623
624     my $city = $builder->build_object({ class => 'Koha::Cities' });
625     my $city_unblessed = $city->unblessed;
626     my $attrs = {
627         name        => 'Cordoba',
628         country     => 'Argentina',
629         postal_code => '5000'
630     };
631     $city->set_from_api($attrs);
632
633     is( $city->city_state, $city_unblessed->{city_state}, 'Untouched attributes are preserved' );
634     is( $city->city_name, $attrs->{name}, 'city_name updated correctly' );
635     is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
636     is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
637
638     $schema->storage->txn_rollback;
639 };
640
641 subtest 'new_from_api() tests' => sub {
642
643     plan tests => 4;
644
645     $schema->storage->txn_begin;
646
647     my $attrs = {
648         name        => 'Cordoba',
649         country     => 'Argentina',
650         postal_code => '5000'
651     };
652     my $city = Koha::City->new_from_api($attrs);
653
654     is( ref($city), 'Koha::City', 'Object type is correct' );
655     is( $city->city_name,    $attrs->{name}, 'city_name updated correctly' );
656     is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
657     is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
658
659     $schema->storage->txn_rollback;
660 };
661
662 subtest 'attributes_from_api() tests' => sub {
663
664     plan tests => 2;
665
666     subtest 'date and date-time handling tests' => sub {
667
668         plan tests => 12;
669
670         my $patron = Koha::Patron->new();
671
672         my $attrs = $patron->attributes_from_api(
673             {
674                 updated_on     => '2019-12-27T14:53:00Z',
675                 last_seen      => '2019-12-27T14:53:00Z',
676                 date_of_birth  => '2019-12-27',
677             }
678         );
679
680         ok( exists $attrs->{updated_on},
681             'No translation takes place if no mapping' );
682         is(
683             $attrs->{updated_on},
684             '2019-12-27 14:53:00',
685             'Given an rfc3339 formatted datetime string, a timestamp field is converted into an SQL formatted datetime string'
686         );
687
688         ok( exists $attrs->{lastseen},
689             'Translation takes place because of the defined mapping' );
690         is(
691             $attrs->{lastseen},
692             '2019-12-27 14:53:00',
693             'Given an rfc3339 formatted datetime string, a datetime field is converted into an SQL formatted datetime string'
694         );
695
696         ok( exists $attrs->{dateofbirth},
697             'Translation takes place because of the defined mapping' );
698         is(
699             $attrs->{dateofbirth},
700             '2019-12-27',
701             'Given an rfc3339 formatted date string, a date field is converted into an SQL formatted date string'
702         );
703
704         $attrs = $patron->attributes_from_api(
705             {
706                 last_seen      => undef,
707                 date_of_birth  => undef,
708             }
709         );
710
711         ok( exists $attrs->{lastseen},
712             'undef parameter is not skipped (Bug 29157)' );
713         is(
714             $attrs->{lastseen},
715             undef,
716             'Given undef, a datetime field is set to undef (Bug 29157)'
717         );
718
719         ok( exists $attrs->{dateofbirth},
720             'undef parameter is not skipped (Bug 29157)' );
721         is(
722             $attrs->{dateofbirth},
723             undef,
724             'Given undef, a date field is set to undef (Bug 29157)'
725         );
726
727         throws_ok
728             {
729                 $attrs = $patron->attributes_from_api(
730                     {
731                         date_of_birth => '20141205',
732                     }
733                 );
734             }
735             'Koha::Exceptions::BadParameter',
736             'Bad date throws an exception';
737
738         is(
739             $@->parameter,
740             'date_of_birth',
741             'Exception parameter is the API field name, not the DB one'
742         );
743     };
744
745     subtest 'booleans handling tests' => sub {
746
747         plan tests => 4;
748
749         my $patron = Koha::Patron->new;
750
751         my $attrs = $patron->attributes_from_api(
752             {
753                 incorrect_address => Mojo::JSON->true,
754                 patron_card_lost  => Mojo::JSON->false,
755             }
756         );
757
758         ok( exists $attrs->{gonenoaddress}, 'Attribute gets translated' );
759         is( $attrs->{gonenoaddress}, 1, 'Boolean correctly translated to integer (true => 1)' );
760         ok( exists $attrs->{lost}, 'Attribute gets translated' );
761         is( $attrs->{lost}, 0, 'Boolean correctly translated to integer (false => 0)' );
762     };
763 };
764
765 subtest "Test update method" => sub {
766     plan tests => 6;
767
768     $schema->storage->txn_begin;
769
770     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
771     my $library = Koha::Libraries->find( $branchcode );
772     $library->update({ branchname => 'New_Name', branchcity => 'AMS' });
773     is( $library->branchname, 'New_Name', 'Changed name with update' );
774     is( $library->branchcity, 'AMS', 'Changed city too' );
775     is( $library->is_changed, 0, 'Change should be stored already' );
776     try {
777         $library->update({
778             branchcity => 'NYC', not_a_column => 53, branchname => 'Name3',
779         });
780         fail( 'It should not be possible to update an unexisting column without an error from Koha::Object/DBIx' );
781     } catch {
782         ok( $_->isa('Koha::Exceptions::Object'), 'Caught error when updating wrong column' );
783         $library->discard_changes; #requery after failing update
784     };
785     # Check if the columns are not updated
786     is( $library->branchcity, 'AMS', 'First column not updated' );
787     is( $library->branchname, 'New_Name', 'Third column not updated' );
788
789     $schema->storage->txn_rollback;
790 };
791
792 subtest 'store() tests' => sub {
793
794     plan tests => 16;
795
796     # Using Koha::Library::Groups to test Koha::Object>-store
797     # Simple object with foreign keys and unique key
798
799     $schema->storage->txn_begin;
800
801     # Create a library to make sure its ID doesn't exist on the DB
802     my $library = $builder->build_object({ class => 'Koha::Libraries' });
803     my $branchcode = $library->branchcode;
804     $library->delete;
805
806     my $library_group = Koha::Library::Group->new(
807         {
808             branchcode      => $library->branchcode,
809             title => 'a title',
810         }
811     );
812
813     my $dbh = $schema->storage->dbh;
814     {
815         local *STDERR;
816         open STDERR, '>', '/dev/null';
817         throws_ok
818             { $library_group->store }
819             'Koha::Exceptions::Object::FKConstraint',
820             'Exception is thrown correctly';
821         is(
822             $@->message,
823             "Broken FK constraint",
824             'Exception message is correct'
825         );
826         is(
827             $@->broken_fk,
828             'branchcode',
829             'Exception field is correct'
830         );
831
832         $library_group = $builder->build_object({ class => 'Koha::Library::Groups' });
833
834         my $new_library_group = Koha::Library::Group->new(
835             {
836                 branchcode      => $library_group->branchcode,
837                 title        => $library_group->title,
838             }
839         );
840
841         throws_ok
842             { $new_library_group->store }
843             'Koha::Exceptions::Object::DuplicateID',
844             'Exception is thrown correctly';
845
846         is(
847             $@->message,
848             'Duplicate ID',
849             'Exception message is correct'
850         );
851
852         like(
853            $@->duplicate_id,
854            qr/(library_groups\.)?title/,
855            'Exception field is correct (note that MySQL 8 is displaying the tablename)'
856         );
857         close STDERR;
858     }
859
860     # Successful test
861     $library_group->set({ title => 'Manuel' });
862     my $ret = $library_group->store;
863     is( ref($ret), 'Koha::Library::Group', 'store() returns the object on success' );
864
865     $library = $builder->build_object( { class => 'Koha::Libraries' } );
866     my $patron_category = $builder->build_object(
867         {
868             class => 'Koha::Patron::Categories',
869             value => { category_type => 'P', enrolmentfee => 0 }
870         }
871     );
872
873     my $patron = eval {
874         Koha::Patron->new(
875             {
876                 categorycode    => $patron_category->categorycode,
877                 branchcode      => $library->branchcode,
878                 dateofbirth     => "", # date will be set to NULL
879                 sms_provider_id => "", # Integer will be set to NULL
880                 privacy         => "", # privacy cannot be NULL but has a default value
881             }
882         )->store;
883     };
884     is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
885     is( $patron->privacy, 1, 'Default value for privacy should be set to 1' );
886     is( $patron->dateofbirth,     undef, 'dateofbirth must have been set to undef');
887     is( $patron->sms_provider_id, undef, 'sms_provider_id must have been set to undef');
888
889     my $itemtype = eval {
890         Koha::ItemType->new(
891             {
892                 itemtype        => 'IT4test',
893                 rentalcharge    => "",
894                 notforloan      => "",
895                 hideinopac      => "",
896             }
897         )->store;
898     };
899     is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
900     is( $itemtype->rentalcharge, undef, 'decimal DEFAULT NULL should default to null');
901     is( $itemtype->notforloan, undef, 'int DEFAULT NULL should default to null');
902     is( $itemtype->hideinopac, 0, 'int NOT NULL DEFAULT 0 should default to 0');
903
904     subtest 'Bad value tests' => sub {
905
906         plan tests => 3;
907
908         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
909
910
911         try {
912             local *STDERR;
913             open STDERR, '>', '/dev/null';
914             $patron->lastseen('wrong_value')->store;
915             close STDERR;
916         } catch {
917             ok( $_->isa('Koha::Exceptions::Object::BadValue'), 'Exception thrown correctly' );
918             like( $_->property, qr/(borrowers\.)?lastseen/, 'Column should be the expected one' ); # The table name is not always displayed, it depends on the DBMS version
919             is( $_->value, 'wrong_value', 'Value should be the expected one' );
920         };
921     };
922
923     $schema->storage->txn_rollback;
924 };
925
926 subtest 'unblessed_all_relateds' => sub {
927     plan tests => 3;
928
929     $schema->storage->txn_begin;
930
931     # FIXME It's very painful to create an issue in tests!
932     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
933     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
934
935     my $patron_category = $builder->build(
936         {
937             source => 'Category',
938             value  => {
939                 category_type                 => 'P',
940                 enrolmentfee                  => 0,
941                 BlockExpiredPatronOpacActions => -1, # Pick the pref value
942             }
943         }
944     );
945     my $patron_data = {
946         firstname =>  'firstname',
947         surname => 'surname',
948         categorycode => $patron_category->{categorycode},
949         branchcode => $library->branchcode,
950     };
951     my $patron = Koha::Patron->new($patron_data)->store;
952     my ($biblionumber) = AddBiblio( MARC::Record->new, '' );
953     my $biblio = Koha::Biblios->find( $biblionumber );
954     my $item = $builder->build_object(
955         {
956             class => 'Koha::Items',
957             value => {
958                 homebranch    => $library->branchcode,
959                 holdingbranch => $library->branchcode,
960                 biblionumber  => $biblio->biblionumber,
961                 itemlost      => 0,
962                 withdrawn     => 0,
963             }
964         }
965     );
966
967     my $issue = AddIssue( $patron->unblessed, $item->barcode, DateTime->now->subtract( days => 1 ) );
968     my $overdues = Koha::Patrons->find( $patron->id )->overdues; # Koha::Patron->overdues prefetches
969     my $overdue = $overdues->next->unblessed_all_relateds;
970     is( $overdue->{issue_id}, $issue->issue_id, 'unblessed_all_relateds has field from the original table (issues)' );
971     is( $overdue->{title}, $biblio->title, 'unblessed_all_relateds has field from other tables (biblio)' );
972     is( $overdue->{homebranch}, $item->homebranch, 'unblessed_all_relateds has field from other tables (items)' );
973
974     $schema->storage->txn_rollback;
975 };
976
977 subtest 'get_from_storage' => sub {
978     plan tests => 4;
979
980     $schema->storage->txn_begin;
981
982     my $biblio = $builder->build_sample_biblio;
983
984     my $old_title = $biblio->title;
985     my $new_title = 'new_title';
986     Koha::Biblios->find( $biblio->biblionumber )->title($new_title)->store;
987
988     is( $biblio->title, $old_title, 'current $biblio should not be modified' );
989     is( $biblio->get_from_storage->title,
990         $new_title, 'get_from_storage should return an updated object' );
991
992     Koha::Biblios->find( $biblio->biblionumber )->delete;
993     is( ref($biblio), 'Koha::Biblio', 'current $biblio should not be deleted' );
994     is( $biblio->get_from_storage, undef,
995         'get_from_storage should return undef if the object has been deleted' );
996
997     $schema->storage->txn_rollback;
998 };
999
1000 subtest 'prefetch_whitelist() tests' => sub {
1001
1002     plan tests => 3;
1003
1004     $schema->storage->txn_begin;
1005
1006     my $biblio = Koha::Biblio->new;
1007
1008     my $prefetch_whitelist = $biblio->prefetch_whitelist;
1009
1010     ok(
1011         exists $prefetch_whitelist->{orders},
1012         'Relationship matching method name is listed'
1013     );
1014     is(
1015         $prefetch_whitelist->{orders},
1016         'Koha::Acquisition::Order',
1017         'Guessed the non-standard object class correctly'
1018     );
1019
1020     is(
1021         $prefetch_whitelist->{items},
1022         'Koha::Item',
1023         'Guessed the standard object class correctly'
1024     );
1025
1026     $schema->storage->txn_rollback;
1027 };
1028
1029 subtest 'set_or_blank' => sub {
1030
1031     plan tests => 5;
1032
1033     $schema->storage->txn_begin;
1034
1035     my $item = $builder->build_sample_item;
1036     my $item_info = $item->unblessed;
1037     $item = $item->set_or_blank($item_info);
1038     is_deeply($item->unblessed, $item_info, 'set_or_blank assign the correct value if unchanged');
1039
1040     # int not null
1041     delete $item_info->{itemlost};
1042     $item = $item->set_or_blank($item_info);
1043     is($item->itemlost, 0, 'set_or_blank should have set itemlost to 0, default value defined in DB');
1044
1045     # int nullable
1046     delete $item_info->{restricted};
1047     $item = $item->set_or_blank($item_info);
1048     is($item->restricted, undef, 'set_or_blank should have set restristed to null' );
1049
1050     # datetime nullable
1051     delete $item_info->{dateaccessioned};
1052     $item = $item->set_or_blank($item_info);
1053     is($item->dateaccessioned, undef, 'set_or_blank should have set dateaccessioned to null');
1054
1055     # timestamp not null
1056     delete $item_info->{timestamp};
1057     $item = $item->set_or_blank($item_info);
1058     isnt($item->timestamp, undef, 'set_or_blank should have set timestamp to a correct value');
1059
1060     $schema->storage->txn_rollback;
1061 };
1062
1063 subtest 'messages() and add_message() tests' => sub {
1064
1065     plan tests => 7;
1066
1067     $schema->storage->txn_begin;
1068
1069     my $patron = Koha::Patron->new;
1070
1071     my @messages = @{ $patron->object_messages };
1072     is( scalar @messages, 0, 'No messages' );
1073
1074     $patron->add_message({ message => "message_1" });
1075     $patron->add_message({ message => "message_2" });
1076
1077     @messages = @{ $patron->object_messages };
1078
1079     is( scalar @messages, 2, 'Messages are returned' );
1080     is( ref($messages[0]), 'Koha::Object::Message', 'Right type returned' );
1081     is( ref($messages[1]), 'Koha::Object::Message', 'Right type returned' );
1082     is( $messages[0]->message, 'message_1', 'Right message recorded' );
1083
1084     my $patron_id = $builder->build_object({ class => 'Koha::Patrons' })->id;
1085     # get a patron from the DB, ->new is not called, ->object_messages should initialize _messages as an empty arrayref
1086     $patron = Koha::Patrons->find( $patron_id );
1087
1088     isnt( $patron->object_messages, undef, '->messages initializes the array if required' );
1089     is( scalar @{ $patron->object_messages }, 0, '->messages returns an empty arrayref' );
1090
1091     $schema->storage->txn_rollback;
1092 };