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