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;
26 use C4::Circulation qw( AddIssue );
27 use C4::Biblio qw( AddBiblio );
31 use Koha::Acquisition::Orders;
33 use Koha::AuthorisedValueCategories;
34 use Koha::AuthorisedValues;
35 use Koha::DateUtils qw( dt_from_string );
38 use Koha::Library::Groups;
41 use Scalar::Util qw( isvstring );
44 use t::lib::TestBuilder;
48 use_ok('Koha::Object');
49 use_ok('Koha::Patron');
52 my $schema = Koha::Database->new->schema;
53 my $builder = t::lib::TestBuilder->new();
55 subtest 'is_changed / make_column_dirty' => sub {
58 $schema->storage->txn_begin;
60 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
61 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
63 my $object = Koha::Patron->new();
64 $object->categorycode( $categorycode );
65 $object->branchcode( $branchcode );
66 $object->surname("Test Surname");
67 $object->store->discard_changes;
68 is( $object->is_changed(), 0, "Object is unchanged" );
69 $object->surname("Test Surname");
70 is( $object->is_changed(), 0, "Object is still unchanged" );
71 $object->surname("Test Surname 2");
72 is( $object->is_changed(), 1, "Object is changed" );
75 is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
77 $object->set({ firstname => 'Test Firstname' });
78 is( $object->is_changed(), 1, "Object is changed after Set" );
80 is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
82 # Test make_column_dirty
83 is( $object->make_column_dirty('firstname'), '', 'make_column_dirty returns empty string on success' );
84 is( $object->make_column_dirty('firstname'), 1, 'make_column_dirty returns 1 if already dirty' );
85 is( $object->is_changed, 1, "Object is changed after make dirty" );
87 is( $object->is_changed, 0, "Store clears dirty mark" );
88 $object->make_column_dirty('firstname');
89 $object->discard_changes;
90 is( $object->is_changed, 0, "Discard clears dirty mark too" );
92 $schema->storage->txn_rollback;
95 subtest 'in_storage' => sub {
98 $schema->storage->txn_begin;
100 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
101 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
103 my $object = Koha::Patron->new();
104 is( $object->in_storage, 0, "Object is not in storage" );
105 $object->categorycode( $categorycode );
106 $object->branchcode( $branchcode );
107 $object->surname("Test Surname");
109 is( $object->in_storage, 1, "Object is now stored" );
110 $object->surname("another surname");
111 is( $object->in_storage, 1 );
113 my $borrowernumber = $object->borrowernumber;
114 my $patron = $schema->resultset('Borrower')->find( $borrowernumber );
115 is( $patron->surname(), "Test Surname", "Object found in database" );
118 $patron = $schema->resultset('Borrower')->find( $borrowernumber );
119 ok( ! $patron, "Object no longer found in database" );
120 is( $object->in_storage, 0, "Object is not in storage" );
122 $schema->storage->txn_rollback;
125 subtest 'id' => sub {
128 $schema->storage->txn_begin;
130 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
131 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
133 my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
134 is( $patron->id, $patron->borrowernumber );
136 $schema->storage->txn_rollback;
139 subtest 'get_column' => sub {
142 $schema->storage->txn_begin;
144 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
145 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
147 my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
148 is( $patron->get_column('borrowernumber'), $patron->borrowernumber, 'get_column should retrieve the correct value' );
150 $schema->storage->txn_rollback;
153 subtest 'discard_changes' => sub {
156 $schema->storage->txn_begin;
158 my $patron = $builder->build( { source => 'Borrower' } );
159 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
160 $patron->dateexpiry(dt_from_string);
161 $patron->discard_changes;
163 dt_from_string( $patron->dateexpiry ),
164 dt_from_string->truncate( to => 'day' ),
165 'discard_changes should refresh the object'
168 $schema->storage->txn_rollback;
171 subtest 'TO_JSON tests' => sub {
175 $schema->storage->txn_begin;
177 my $dt = dt_from_string();
178 my $borrowernumber = $builder->build(
179 { source => 'Borrower',
180 value => { lost => 1,
181 sms_provider_id => undef,
184 lastseen => $dt, } })->{borrowernumber};
186 my $patron = Koha::Patrons->find($borrowernumber);
187 my $lost = $patron->TO_JSON()->{lost};
188 my $gonenoaddress = $patron->TO_JSON->{gonenoaddress};
189 my $updated_on = $patron->TO_JSON->{updated_on};
190 my $lastseen = $patron->TO_JSON->{lastseen};
192 ok( $lost->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
193 is( $lost, 1, 'Boolean attribute value is correct (true)' );
195 ok( $gonenoaddress->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
196 is( $gonenoaddress, 0, 'Boolean attribute value is correct (false)' );
198 is( $patron->TO_JSON->{sms_provider_id}, undef, 'Undef values should not be casted to 0' );
200 ok( !isvstring($patron->borrowernumber), 'Integer values are not coded as strings' );
202 my $rfc3999_regex = qr/
214 (([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))
216 like( $updated_on, $rfc3999_regex, "Date-time $updated_on formatted correctly");
217 like( $lastseen, $rfc3999_regex, "Date-time $updated_on formatted correctly");
219 # Test JSON doesn't receive strings
220 my $order = $builder->build_object({ class => 'Koha::Acquisition::Orders' });
221 $order = Koha::Acquisition::Orders->find( $order->ordernumber );
222 is_deeply( $order->TO_JSON, decode_json( encode_json( $order->TO_JSON ) ), 'Orders are similar' );
224 $schema->storage->txn_rollback;
227 subtest "to_api() tests" => sub {
231 $schema->storage->txn_begin;
233 my $city = $builder->build_object({ class => 'Koha::Cities' });
236 # cityid => 'city_id',
237 # city_country => 'country',
238 # city_name => 'name',
239 # city_state => 'state',
240 # city_zipcode => 'postal_code'
242 my $api_city = $city->to_api;
244 is( $api_city->{city_id}, $city->cityid, 'Attribute translated correctly' );
245 is( $api_city->{country}, $city->city_country, 'Attribute translated correctly' );
246 is( $api_city->{name}, $city->city_name, 'Attribute translated correctly' );
247 is( $api_city->{state}, $city->city_state, 'Attribute translated correctly' );
248 is( $api_city->{postal_code}, $city->city_zipcode, 'Attribute translated correctly' );
250 # Lets emulate an undef
251 my $city_class = Test::MockModule->new('Koha::City');
252 $city_class->mock( 'to_api_mapping',
256 city_country => 'country',
258 city_state => 'state',
259 city_zipcode => undef
264 $api_city = $city->to_api;
266 is( $api_city->{city_id}, $city->cityid, 'Attribute translated correctly' );
267 is( $api_city->{country}, $city->city_country, 'Attribute translated correctly' );
268 is( $api_city->{name}, $city->city_name, 'Attribute translated correctly' );
269 is( $api_city->{state}, $city->city_state, 'Attribute translated correctly' );
270 ok( !exists $api_city->{postal_code}, 'Attribute removed' );
272 # Pick a class that won't have a mapping for the API
273 my $illrequest = $builder->build_object({ class => 'Koha::Illrequests' });
274 is_deeply( $illrequest->to_api, $illrequest->TO_JSON, 'If no overloaded to_api_mapping method, return TO_JSON' );
276 my $biblio = $builder->build_sample_biblio();
277 my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
278 my $hold = $builder->build_object({ class => 'Koha::Holds', value => { itemnumber => $item->itemnumber } });
280 my $embeds = { 'items' => {} };
282 my $biblio_api = $biblio->to_api({ embed => $embeds });
284 ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
285 is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item matches');
286 ok(!exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet');
298 $biblio_api = $biblio->to_api({ embed => $embeds });
300 ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
301 is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item still matches');
302 ok(exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded');
303 is($biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $hold->reserve_id, 'Hold matches');
304 is_deeply($biblio_api->{biblioitem}, $biblio->biblioitem->to_api, 'More than one root');
309 str => 'Estante alto',
314 # mock Koha::Item so it implements 'api_strings_mapping'
315 my $item_mock = Test::MockModule->new('Koha::Item');
317 'api_strings_mapping',
323 my $hold_api = $hold->to_api(
325 embed => { 'item' => { strings => 1 } }
329 is( ref($hold_api->{item}), 'HASH', 'Single nested object works correctly' );
330 is( $hold_api->{item}->{item_id}, $item->itemnumber, 'Object embedded correctly' );
332 $hold_api->{item}->{_strings},
334 '_strings correctly added to nested embed'
337 # biblio with no items
338 my $new_biblio = $builder->build_sample_biblio;
339 my $new_biblio_api = $new_biblio->to_api({ embed => $embeds });
341 is_deeply( $new_biblio_api->{items}, [], 'Empty list if no items' );
343 my $biblio_class = Test::MockModule->new('Koha::Biblio');
344 $biblio_class->mock( 'undef_result', sub { return; } );
346 $new_biblio_api = $new_biblio->to_api({ embed => ( { 'undef_result' => {} } ) });
347 ok( exists $new_biblio_api->{undef_result}, 'If a method returns undef, then the attribute is defined' );
348 is( $new_biblio_api->{undef_result}, undef, 'If a method returns undef, then the attribute is undef' );
350 $biblio_class->mock( 'items',
351 sub { return [ bless { itemnumber => 1 }, 'Somethings' ]; } );
354 $new_biblio_api = $new_biblio->to_api(
355 { embed => { 'items' => { children => { asd => {} } } } } );
358 "An exception is thrown if a blessed object to embed doesn't implement to_api";
362 "Asked to embed items but its return value doesn't implement to_api",
363 "Exception message correct"
367 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
368 $builder->build_object(
370 class => 'Koha::Holds',
372 biblionumber => $biblio->biblionumber,
373 borrowernumber => $patron->borrowernumber
377 $builder->build_object(
379 class => 'Koha::Holds',
381 biblionumber => $biblio->biblionumber,
382 borrowernumber => $patron->borrowernumber
387 my $patron_api = $patron->to_api(
389 embed => { holds_count => { is_count => 1 } }
392 is( $patron_api->{holds_count}, $patron->holds->count, 'Count embeds are supported and work as expected' );
396 $patron->to_api({ embed => { holds_count => {} } });
398 'Koha::Exceptions::Object::MethodNotCoveredByTests',
399 'Unknown method exception thrown if is_count not specified';
401 subtest 'unprivileged request tests' => sub {
403 my @all_attrs = Koha::Libraries->columns();
404 my $public_attrs = { map { $_ => 1 } @{ Koha::Library->public_read_list() } };
405 my $mapping = Koha::Library->to_api_mapping;
407 plan tests => scalar @all_attrs * 2;
409 # Create a sample library
410 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
412 my $unprivileged_representation = $library->to_api({ public => 1 });
413 my $privileged_representation = $library->to_api;
415 foreach my $attr (@all_attrs) {
416 my $mapped = exists $mapping->{$attr} ? $mapping->{$attr} : $attr;
417 if ( defined($mapped) ) {
419 exists $privileged_representation->{$mapped},
420 "Attribute '$attr' is present when privileged"
422 if ( exists $public_attrs->{$attr} ) {
424 exists $unprivileged_representation->{$mapped},
425 "Attribute '$attr' is present when public"
430 !exists $unprivileged_representation->{$mapped},
431 "Attribute '$attr' is not present when public"
437 !exists $privileged_representation->{$attr},
438 "Unmapped attribute '$attr' is not present when privileged"
441 !exists $unprivileged_representation->{$attr},
442 "Unmapped attribute '$attr' is not present when public"
448 subtest 'Authorised values expansion' => sub {
452 $schema->storage->txn_begin;
455 my $category = $builder->build_object({ class => 'Koha::AuthorisedValueCategories' });
457 my $argentina = $builder->build_object(
458 { class => 'Koha::AuthorisedValues',
460 category => $category->category_name,
461 lib => 'AR (Argentina)',
462 lib_opac => 'Argentina',
466 my $france = $builder->build_object(
467 { class => 'Koha::AuthorisedValues',
469 category => $category->category_name,
470 lib => 'FR (France)',
471 lib_opac => 'France',
476 my $city_mock = Test::MockModule->new('Koha::City');
478 'api_strings_mapping',
480 my ( $self, $params ) = @_;
482 my $av = Koha::AuthorisedValues->find(
484 authorised_value => $self->city_country,
485 category => $category->category_name,
491 category => $av->category,
492 str => ( $params->{public} ) ? $av->lib_opac : $av->lib,
498 $city_mock->mock( 'public_read_list', sub { return [ 'city_id', 'city_country', 'city_name', 'city_state' ] } );
500 my $cordoba = $builder->build_object(
501 { class => 'Koha::Cities',
502 value => { city_country => $argentina->authorised_value, city_name => 'Cordoba' }
505 my $marseille = $builder->build_object(
506 { class => 'Koha::Cities',
507 value => { city_country => $france->authorised_value, city_name => 'Marseille' }
511 my $mobj = $marseille->to_api( { strings => 1, public => 1 } );
512 my $cobj = $cordoba->to_api( { strings => 1, public => 0 } );
514 ok( exists $mobj->{_strings}, '_strings exists for Marseille' );
515 ok( exists $cobj->{_strings}, '_strings exists for Córdoba' );
518 $mobj->{_strings}->{country},
520 category => $category->category_name,
521 str => $france->lib_opac,
524 'Authorised value for country expanded'
527 $cobj->{_strings}->{country},
529 category => $category->category_name,
530 str => $argentina->lib,
533 'Authorised value for country expanded'
536 $schema->storage->txn_rollback;
539 $schema->storage->txn_rollback;
542 subtest "to_api_mapping() tests" => sub {
546 $schema->storage->txn_begin;
548 my $illrequest = $builder->build_object({ class => 'Koha::Illrequests' });
549 is_deeply( $illrequest->to_api_mapping, {}, 'If no to_api_mapping present, return empty hashref' );
551 $schema->storage->txn_rollback;
554 subtest "from_api_mapping() tests" => sub {
558 $schema->storage->txn_begin;
560 my $city = $builder->build_object({ class => 'Koha::Cities' });
562 # Lets emulate an undef
563 my $city_class = Test::MockModule->new('Koha::City');
564 $city_class->mock( 'to_api_mapping',
568 city_country => 'country',
569 city_zipcode => undef
575 $city->from_api_mapping,
578 country => 'city_country'
580 'Mapping returns correctly, undef ommited'
583 $city_class->unmock( 'to_api_mapping');
584 $city_class->mock( 'to_api_mapping',
588 city_country => 'country',
589 city_zipcode => 'postal_code'
595 $city->from_api_mapping,
598 country => 'city_country'
600 'Reverse mapping is cached'
604 $city = $builder->build_object({ class => 'Koha::Cities' });
606 $city->from_api_mapping,
609 country => 'city_country',
610 postal_code => 'city_zipcode'
612 'Fresh mapping loaded'
615 $city_class->unmock( 'to_api_mapping');
616 $city_class->mock( 'to_api_mapping', undef );
619 $city = $builder->build_object({ class => 'Koha::Cities' });
621 $city->from_api_mapping,
623 'No to_api_mapping then empty hashref'
626 $city_class->unmock( 'to_api_mapping');
627 $city_class->mock( 'to_api_mapping', sub { return; } );
630 $city = $builder->build_object({ class => 'Koha::Cities' });
632 $city->from_api_mapping,
634 'Empty to_api_mapping then empty hashref'
637 $schema->storage->txn_rollback;
640 subtest 'set_from_api() tests' => sub {
644 $schema->storage->txn_begin;
646 my $city = $builder->build_object({ class => 'Koha::Cities' });
647 my $city_unblessed = $city->unblessed;
650 country => 'Argentina',
651 postal_code => '5000'
653 $city->set_from_api($attrs);
655 is( $city->city_state, $city_unblessed->{city_state}, 'Untouched attributes are preserved' );
656 is( $city->city_name, $attrs->{name}, 'city_name updated correctly' );
657 is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
658 is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
660 $schema->storage->txn_rollback;
663 subtest 'new_from_api() tests' => sub {
667 $schema->storage->txn_begin;
671 country => 'Argentina',
672 postal_code => '5000'
674 my $city = Koha::City->new_from_api($attrs);
676 is( ref($city), 'Koha::City', 'Object type is correct' );
677 is( $city->city_name, $attrs->{name}, 'city_name updated correctly' );
678 is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
679 is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
681 $schema->storage->txn_rollback;
684 subtest 'attributes_from_api() tests' => sub {
688 subtest 'date and date-time handling tests' => sub {
692 my $patron = Koha::Patron->new();
694 my $attrs = $patron->attributes_from_api(
696 updated_on => '2019-12-27T14:53:00Z',
697 last_seen => '2019-12-27T14:53:00Z',
698 date_of_birth => '2019-12-27',
702 ok( exists $attrs->{updated_on},
703 'No translation takes place if no mapping' );
705 $attrs->{updated_on},
706 '2019-12-27 14:53:00',
707 'Given an rfc3339 formatted datetime string, a timestamp field is converted into an SQL formatted datetime string'
710 ok( exists $attrs->{lastseen},
711 'Translation takes place because of the defined mapping' );
714 '2019-12-27 14:53:00',
715 'Given an rfc3339 formatted datetime string, a datetime field is converted into an SQL formatted datetime string'
718 ok( exists $attrs->{dateofbirth},
719 'Translation takes place because of the defined mapping' );
721 $attrs->{dateofbirth},
723 'Given an rfc3339 formatted date string, a date field is converted into an SQL formatted date string'
726 $attrs = $patron->attributes_from_api(
729 date_of_birth => undef,
733 ok( exists $attrs->{lastseen},
734 'undef parameter is not skipped (Bug 29157)' );
738 'Given undef, a datetime field is set to undef (Bug 29157)'
741 ok( exists $attrs->{dateofbirth},
742 'undef parameter is not skipped (Bug 29157)' );
744 $attrs->{dateofbirth},
746 'Given undef, a date field is set to undef (Bug 29157)'
751 $attrs = $patron->attributes_from_api(
753 date_of_birth => '20141205',
757 'Koha::Exceptions::BadParameter',
758 'Bad date throws an exception';
763 'Exception parameter is the API field name, not the DB one'
767 subtest 'booleans handling tests' => sub {
771 my $patron = Koha::Patron->new;
773 my $attrs = $patron->attributes_from_api(
775 incorrect_address => Mojo::JSON->true,
776 patron_card_lost => Mojo::JSON->false,
780 ok( exists $attrs->{gonenoaddress}, 'Attribute gets translated' );
781 is( $attrs->{gonenoaddress}, 1, 'Boolean correctly translated to integer (true => 1)' );
782 ok( exists $attrs->{lost}, 'Attribute gets translated' );
783 is( $attrs->{lost}, 0, 'Boolean correctly translated to integer (false => 0)' );
787 subtest "Test update method" => sub {
790 $schema->storage->txn_begin;
792 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
793 my $library = Koha::Libraries->find( $branchcode );
794 $library->update({ branchname => 'New_Name', branchcity => 'AMS' });
795 is( $library->branchname, 'New_Name', 'Changed name with update' );
796 is( $library->branchcity, 'AMS', 'Changed city too' );
797 is( $library->is_changed, 0, 'Change should be stored already' );
800 branchcity => 'NYC', not_a_column => 53, branchname => 'Name3',
802 fail( 'It should not be possible to update an unexisting column without an error from Koha::Object/DBIx' );
804 ok( $_->isa('Koha::Exceptions::Object'), 'Caught error when updating wrong column' );
805 $library->discard_changes; #requery after failing update
807 # Check if the columns are not updated
808 is( $library->branchcity, 'AMS', 'First column not updated' );
809 is( $library->branchname, 'New_Name', 'Third column not updated' );
811 $schema->storage->txn_rollback;
814 subtest 'store() tests' => sub {
818 # Using Koha::Library::Groups to test Koha::Object>-store
819 # Simple object with foreign keys and unique key
821 $schema->storage->txn_begin;
823 # Create a library to make sure its ID doesn't exist on the DB
824 my $library = $builder->build_object({ class => 'Koha::Libraries' });
825 my $branchcode = $library->branchcode;
828 my $library_group = Koha::Library::Group->new(
830 branchcode => $library->branchcode,
835 my $dbh = $schema->storage->dbh;
838 open STDERR, '>', '/dev/null';
840 { $library_group->store }
841 'Koha::Exceptions::Object::FKConstraint',
842 'Exception is thrown correctly';
845 "Broken FK constraint",
846 'Exception message is correct'
851 'Exception field is correct'
854 $library_group = $builder->build_object({ class => 'Koha::Library::Groups' });
856 my $new_library_group = Koha::Library::Group->new(
858 branchcode => $library_group->branchcode,
859 title => $library_group->title,
864 { $new_library_group->store }
865 'Koha::Exceptions::Object::DuplicateID',
866 'Exception is thrown correctly';
871 'Exception message is correct'
876 qr/(library_groups\.)?title/,
877 'Exception field is correct (note that MySQL 8 is displaying the tablename)'
883 $library_group->set({ title => 'Manuel' });
884 my $ret = $library_group->store;
885 is( ref($ret), 'Koha::Library::Group', 'store() returns the object on success' );
887 $library = $builder->build_object( { class => 'Koha::Libraries' } );
888 my $patron_category = $builder->build_object(
890 class => 'Koha::Patron::Categories',
891 value => { category_type => 'P', enrolmentfee => 0 }
898 categorycode => $patron_category->categorycode,
899 branchcode => $library->branchcode,
900 dateofbirth => "", # date will be set to NULL
901 sms_provider_id => "", # Integer will be set to NULL
902 privacy => "", # privacy cannot be NULL but has a default value
906 is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
907 is( $patron->privacy, 1, 'Default value for privacy should be set to 1' );
908 is( $patron->dateofbirth, undef, 'dateofbirth must have been set to undef');
909 is( $patron->sms_provider_id, undef, 'sms_provider_id must have been set to undef');
911 my $itemtype = eval {
914 itemtype => 'IT4test',
921 is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
922 is( $itemtype->rentalcharge, undef, 'decimal DEFAULT NULL should default to null');
923 is( $itemtype->notforloan, undef, 'int DEFAULT NULL should default to null');
924 is( $itemtype->hideinopac, 0, 'int NOT NULL DEFAULT 0 should default to 0');
926 subtest 'Bad value tests' => sub {
930 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
935 open STDERR, '>', '/dev/null';
936 $patron->lastseen('wrong_value')->store;
939 ok( $_->isa('Koha::Exceptions::Object::BadValue'), 'Exception thrown correctly' );
940 like( $_->property, qr/(borrowers\.)?lastseen/, 'Column should be the expected one' ); # The table name is not always displayed, it depends on the DBMS version
941 is( $_->value, 'wrong_value', 'Value should be the expected one' );
945 $schema->storage->txn_rollback;
948 subtest 'unblessed_all_relateds' => sub {
951 $schema->storage->txn_begin;
953 # FIXME It's very painful to create an issue in tests!
954 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
955 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
957 my $patron_category = $builder->build(
959 source => 'Category',
961 category_type => 'P',
963 BlockExpiredPatronOpacActions => -1, # Pick the pref value
968 firstname => 'firstname',
969 surname => 'surname',
970 categorycode => $patron_category->{categorycode},
971 branchcode => $library->branchcode,
973 my $patron = Koha::Patron->new($patron_data)->store;
974 my ($biblionumber) = AddBiblio( MARC::Record->new, '' );
975 my $biblio = Koha::Biblios->find( $biblionumber );
976 my $item = $builder->build_object(
978 class => 'Koha::Items',
980 homebranch => $library->branchcode,
981 holdingbranch => $library->branchcode,
982 biblionumber => $biblio->biblionumber,
989 my $issue = AddIssue( $patron->unblessed, $item->barcode, DateTime->now->subtract( days => 1 ) );
990 my $overdues = Koha::Patrons->find( $patron->id )->overdues; # Koha::Patron->overdues prefetches
991 my $overdue = $overdues->next->unblessed_all_relateds;
992 is( $overdue->{issue_id}, $issue->issue_id, 'unblessed_all_relateds has field from the original table (issues)' );
993 is( $overdue->{title}, $biblio->title, 'unblessed_all_relateds has field from other tables (biblio)' );
994 is( $overdue->{homebranch}, $item->homebranch, 'unblessed_all_relateds has field from other tables (items)' );
996 $schema->storage->txn_rollback;
999 subtest 'get_from_storage' => sub {
1002 $schema->storage->txn_begin;
1004 my $biblio = $builder->build_sample_biblio;
1006 my $old_title = $biblio->title;
1007 my $new_title = 'new_title';
1008 Koha::Biblios->find( $biblio->biblionumber )->title($new_title)->store;
1010 is( $biblio->title, $old_title, 'current $biblio should not be modified' );
1011 is( $biblio->get_from_storage->title,
1012 $new_title, 'get_from_storage should return an updated object' );
1014 Koha::Biblios->find( $biblio->biblionumber )->delete;
1015 is( ref($biblio), 'Koha::Biblio', 'current $biblio should not be deleted' );
1016 is( $biblio->get_from_storage, undef,
1017 'get_from_storage should return undef if the object has been deleted' );
1019 $schema->storage->txn_rollback;
1022 subtest 'prefetch_whitelist() tests' => sub {
1026 $schema->storage->txn_begin;
1028 my $biblio = Koha::Biblio->new;
1030 my $prefetch_whitelist = $biblio->prefetch_whitelist;
1033 exists $prefetch_whitelist->{orders},
1034 'Relationship matching method name is listed'
1037 $prefetch_whitelist->{orders},
1038 'Koha::Acquisition::Order',
1039 'Guessed the non-standard object class correctly'
1043 $prefetch_whitelist->{items},
1045 'Guessed the standard object class correctly'
1048 $schema->storage->txn_rollback;
1051 subtest 'set_or_blank' => sub {
1055 $schema->storage->txn_begin;
1057 my $item = $builder->build_sample_item;
1058 my $item_info = $item->unblessed;
1059 $item = $item->set_or_blank($item_info);
1060 is_deeply($item->unblessed, $item_info, 'set_or_blank assign the correct value if unchanged');
1063 delete $item_info->{itemlost};
1064 $item = $item->set_or_blank($item_info);
1065 is($item->itemlost, 0, 'set_or_blank should have set itemlost to 0, default value defined in DB');
1068 delete $item_info->{restricted};
1069 $item = $item->set_or_blank($item_info);
1070 is($item->restricted, undef, 'set_or_blank should have set restristed to null' );
1073 delete $item_info->{dateaccessioned};
1074 $item = $item->set_or_blank($item_info);
1075 is($item->dateaccessioned, undef, 'set_or_blank should have set dateaccessioned to null');
1077 # timestamp not null
1078 delete $item_info->{timestamp};
1079 $item = $item->set_or_blank($item_info);
1080 isnt($item->timestamp, undef, 'set_or_blank should have set timestamp to a correct value');
1082 $schema->storage->txn_rollback;
1085 subtest 'messages() and add_message() tests' => sub {
1089 $schema->storage->txn_begin;
1091 my $patron = Koha::Patron->new;
1093 my @messages = @{ $patron->object_messages };
1094 is( scalar @messages, 0, 'No messages' );
1096 $patron->add_message({ message => "message_1" });
1097 $patron->add_message({ message => "message_2" });
1099 @messages = @{ $patron->object_messages };
1101 is( scalar @messages, 2, 'Messages are returned' );
1102 is( ref($messages[0]), 'Koha::Object::Message', 'Right type returned' );
1103 is( ref($messages[1]), 'Koha::Object::Message', 'Right type returned' );
1104 is( $messages[0]->message, 'message_1', 'Right message recorded' );
1106 my $patron_id = $builder->build_object({ class => 'Koha::Patrons' })->id;
1107 # get a patron from the DB, ->new is not called, ->object_messages should initialize _messages as an empty arrayref
1108 $patron = Koha::Patrons->find( $patron_id );
1110 isnt( $patron->object_messages, undef, '->messages initializes the array if required' );
1111 is( scalar @{ $patron->object_messages }, 0, '->messages returns an empty arrayref' );
1113 $schema->storage->txn_rollback;