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