Bug 24228: Add parameters to Koha::Object(s)->to_api to automatically embed objects
[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 => 17;
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::ApiKeys;
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 => 18;
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 $item_class = Test::MockModule->new('Koha::Item');
266     $item_class->mock( 'to_api_mapping',
267         sub {
268             return {
269                 itemnumber       => 'item_id'
270             };
271         }
272     );
273
274     my $hold_class = Test::MockModule->new('Koha::Hold');
275     $hold_class->mock( 'to_api_mapping',
276         sub {
277             return {
278                 reserve_id       => 'hold_id'
279             };
280         }
281     );
282
283     my $biblio = $builder->build_sample_biblio();
284     my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber });
285     my $hold = $builder->build_object({ class => 'Koha::Holds', value => { itemnumber => $item->itemnumber } });
286
287     my @embeds = ('items');
288
289     my $biblio_api = $biblio->to_api(\@embeds);
290
291     ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
292     is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item matches');
293     ok(!exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet');
294
295     @embeds = ('items.holds');
296     $biblio_api = $biblio->to_api(\@embeds);
297
298     ok(exists $biblio_api->{items}, 'Items where embedded in biblio results');
299     is($biblio_api->{items}->[0]->{item_id}, $item->itemnumber, 'Item still matches');
300     ok(exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded');
301     is($biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $hold->reserve_id, 'Hold matches');
302
303     $schema->storage->txn_rollback;
304 };
305
306 subtest "to_api_mapping() tests" => sub {
307
308     plan tests => 1;
309
310     $schema->storage->txn_begin;
311
312     my $illrequest = $builder->build_object({ class => 'Koha::Illrequests' });
313     is_deeply( $illrequest->to_api_mapping, {}, 'If no to_api_mapping present, return empty hashref' );
314
315     $schema->storage->txn_rollback;
316 };
317
318 subtest "from_api_mapping() tests" => sub {
319
320     plan tests => 3;
321
322     $schema->storage->txn_begin;
323
324     my $city = $builder->build_object({ class => 'Koha::Cities' });
325
326     # Lets emulate an undef
327     my $city_class = Test::MockModule->new('Koha::City');
328     $city_class->mock( 'to_api_mapping',
329         sub {
330             return {
331                 cityid       => 'city_id',
332                 city_country => 'country',
333                 city_zipcode => undef
334             };
335         }
336     );
337
338     is_deeply(
339         $city->from_api_mapping,
340         {
341             city_id => 'cityid',
342             country => 'city_country'
343         },
344         'Mapping returns correctly, undef ommited'
345     );
346
347     $city_class->unmock( 'to_api_mapping');
348     $city_class->mock( 'to_api_mapping',
349         sub {
350             return {
351                 cityid       => 'city_id',
352                 city_country => 'country',
353                 city_zipcode => 'postal_code'
354             };
355         }
356     );
357
358     is_deeply(
359         $city->from_api_mapping,
360         {
361             city_id => 'cityid',
362             country => 'city_country'
363         },
364         'Reverse mapping is cached'
365     );
366
367     # Get a fresh object
368     $city = $builder->build_object({ class => 'Koha::Cities' });
369     is_deeply(
370         $city->from_api_mapping,
371         {
372             city_id     => 'cityid',
373             country     => 'city_country',
374             postal_code => 'city_zipcode'
375         },
376         'Fresh mapping loaded'
377     );
378
379     $schema->storage->txn_rollback;
380 };
381
382 subtest 'set_from_api() tests' => sub {
383
384     plan tests => 4;
385
386     $schema->storage->txn_begin;
387
388     my $city = $builder->build_object({ class => 'Koha::Cities' });
389     my $city_unblessed = $city->unblessed;
390     my $attrs = {
391         name        => 'Cordoba',
392         country     => 'Argentina',
393         postal_code => '5000'
394     };
395     $city->set_from_api($attrs);
396
397     is( $city->city_state, $city_unblessed->{city_state}, 'Untouched attributes are preserved' );
398     is( $city->city_name, $attrs->{name}, 'city_name updated correctly' );
399     is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
400     is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
401
402     $schema->storage->txn_rollback;
403 };
404
405 subtest 'new_from_api() tests' => sub {
406
407     plan tests => 4;
408
409     $schema->storage->txn_begin;
410
411     my $attrs = {
412         name        => 'Cordoba',
413         country     => 'Argentina',
414         postal_code => '5000'
415     };
416     my $city = Koha::City->new_from_api($attrs);
417
418     is( ref($city), 'Koha::City', 'Object type is correct' );
419     is( $city->city_name,    $attrs->{name}, 'city_name updated correctly' );
420     is( $city->city_country, $attrs->{country}, 'city_country updated correctly' );
421     is( $city->city_zipcode, $attrs->{postal_code}, 'city_zipcode updated correctly' );
422
423     $schema->storage->txn_rollback;
424 };
425
426 subtest 'attributes_from_api() tests' => sub {
427
428     plan tests => 8;
429
430     my $patron = Koha::Patron->new();
431
432     use Data::Printer colored => 1;
433
434     my $attrs = $patron->attributes_from_api(
435         {
436             updated_on  => '2019-12-27T14:53:00'
437         }
438     );
439
440     ok( exists $attrs->{updated_on},
441         'No translation takes place if no mapping' );
442     is(
443         ref( $attrs->{updated_on} ),
444         'DateTime',
445         'Given a string, a timestamp field is converted into a DateTime object'
446     );
447
448     $attrs = $patron->attributes_from_api(
449         {
450             last_seen  => '2019-12-27T14:53:00'
451         }
452     );
453
454     ok( exists $attrs->{lastseen},
455         'Translation takes place because of the defined mapping' );
456     is(
457         ref( $attrs->{lastseen} ),
458         'DateTime',
459         'Given a string, a datetime field is converted into a DateTime object'
460     );
461
462     $attrs = $patron->attributes_from_api(
463         {
464             date_of_birth  => '2019-12-27'
465         }
466     );
467
468     ok( exists $attrs->{dateofbirth},
469         'Translation takes place because of the defined mapping' );
470     is(
471         ref( $attrs->{dateofbirth} ),
472         'DateTime',
473         'Given a string, a date field is converted into a DateTime object'
474     );
475
476     throws_ok
477         {
478             $attrs = $patron->attributes_from_api(
479                 {
480                     date_of_birth => '20141205',
481                 }
482             );
483         }
484         'Koha::Exceptions::BadParameter',
485         'Bad date throws an exception';
486
487     is(
488         $@->parameter,
489         'date_of_birth',
490         'Exception parameter is the API field name, not the DB one'
491     );
492 };
493
494 subtest "Test update method" => sub {
495     plan tests => 6;
496
497     $schema->storage->txn_begin;
498
499     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
500     my $library = Koha::Libraries->find( $branchcode );
501     $library->update({ branchname => 'New_Name', branchcity => 'AMS' });
502     is( $library->branchname, 'New_Name', 'Changed name with update' );
503     is( $library->branchcity, 'AMS', 'Changed city too' );
504     is( $library->is_changed, 0, 'Change should be stored already' );
505     try {
506         $library->update({
507             branchcity => 'NYC', not_a_column => 53, branchname => 'Name3',
508         });
509         fail( 'It should not be possible to update an unexisting column without an error from Koha::Object/DBIx' );
510     } catch {
511         ok( $_->isa('Koha::Exceptions::Object'), 'Caught error when updating wrong column' );
512         $library->discard_changes; #requery after failing update
513     };
514     # Check if the columns are not updated
515     is( $library->branchcity, 'AMS', 'First column not updated' );
516     is( $library->branchname, 'New_Name', 'Third column not updated' );
517
518     $schema->storage->txn_rollback;
519 };
520
521 subtest 'store() tests' => sub {
522
523     plan tests => 16;
524
525     # Using Koha::ApiKey to test Koha::Object>-store
526     # Simple object with foreign keys and unique key
527
528     $schema->storage->txn_begin;
529
530     # Create a patron to make sure its ID doesn't exist on the DB
531     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
532     my $patron_id = $patron->id;
533     $patron->delete;
534
535     my $api_key = Koha::ApiKey->new({ patron_id => $patron_id, secret => 'a secret', description => 'a description' });
536
537     my $print_error = $schema->storage->dbh->{PrintError};
538     $schema->storage->dbh->{PrintError} = 0;
539     throws_ok
540         { $api_key->store }
541         'Koha::Exceptions::Object::FKConstraint',
542         'Exception is thrown correctly';
543     is(
544         $@->message,
545         "Broken FK constraint",
546         'Exception message is correct'
547     );
548     is(
549         $@->broken_fk,
550         'patron_id',
551         'Exception field is correct'
552     );
553
554     $patron = $builder->build_object({ class => 'Koha::Patrons' });
555     $api_key = $builder->build_object({ class => 'Koha::ApiKeys' });
556
557     my $new_api_key = Koha::ApiKey->new({
558         patron_id => $patron_id,
559         secret => $api_key->secret,
560         description => 'a description',
561     });
562
563     throws_ok
564         { $new_api_key->store }
565         'Koha::Exceptions::Object::DuplicateID',
566         'Exception is thrown correctly';
567
568     is(
569         $@->message,
570         'Duplicate ID',
571         'Exception message is correct'
572     );
573
574     is(
575        $@->duplicate_id,
576        'secret',
577        'Exception field is correct'
578     );
579
580     $schema->storage->dbh->{PrintError} = $print_error;
581
582     # Successful test
583     $api_key->set({ secret => 'Manuel' });
584     my $ret = $api_key->store;
585     is( ref($ret), 'Koha::ApiKey', 'store() returns the object on success' );
586
587     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
588     my $patron_category = $builder->build_object(
589         {
590             class => 'Koha::Patron::Categories',
591             value => { category_type => 'P', enrolmentfee => 0 }
592         }
593     );
594
595     $patron = eval {
596         Koha::Patron->new(
597             {
598                 categorycode    => $patron_category->categorycode,
599                 branchcode      => $library->branchcode,
600                 dateofbirth     => "", # date will be set to NULL
601                 sms_provider_id => "", # Integer will be set to NULL
602                 privacy         => "", # privacy cannot be NULL but has a default value
603             }
604         )->store;
605     };
606     is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
607     is( $patron->privacy, 1, 'Default value for privacy should be set to 1' );
608     is( $patron->dateofbirth,     undef, 'dateofbirth must have been set to undef');
609     is( $patron->sms_provider_id, undef, 'sms_provider_id must have been set to undef');
610
611     my $itemtype = eval {
612         Koha::ItemType->new(
613             {
614                 itemtype        => 'IT4test',
615                 rentalcharge    => "",
616                 notforloan      => "",
617                 hideinopac      => "",
618             }
619         )->store;
620     };
621     is( $@, '', 'No error should be raised by ->store if empty strings are passed' );
622     is( $itemtype->rentalcharge, undef, 'decimal DEFAULT NULL should default to null');
623     is( $itemtype->notforloan, undef, 'int DEFAULT NULL should default to null');
624     is( $itemtype->hideinopac, 0, 'int NOT NULL DEFAULT 0 should default to 0');
625
626     subtest 'Bad value tests' => sub {
627
628         plan tests => 3;
629
630         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
631
632         my $print_error = $schema->storage->dbh->{PrintError};
633         $schema->storage->dbh->{PrintError} = 0;
634
635         try {
636             $patron->lastseen('wrong_value')->store;
637         } catch {
638             ok( $_->isa('Koha::Exceptions::Object::BadValue'), 'Exception thrown correctly' );
639             like( $_->property, qr/(borrowers\.)?lastseen/, 'Column should be the expected one' ); # The table name is not always displayed, it depends on the DBMS version
640             is( $_->value, 'wrong_value', 'Value should be the expected one' );
641         };
642
643         $schema->storage->dbh->{PrintError} = $print_error;
644     };
645
646     $schema->storage->txn_rollback;
647 };
648
649 subtest 'unblessed_all_relateds' => sub {
650     plan tests => 3;
651
652     $schema->storage->txn_begin;
653
654     # FIXME It's very painful to create an issue in tests!
655     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
656     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
657
658     my $patron_category = $builder->build(
659         {
660             source => 'Category',
661             value  => {
662                 category_type                 => 'P',
663                 enrolmentfee                  => 0,
664                 BlockExpiredPatronOpacActions => -1, # Pick the pref value
665             }
666         }
667     );
668     my $patron_data = {
669         firstname =>  'firstname',
670         surname => 'surname',
671         categorycode => $patron_category->{categorycode},
672         branchcode => $library->branchcode,
673     };
674     my $patron = Koha::Patron->new($patron_data)->store;
675     my ($biblionumber) = AddBiblio( MARC::Record->new, '' );
676     my $biblio = Koha::Biblios->find( $biblionumber );
677     my $item = $builder->build_object(
678         {
679             class => 'Koha::Items',
680             value => {
681                 homebranch    => $library->branchcode,
682                 holdingbranch => $library->branchcode,
683                 biblionumber  => $biblio->biblionumber,
684                 itemlost      => 0,
685                 withdrawn     => 0,
686             }
687         }
688     );
689
690     my $issue = AddIssue( $patron->unblessed, $item->barcode, DateTime->now->subtract( days => 1 ) );
691     my $overdues = Koha::Patrons->find( $patron->id )->get_overdues; # Koha::Patron->get_overdue prefetches
692     my $overdue = $overdues->next->unblessed_all_relateds;
693     is( $overdue->{issue_id}, $issue->issue_id, 'unblessed_all_relateds has field from the original table (issues)' );
694     is( $overdue->{title}, $biblio->title, 'unblessed_all_relateds has field from other tables (biblio)' );
695     is( $overdue->{homebranch}, $item->homebranch, 'unblessed_all_relateds has field from other tables (items)' );
696
697     $schema->storage->txn_rollback;
698 };