Bug 20287: Use more simple object for 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 => 11;
21 use Test::Exception;
22 use Test::Warn;
23 use DateTime;
24
25 use C4::Context;
26 use C4::Biblio; # AddBiblio
27 use C4::Circulation; # AddIssue
28 use Koha::Database;
29 use Koha::DateUtils qw( dt_from_string );
30 use Koha::Libraries;
31 use Koha::Patrons;
32 use Koha::ApiKeys;
33
34 use Scalar::Util qw( isvstring );
35 use Try::Tiny;
36
37 use t::lib::TestBuilder;
38
39 BEGIN {
40     use_ok('Koha::Object');
41     use_ok('Koha::Patron');
42 }
43
44 my $schema  = Koha::Database->new->schema;
45 my $builder = t::lib::TestBuilder->new();
46
47 subtest 'is_changed / make_column_dirty' => sub {
48     plan tests => 11;
49
50     $schema->storage->txn_begin;
51
52     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
53     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
54
55     my $object = Koha::Patron->new();
56     $object->categorycode( $categorycode );
57     $object->branchcode( $branchcode );
58     $object->surname("Test Surname");
59     $object->store();
60     is( $object->is_changed(), 0, "Object is unchanged" );
61     $object->surname("Test Surname");
62     is( $object->is_changed(), 0, "Object is still unchanged" );
63     $object->surname("Test Surname 2");
64     is( $object->is_changed(), 1, "Object is changed" );
65
66     $object->store();
67     is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
68
69     $object->set({ firstname => 'Test Firstname' });
70     is( $object->is_changed(), 1, "Object is changed after Set" );
71     $object->store();
72     is( $object->is_changed(), 0, "Object no longer marked as changed after being stored" );
73
74     # Test make_column_dirty
75     is( $object->make_column_dirty('firstname'), '', 'make_column_dirty returns empty string on success' );
76     is( $object->make_column_dirty('firstname'), 1, 'make_column_dirty returns 1 if already dirty' );
77     is( $object->is_changed, 1, "Object is changed after make dirty" );
78     $object->store;
79     is( $object->is_changed, 0, "Store clears dirty mark" );
80     $object->make_column_dirty('firstname');
81     $object->discard_changes;
82     is( $object->is_changed, 0, "Discard clears dirty mark too" );
83
84     $schema->storage->txn_rollback;
85 };
86
87 subtest 'in_storage' => sub {
88     plan tests => 6;
89
90     $schema->storage->txn_begin;
91
92     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
93     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
94
95     my $object = Koha::Patron->new();
96     is( $object->in_storage, 0, "Object is not in storage" );
97     $object->categorycode( $categorycode );
98     $object->branchcode( $branchcode );
99     $object->surname("Test Surname");
100     $object->store();
101     is( $object->in_storage, 1, "Object is now stored" );
102     $object->surname("another surname");
103     is( $object->in_storage, 1 );
104
105     my $borrowernumber = $object->borrowernumber;
106     my $patron = $schema->resultset('Borrower')->find( $borrowernumber );
107     is( $patron->surname(), "Test Surname", "Object found in database" );
108
109     $object->delete();
110     $patron = $schema->resultset('Borrower')->find( $borrowernumber );
111     ok( ! $patron, "Object no longer found in database" );
112     is( $object->in_storage, 0, "Object is not in storage" );
113
114     $schema->storage->txn_rollback;
115 };
116
117 subtest 'id' => sub {
118     plan tests => 1;
119
120     $schema->storage->txn_begin;
121
122     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
123     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
124
125     my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
126     is( $patron->id, $patron->borrowernumber );
127
128     $schema->storage->txn_rollback;
129 };
130
131 subtest 'get_column' => sub {
132     plan tests => 1;
133
134     $schema->storage->txn_begin;
135
136     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
137     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
138
139     my $patron = Koha::Patron->new({categorycode => $categorycode, branchcode => $branchcode })->store;
140     is( $patron->get_column('borrowernumber'), $patron->borrowernumber, 'get_column should retrieve the correct value' );
141
142     $schema->storage->txn_rollback;
143 };
144
145 subtest 'discard_changes' => sub {
146     plan tests => 1;
147
148     $schema->storage->txn_begin;
149
150     my $patron = $builder->build( { source => 'Borrower' } );
151     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
152     $patron->dateexpiry(dt_from_string);
153     $patron->discard_changes;
154     is(
155         dt_from_string( $patron->dateexpiry ),
156         dt_from_string->truncate( to => 'day' ),
157         'discard_changes should refresh the object'
158     );
159
160     $schema->storage->txn_rollback;
161 };
162
163 subtest 'TO_JSON tests' => sub {
164
165     plan tests => 8;
166
167     $schema->storage->txn_begin;
168
169     my $dt = dt_from_string();
170     my $borrowernumber = $builder->build(
171         { source => 'Borrower',
172           value => { lost => 1,
173                      sms_provider_id => undef,
174                      gonenoaddress => 0,
175                      updated_on => $dt,
176                      lastseen   => $dt, } })->{borrowernumber};
177
178     my $patron = Koha::Patrons->find($borrowernumber);
179     my $lost = $patron->TO_JSON()->{lost};
180     my $gonenoaddress = $patron->TO_JSON->{gonenoaddress};
181     my $updated_on = $patron->TO_JSON->{updated_on};
182     my $lastseen = $patron->TO_JSON->{lastseen};
183
184     ok( $lost->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
185     is( $lost, 1, 'Boolean attribute value is correct (true)' );
186
187     ok( $gonenoaddress->isa('JSON::PP::Boolean'), 'Boolean attribute type is correct' );
188     is( $gonenoaddress, 0, 'Boolean attribute value is correct (false)' );
189
190     is( $patron->TO_JSON->{sms_provider_id}, undef, 'Undef values should not be casted to 0' );
191
192     ok( !isvstring($patron->borrowernumber), 'Integer values are not coded as strings' );
193
194     my $rfc3999_regex = qr/
195             (?<year>\d{4})
196             -
197             (?<month>\d{2})
198             -
199             (?<day>\d{2})
200             ([Tt\s])
201             (?<hour>\d{2})
202             :
203             (?<minute>\d{2})
204             :
205             (?<second>\d{2})
206             (([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))
207         /xms;
208     like( $updated_on, $rfc3999_regex, "Date-time $updated_on formatted correctly");
209     like( $lastseen, $rfc3999_regex, "Date-time $updated_on formatted correctly");
210
211     $schema->storage->txn_rollback;
212 };
213
214 subtest "Test update method" => sub {
215     plan tests => 6;
216
217     $schema->storage->txn_begin;
218
219     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
220     my $library = Koha::Libraries->find( $branchcode );
221     $library->update({ branchname => 'New_Name', branchcity => 'AMS' });
222     is( $library->branchname, 'New_Name', 'Changed name with update' );
223     is( $library->branchcity, 'AMS', 'Changed city too' );
224     is( $library->is_changed, 0, 'Change should be stored already' );
225     try {
226         $library->update({
227             branchcity => 'NYC', not_a_column => 53, branchname => 'Name3',
228         });
229         fail( 'It should not be possible to update an unexisting column without an error from Koha::Object/DBIx' );
230     } catch {
231         ok( $_->isa('Koha::Exceptions::Object'), 'Caught error when updating wrong column' );
232         $library->discard_changes; #requery after failing update
233     };
234     # Check if the columns are not updated
235     is( $library->branchcity, 'AMS', 'First column not updated' );
236     is( $library->branchname, 'New_Name', 'Third column not updated' );
237
238     $schema->storage->txn_rollback;
239 };
240
241 subtest 'store() tests' => sub {
242
243     plan tests => 7;
244
245     # Using Koha::ApiKey to test Koha::Object>-store
246     # Simple object with foreign keys and unique key
247
248     $schema->storage->txn_begin;
249
250     # Create a patron to make sure its ID doesn't exist on the DB
251     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
252     my $patron_id = $patron->id;
253     $patron->delete;
254
255     my $api_key = Koha::ApiKey->new({ patron_id => $patron_id });
256
257     my $print_error = $schema->storage->dbh->{PrintError};
258     $schema->storage->dbh->{PrintError} = 0; # FIXME This does not longer work - because of the transaction in Koha::Patron->store?
259     throws_ok
260         { $api_key->store }
261         'Koha::Exceptions::Object::FKConstraint',
262         'Exception is thrown correctly';
263     is(
264         $@->message,
265         "Broken FK constraint",
266         'Exception message is correct'
267     );
268     is(
269         $@->broken_fk,
270         'patron_id',
271         'Exception field is correct'
272     );
273
274     $patron = $builder->build_object({ class => 'Koha::Patrons' });
275     $api_key = $builder->build_object({ class => 'Koha::ApiKeys' });
276
277     my $new_api_key = Koha::ApiKey->new({
278         patron_id => $patron_id,
279         secret => $api_key->secret,
280     });
281
282     throws_ok
283         { $new_api_key->store }
284         'Koha::Exceptions::Object::DuplicateID',
285         'Exception is thrown correctly';
286
287     is(
288         $@->message,
289         'Duplicate ID',
290         'Exception message is correct'
291     );
292
293     is(
294        $@->duplicate_id,
295        'secret',
296        'Exception field is correct'
297     );
298
299     $schema->storage->dbh->{PrintError} = $print_error;
300
301     # Successful test
302     $api_key->set({ secret => 'Manuel' });
303     my $ret = $api_key->store;
304     is( ref($ret), 'Koha::ApiKey', 'store() returns the object on success' );
305
306     $schema->storage->txn_rollback;
307 };
308
309 subtest 'unblessed_all_relateds' => sub {
310     plan tests => 3;
311
312     $schema->storage->txn_begin;
313
314     # FIXME It's very painful to create an issue in tests!
315     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
316     C4::Context->_new_userenv('xxx');
317     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Midway Public Library', '', '', '');
318     my $patron_category = $builder->build(
319         {
320             source => 'Category',
321             value  => {
322                 category_type                 => 'P',
323                 enrolmentfee                  => 0,
324                 BlockExpiredPatronOpacActions => -1, # Pick the pref value
325             }
326         }
327     );
328     my $patron_data = {
329         firstname =>  'firstname',
330         surname => 'surname',
331         categorycode => $patron_category->{categorycode},
332         branchcode => $library->branchcode,
333     };
334     my $patron = Koha::Patron->new($patron_data)->store;
335     my ($biblionumber) = AddBiblio( MARC::Record->new, '' );
336     my $biblio = Koha::Biblios->find( $biblionumber );
337     my $item = $builder->build_object(
338         {
339             class => 'Koha::Items',
340             value => {
341                 homebranch    => $library->branchcode,
342                 holdingbranch => $library->branchcode,
343                 biblionumber  => $biblio->biblionumber,
344                 itemlost      => 0,
345                 withdrawn     => 0,
346             }
347         }
348     );
349
350     my $issue = AddIssue( $patron->unblessed, $item->barcode, DateTime->now->subtract( days => 1 ) );
351     my $overdues = Koha::Patrons->find( $patron->id )->get_overdues; # Koha::Patron->get_overdue prefetches
352     my $overdue = $overdues->next->unblessed_all_relateds;
353     is( $overdue->{issue_id}, $issue->issue_id, 'unblessed_all_relateds has field from the original table (issues)' );
354     is( $overdue->{title}, $biblio->title, 'unblessed_all_relateds has field from other tables (biblio)' );
355     is( $overdue->{homebranch}, $item->homebranch, 'unblessed_all_relateds has field from other tables (items)' );
356
357     $schema->storage->txn_rollback;
358 };