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