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