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