3 # This file is part of Koha.
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.
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.
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>.
20 use Test::More tests => 21;
25 use C4::Circulation qw( AddIssue );
26 use C4::Biblio qw( AddBiblio );
30 use Koha::Acquisition::Orders;
32 use Koha::AuthorisedValueCategories;
33 use Koha::AuthorisedValues;
34 use Koha::DateUtils qw( dt_from_string );
37 use Koha::Library::Groups;
40 use Scalar::Util qw( isvstring );
43 use t::lib::TestBuilder;
47 use_ok('Koha::Object');
48 use_ok('Koha::Patron');
51 my $schema = Koha::Database->new->schema;
52 my $builder = t::lib::TestBuilder->new();
54 subtest 'is_changed / make_column_dirty' => sub {
57 $schema->storage->txn_begin;
59 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
60 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
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" );
74 is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
76 $object->set({ firstname => 'Test Firstname' });
77 is( $object->is_changed(), 1, "Object is changed after Set" );
79 is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
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" );
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" );
91 $schema->storage->txn_rollback;
94 subtest 'in_storage' => sub {
97 $schema->storage->txn_begin;
99 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
100 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
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");
108 is( $object->in_storage, 1, "Object is now stored" );
109 $object->surname("another surname");
110 is( $object->in_storage, 1 );
112 my $borrowernumber = $object->borrowernumber;
113 my $patron = $schema->resultset('Borrower')->find( $borrowernumber );
114 is( $patron->surname(), "Test Surname", "Object found in database" );
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" );
121 $schema->storage->txn_rollback;
124 subtest 'id' => sub {
127 $schema->storage->txn_begin;
129 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
130 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
132 my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
133 is( $patron->id, $patron->borrowernumber );
135 $schema->storage->txn_rollback;
138 subtest 'get_column' => sub {
141 $schema->storage->txn_begin;
143 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
144 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
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' );
149 $schema->storage->txn_rollback;
152 subtest 'discard_changes' => sub {
155 $schema->storage->txn_begin;
157 my $patron = $builder->build( { source => 'Borrower' } );
158 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
159 $patron->dateexpiry(dt_from_string);
160 $patron->discard_changes;
162 dt_from_string( $patron->dateexpiry ),
163 dt_from_string->truncate( to => 'day' ),
164 'discard_changes should refresh the object'
167 $schema->storage->txn_rollback;
170 subtest 'TO_JSON tests' => sub {
174 $schema->storage->txn_begin;
176 my $dt = dt_from_string();
177 my $borrowernumber = $builder->build(
178 { source => 'Borrower',
179 value => { lost => 1,
180 sms_provider_id => undef,
183 lastseen => $dt, } })->{borrowernumber};
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};
191 ok( $lost->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
192 is( $lost, 1, 'Boolean attribute value is correct (true)' );
194 ok( $gonenoaddress->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
195 is( $gonenoaddress, 0, 'Boolean attribute value is correct (false)' );
197 is( $patron->TO_JSON->{sms_provider_id}, undef, 'Undef values should not be casted to 0' );
199 ok( !isvstring($patron->borrowernumber), 'Integer values are not coded as strings' );
201 my $rfc3999_regex = qr/
213 (([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))
215 like( $updated_on, $rfc3999_regex, "Date-time $updated_on formatted correctly");
216 like( $lastseen, $rfc3999_regex, "Date-time $updated_on formatted correctly");
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' );
223 $schema->storage->txn_rollback;
226 subtest "to_api() tests" => sub {
230 $schema->storage->txn_begin;
232 my $city = $builder->build_object({ class => 'Koha::Cities' });
235 # cityid => 'city_id',
236 # city_country => 'country',
237 # city_name => 'name',
238 # city_state => 'state',
239 # city_zipcode => 'postal_code'
241 my $api_city = $city->to_api;
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' );
249 # Lets emulate an undef
250 my $city_class = Test::MockModule->new('Koha::City');
251 $city_class->mock( 'to_api_mapping',
255 city_country => 'country',
257 city_state => 'state',
258 city_zipcode => undef
263 $api_city = $city->to_api;
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' );
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' );
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 } });
279 my $embeds = { 'items' => {} };
281 my $biblio_api = $biblio->to_api({ embed => $embeds });
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');
297 $biblio_api = $biblio->to_api({ embed => $embeds });
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');
308 str => 'Estante alto',
313 # mock Koha::Item so it implements 'strings_map'
314 my $item_mock = Test::MockModule->new('Koha::Item');
322 my $hold_api = $hold->to_api(
324 embed => { 'item' => { strings => 1 } }
328 is( ref($hold_api->{item}), 'HASH', 'Single nested object works correctly' );
329 is( $hold_api->{item}->{item_id}, $item->itemnumber, 'Object embedded correctly' );
331 $hold_api->{item}->{_strings},
333 '_strings correctly added to nested embed'
336 # biblio with no items
337 my $new_biblio = $builder->build_sample_biblio;
338 my $new_biblio_api = $new_biblio->to_api({ embed => $embeds });
340 is_deeply( $new_biblio_api->{items}, [], 'Empty list if no items' );
342 my $biblio_class = Test::MockModule->new('Koha::Biblio');
343 $biblio_class->mock( 'undef_result', sub { return; } );
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' );
349 $biblio_class->mock( 'items',
350 sub { return [ bless { itemnumber => 1 }, 'Somethings' ]; } );
353 $new_biblio_api = $new_biblio->to_api(
354 { embed => { 'items' => { children => { asd => {} } } } } );
357 "An exception is thrown if a blessed object to embed doesn't implement to_api";
361 "Asked to embed items but its return value doesn't implement to_api",
362 "Exception message correct"
366 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
367 $builder->build_object(
369 class => 'Koha::Holds',
371 biblionumber => $biblio->biblionumber,
372 borrowernumber => $patron->borrowernumber
376 $builder->build_object(
378 class => 'Koha::Holds',
380 biblionumber => $biblio->biblionumber,
381 borrowernumber => $patron->borrowernumber
386 my $patron_api = $patron->to_api(
388 embed => { holds_count => { is_count => 1 } }
391 is( $patron_api->{holds_count}, $patron->holds->count, 'Count embeds are supported and work as expected' );
395 $patron->to_api({ embed => { holds_count => {} } });
397 'Koha::Exceptions::Object::MethodNotCoveredByTests',
398 'Unknown method exception thrown if is_count not specified';
400 subtest 'unprivileged request tests' => sub {
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;
406 plan tests => scalar @all_attrs * 2;
408 # Create a sample library
409 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
411 my $unprivileged_representation = $library->to_api({ public => 1 });
412 my $privileged_representation = $library->to_api;
414 foreach my $attr (@all_attrs) {
415 my $mapped = exists $mapping->{$attr} ? $mapping->{$attr} : $attr;
416 if ( defined($mapped) ) {
418 exists $privileged_representation->{$mapped},
419 "Attribute '$attr' is present when privileged"
421 if ( exists $public_attrs->{$attr} ) {
423 exists $unprivileged_representation->{$mapped},
424 "Attribute '$attr' is present when public"
429 !exists $unprivileged_representation->{$mapped},
430 "Attribute '$attr' is not present when public"
436 !exists $privileged_representation->{$attr},
437 "Unmapped attribute '$attr' is not present when privileged"
440 !exists $unprivileged_representation->{$attr},
441 "Unmapped attribute '$attr' is not present when public"
447 subtest 'Authorised values expansion' => sub {
451 $schema->storage->txn_begin;
454 my $category = $builder->build_object({ class => 'Koha::AuthorisedValueCategories' });
456 my $argentina = $builder->build_object(
457 { class => 'Koha::AuthorisedValues',
459 category => $category->category_name,
460 lib => 'AR (Argentina)',
461 lib_opac => 'Argentina',
465 my $france = $builder->build_object(
466 { class => 'Koha::AuthorisedValues',
468 category => $category->category_name,
469 lib => 'FR (France)',
470 lib_opac => 'France',
475 my $city_mock = Test::MockModule->new('Koha::City');
479 my ( $self, $params ) = @_;
481 my $av = Koha::AuthorisedValues->find(
483 authorised_value => $self->city_country,
484 category => $category->category_name,
490 category => $av->category,
491 str => ( $params->{public} ) ? $av->lib_opac : $av->lib,
497 $city_mock->mock( 'public_read_list', sub { return [ 'city_id', 'city_country', 'city_name', 'city_state' ] } );
499 my $cordoba = $builder->build_object(
500 { class => 'Koha::Cities',
501 value => { city_country => $argentina->authorised_value, city_name => 'Cordoba' }
504 my $marseille = $builder->build_object(
505 { class => 'Koha::Cities',
506 value => { city_country => $france->authorised_value, city_name => 'Marseille' }
510 my $mobj = $marseille->to_api( { strings => 1, public => 1 } );
511 my $cobj = $cordoba->to_api( { strings => 1, public => 0 } );
513 ok( exists $mobj->{_strings}, '_strings exists for Marseille' );
514 ok( exists $cobj->{_strings}, '_strings exists for Córdoba' );
517 $mobj->{_strings}->{country},
519 category => $category->category_name,
520 str => $france->lib_opac,
523 'Authorised value for country expanded'
526 $cobj->{_strings}->{country},
528 category => $category->category_name,
529 str => $argentina->lib,
532 'Authorised value for country expanded'
535 $schema->storage->txn_rollback;
538 $schema->storage->txn_rollback;
541 subtest "to_api_mapping() tests" => sub {
545 $schema->storage->txn_begin;
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' );
550 $schema->storage->txn_rollback;
553 subtest "from_api_mapping() tests" => sub {
557 $schema->storage->txn_begin;
559 my $city = $builder->build_object({ class => 'Koha::Cities' });
561 # Lets emulate an undef
562 my $city_class = Test::MockModule->new('Koha::City');
563 $city_class->mock( 'to_api_mapping',
567 city_country => 'country',
568 city_zipcode => undef
574 $city->from_api_mapping,
577 country => 'city_country'
579 'Mapping returns correctly, undef ommited'
582 $city_class->unmock( 'to_api_mapping');
583 $city_class->mock( 'to_api_mapping',
587 city_country => 'country',
588 city_zipcode => 'postal_code'
594 $city->from_api_mapping,
597 country => 'city_country'
599 'Reverse mapping is cached'
603 $city = $builder->build_object({ class => 'Koha::Cities' });
605 $city->from_api_mapping,
608 country => 'city_country',
609 postal_code => 'city_zipcode'
611 'Fresh mapping loaded'
614 $city_class->unmock( 'to_api_mapping');
615 $city_class->mock( 'to_api_mapping', undef );
618 $city = $builder->build_object({ class => 'Koha::Cities' });
620 $city->from_api_mapping,
622 'No to_api_mapping then empty hashref'
625 $city_class->unmock( 'to_api_mapping');
626 $city_class->mock( 'to_api_mapping', sub { return; } );
629 $city = $builder->build_object({ class => 'Koha::Cities' });
631 $city->from_api_mapping,
633 'Empty to_api_mapping then empty hashref'
636 $schema->storage->txn_rollback;
639 subtest 'set_from_api() tests' => sub {
643 $schema->storage->txn_begin;
645 my $city = $builder->build_object({ class => 'Koha::Cities' });
646 my $city_unblessed = $city->unblessed;
649 country => 'Argentina',
650 postal_code => '5000'
652 $city->set_from_api($attrs);
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' );
659 $schema->storage->txn_rollback;
662 subtest 'new_from_api() tests' => sub {
666 $schema->storage->txn_begin;
670 country => 'Argentina',
671 postal_code => '5000'
673 my $city = Koha::City->new_from_api($attrs);
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' );
680 $schema->storage->txn_rollback;
683 subtest 'attributes_from_api() tests' => sub {
687 subtest 'date and date-time handling tests' => sub {
691 my $patron = Koha::Patron->new();
693 my $attrs = $patron->attributes_from_api(
695 updated_on => '2019-12-27T14:53:00Z',
696 last_seen => '2019-12-27T14:53:00Z',
697 date_of_birth => '2019-12-27',
701 ok( exists $attrs->{updated_on},
702 'No translation takes place if no mapping' );
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'
709 ok( exists $attrs->{lastseen},
710 'Translation takes place because of the defined mapping' );
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'
717 ok( exists $attrs->{dateofbirth},
718 'Translation takes place because of the defined mapping' );
720 $attrs->{dateofbirth},
722 'Given an rfc3339 formatted date string, a date field is converted into an SQL formatted date string'
725 $attrs = $patron->attributes_from_api(
728 date_of_birth => undef,
732 ok( exists $attrs->{lastseen},
733 'undef parameter is not skipped (Bug 29157)' );
737 'Given undef, a datetime field is set to undef (Bug 29157)'
740 ok( exists $attrs->{dateofbirth},
741 'undef parameter is not skipped (Bug 29157)' );
743 $attrs->{dateofbirth},
745 'Given undef, a date field is set to undef (Bug 29157)'
750 $attrs = $patron->attributes_from_api(
752 date_of_birth => '20141205',
756 'Koha::Exceptions::BadParameter',
757 'Bad date throws an exception';
762 'Exception parameter is the API field name, not the DB one'
766 subtest 'booleans handling tests' => sub {
770 my $patron = Koha::Patron->new;
772 my $attrs = $patron->attributes_from_api(
774 incorrect_address => Mojo::JSON->true,
775 patron_card_lost => Mojo::JSON->false,
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)' );
786 subtest "Test update method" => sub {
789 $schema->storage->txn_begin;
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' );
799 branchcity => 'NYC', not_a_column => 53, branchname => 'Name3',
801 fail( 'It should not be possible to update an unexisting column without an error from Koha::Object/DBIx' );
803 ok( $_->isa('Koha::Exceptions::Object'), 'Caught error when updating wrong column' );
804 $library->discard_changes; #requery after failing update
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' );
810 $schema->storage->txn_rollback;
813 subtest 'store() tests' => sub {
817 # Using Koha::Library::Groups to test Koha::Object>-store
818 # Simple object with foreign keys and unique key
820 $schema->storage->txn_begin;
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;
827 my $library_group = Koha::Library::Group->new(
829 branchcode => $library->branchcode,
834 my $dbh = $schema->storage->dbh;
837 open STDERR, '>', '/dev/null';
839 { $library_group->store }
840 'Koha::Exceptions::Object::FKConstraint',
841 'Exception is thrown correctly';
844 "Broken FK constraint",
845 'Exception message is correct'
850 'Exception field is correct'
853 $library_group = $builder->build_object({ class => 'Koha::Library::Groups' });
855 my $new_library_group = Koha::Library::Group->new(
857 branchcode => $library_group->branchcode,
858 title => $library_group->title,
863 { $new_library_group->store }
864 'Koha::Exceptions::Object::DuplicateID',
865 'Exception is thrown correctly';
870 'Exception message is correct'
875 qr/(library_groups\.)?title/,
876 'Exception field is correct (note that MySQL 8 is displaying the tablename)'
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' );
886 $library = $builder->build_object( { class => 'Koha::Libraries' } );
887 my $patron_category = $builder->build_object(
889 class => 'Koha::Patron::Categories',
890 value => { category_type => 'P', enrolmentfee => 0 }
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
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');
910 my $itemtype = eval {
913 itemtype => 'IT4test',
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');
925 subtest 'Bad value tests' => sub {
929 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
934 open STDERR, '>', '/dev/null';
935 $patron->lastseen('wrong_value')->store;
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' );
944 $schema->storage->txn_rollback;
947 subtest 'unblessed_all_relateds' => sub {
950 $schema->storage->txn_begin;
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 });
956 my $patron_category = $builder->build(
958 source => 'Category',
960 category_type => 'P',
962 BlockExpiredPatronOpacActions => -1, # Pick the pref value
967 firstname => 'firstname',
968 surname => 'surname',
969 categorycode => $patron_category->{categorycode},
970 branchcode => $library->branchcode,
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(
978 class => 'Koha::Items',
980 homebranch => $library->branchcode,
981 holdingbranch => $library->branchcode,
982 biblionumber => $biblio->biblionumber,
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)' );
997 $schema->storage->txn_rollback;
1000 subtest 'get_from_storage' => sub {
1003 $schema->storage->txn_begin;
1005 my $biblio = $builder->build_sample_biblio;
1007 my $old_title = $biblio->title;
1008 my $new_title = 'new_title';
1009 Koha::Biblios->find( $biblio->biblionumber )->title($new_title)->store;
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' );
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' );
1020 $schema->storage->txn_rollback;
1023 subtest 'prefetch_whitelist() tests' => sub {
1027 $schema->storage->txn_begin;
1029 my $biblio = Koha::Biblio->new;
1031 my $prefetch_whitelist = $biblio->prefetch_whitelist;
1034 exists $prefetch_whitelist->{orders},
1035 'Relationship matching method name is listed'
1038 $prefetch_whitelist->{orders},
1039 'Koha::Acquisition::Order',
1040 'Guessed the non-standard object class correctly'
1044 $prefetch_whitelist->{items},
1046 'Guessed the standard object class correctly'
1049 $schema->storage->txn_rollback;
1052 subtest 'set_or_blank' => sub {
1056 $schema->storage->txn_begin;
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');
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');
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' );
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');
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');
1083 $schema->storage->txn_rollback;
1086 subtest 'messages() and add_message() tests' => sub {
1090 $schema->storage->txn_begin;
1092 my $patron = Koha::Patron->new;
1094 my @messages = @{ $patron->object_messages };
1095 is( scalar @messages, 0, 'No messages' );
1097 $patron->add_message({ message => "message_1" });
1098 $patron->add_message({ message => "message_2" });
1100 @messages = @{ $patron->object_messages };
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' );
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 );
1111 isnt( $patron->object_messages, undef, '->messages initializes the array if required' );
1112 is( scalar @{ $patron->object_messages }, 0, '->messages returns an empty arrayref' );
1114 $schema->storage->txn_rollback;