Bug 24908: Unit tests
[koha.git] / t / db_dependent / api / v1 / patrons.t
1 #!/usr/bin/env 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 => 7;
21 use Test::Mojo;
22 use Test::Warn;
23
24 use t::lib::TestBuilder;
25 use t::lib::Mocks;
26
27 use C4::Auth;
28 use Koha::Database;
29 use Koha::Patron::Debarments qw/AddDebarment/;
30
31 my $schema  = Koha::Database->new->schema;
32 my $builder = t::lib::TestBuilder->new;
33
34 my $t = Test::Mojo->new('Koha::REST::V1');
35 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
36
37 subtest 'list() tests' => sub {
38     plan tests => 2;
39
40     $schema->storage->txn_begin;
41     unauthorized_access_tests('GET', undef, undef);
42     $schema->storage->txn_rollback;
43
44     subtest 'librarian access tests' => sub {
45         plan tests => 13;
46
47         $schema->storage->txn_begin;
48
49         my $librarian = $builder->build_object(
50             {
51                 class => 'Koha::Patrons',
52                 value => { flags => 2**4 }    # borrowers flag = 4
53             }
54         );
55         my $password = 'thePassword123';
56         $librarian->set_password( { password => $password, skip_validation => 1 } );
57         my $userid = $librarian->userid;
58
59         $t->get_ok("//$userid:$password@/api/v1/patrons")
60           ->status_is(200);
61
62         $t->get_ok("//$userid:$password@/api/v1/patrons?cardnumber=" . $librarian->cardnumber)
63           ->status_is(200)
64           ->json_is('/0/cardnumber' => $librarian->cardnumber);
65
66         $t->get_ok("//$userid:$password@/api/v1/patrons?address2=" . $librarian->address2)
67           ->status_is(200)
68           ->json_is('/0/address2' => $librarian->address2);
69
70         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
71         AddDebarment({ borrowernumber => $patron->borrowernumber });
72
73         $t->get_ok("//$userid:$password@/api/v1/patrons?restricted=" . Mojo::JSON->true . "&cardnumber=" . $patron->cardnumber )
74           ->status_is(200)
75           ->json_has('/0/restricted')
76           ->json_is( '/0/restricted' => Mojo::JSON->true )
77           ->json_hasnt('/1');
78
79         $schema->storage->txn_rollback;
80     };
81 };
82
83 subtest 'get() tests' => sub {
84     plan tests => 2;
85
86     $schema->storage->txn_begin;
87     unauthorized_access_tests('GET', -1, undef);
88     $schema->storage->txn_rollback;
89
90     subtest 'librarian access tests' => sub {
91         plan tests => 6;
92
93         $schema->storage->txn_begin;
94
95         my $librarian = $builder->build_object(
96             {
97                 class => 'Koha::Patrons',
98                 value => { flags => 2**4 }    # borrowers flag = 4
99             }
100         );
101         my $password = 'thePassword123';
102         $librarian->set_password( { password => $password, skip_validation => 1 } );
103         my $userid = $librarian->userid;
104
105         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
106
107         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id)
108           ->status_is(200)
109           ->json_is('/patron_id'        => $patron->id)
110           ->json_is('/category_id'      => $patron->categorycode )
111           ->json_is('/surname'          => $patron->surname)
112           ->json_is('/patron_card_lost' => Mojo::JSON->false );
113
114         $schema->storage->txn_rollback;
115     };
116 };
117
118 subtest 'add() tests' => sub {
119     plan tests => 2;
120
121     $schema->storage->txn_begin;
122
123     my $patron = $builder->build_object( { class => 'Koha::Patrons' } )->to_api;
124
125     unauthorized_access_tests('POST', undef, $patron);
126
127     $schema->storage->txn_rollback;
128
129     subtest 'librarian access tests' => sub {
130         plan tests => 21;
131
132         $schema->storage->txn_begin;
133
134         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
135         my $newpatron = $patron->to_api;
136         # delete RO attributes
137         delete $newpatron->{patron_id};
138         delete $newpatron->{restricted};
139         delete $newpatron->{anonymized};
140
141         # Create a library just to make sure its ID doesn't exist on the DB
142         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
143         my $deleted_library_id = $library_to_delete->id;
144         # Delete library
145         $library_to_delete->delete;
146
147         my $librarian = $builder->build_object(
148             {
149                 class => 'Koha::Patrons',
150                 value => { flags => 2**4 }    # borrowers flag = 4
151             }
152         );
153         my $password = 'thePassword123';
154         $librarian->set_password( { password => $password, skip_validation => 1 } );
155         my $userid = $librarian->userid;
156
157         $newpatron->{library_id} = $deleted_library_id;
158
159         warning_like {
160             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
161               ->status_is(409)
162               ->json_is('/error' => "Duplicate ID"); }
163             qr/DBD::mysql::st execute failed: Duplicate entry/;
164
165         $newpatron->{library_id} = $patron->branchcode;
166
167         # Create a library just to make sure its ID doesn't exist on the DB
168         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
169         my $deleted_category_id = $category_to_delete->id;
170         # Delete library
171         $category_to_delete->delete;
172
173         $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category
174
175         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
176           ->status_is(400)
177           ->json_is('/error' => "Given category_id does not exist");
178         $newpatron->{category_id} = $patron->categorycode;
179
180         $newpatron->{falseproperty} = "Non existent property";
181
182         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
183           ->status_is(400);
184
185         delete $newpatron->{falseproperty};
186
187         my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
188         $newpatron = $patron_to_delete->to_api;
189         # delete RO attributes
190         delete $newpatron->{patron_id};
191         delete $newpatron->{restricted};
192         delete $newpatron->{anonymized};
193         $patron_to_delete->delete;
194
195         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
196           ->status_is(201, 'Patron created successfully')
197           ->header_like(
198             Location => qr|^\/api\/v1\/patrons/\d*|,
199             'SWAGGER3.4.1'
200           )
201           ->json_has('/patron_id', 'got a patron_id')
202           ->json_is( '/cardnumber' => $newpatron->{ cardnumber })
203           ->json_is( '/surname'    => $newpatron->{ surname })
204           ->json_is( '/firstname'  => $newpatron->{ firstname });
205
206         warning_like {
207             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
208               ->status_is(409)
209               ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' )
210               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
211             qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
212
213         $schema->storage->txn_rollback;
214     };
215 };
216
217 subtest 'update() tests' => sub {
218     plan tests => 2;
219
220     $schema->storage->txn_begin;
221     unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'});
222     $schema->storage->txn_rollback;
223
224     subtest 'librarian access tests' => sub {
225         plan tests => 22;
226
227         $schema->storage->txn_begin;
228
229         my $authorized_patron = $builder->build_object(
230             {
231                 class => 'Koha::Patrons',
232                 value => { flags => 2**4 } # borrowers flag = 4
233             }
234         );
235         my $password = 'thePassword123';
236         $authorized_patron->set_password(
237             { password => $password, skip_validation => 1 } );
238         my $userid = $authorized_patron->userid;
239
240         my $unauthorized_patron = $builder->build_object(
241             {
242                 class => 'Koha::Patrons',
243                 value => { flags => 0 }
244             }
245         );
246         $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } );
247         my $unauth_userid = $unauthorized_patron->userid;
248
249         my $patron_1  = $authorized_patron;
250         my $patron_2  = $unauthorized_patron;
251         my $newpatron = $unauthorized_patron->to_api;
252         # delete RO attributes
253         delete $newpatron->{patron_id};
254         delete $newpatron->{restricted};
255         delete $newpatron->{anonymized};
256
257         $t->put_ok("//$userid:$password@/api/v1/patrons/-1" => json => $newpatron)
258           ->status_is(404)
259           ->json_has('/error', 'Fails when trying to PUT nonexistent patron');
260
261         # Create a library just to make sure its ID doesn't exist on the DB
262         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
263         my $deleted_category_id = $category_to_delete->id;
264         # Delete library
265         $category_to_delete->delete;
266
267         # Use an invalid category
268         $newpatron->{category_id} = $deleted_category_id;
269
270         $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
271           ->status_is(400)
272           ->json_is('/error' => "Given category_id does not exist");
273
274         # Restore the valid category
275         $newpatron->{category_id} = $patron_2->categorycode;
276
277         # Create a library just to make sure its ID doesn't exist on the DB
278         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
279         my $deleted_library_id = $library_to_delete->id;
280         # Delete library
281         $library_to_delete->delete;
282
283         # Use an invalid library_id
284         $newpatron->{library_id} = $deleted_library_id;
285
286         warning_like {
287             $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
288               ->status_is(400)
289               ->json_is('/error' => "Given library_id does not exist"); }
290             qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
291
292         # Restore the valid library_id
293         $newpatron->{library_id} = $patron_2->branchcode;
294
295         # Use an invalid attribute
296         $newpatron->{falseproperty} = "Non existent property";
297
298         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
299           ->status_is(400)
300           ->json_is('/errors/0/message' =>
301                     'Properties not allowed: falseproperty.');
302
303         # Get rid of the invalid attribute
304         delete $newpatron->{falseproperty};
305
306         # Set both cardnumber and userid to already existing values
307         $newpatron->{cardnumber} = $patron_1->cardnumber;
308         $newpatron->{userid}     = $patron_1->userid;
309
310         warning_like {
311             $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
312               ->status_is(409)
313               ->json_has( '/error', "Fails when trying to update to an existing cardnumber or userid")
314               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
315             qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
316
317         $newpatron->{ cardnumber } = $patron_1->id . $patron_2->id;
318         $newpatron->{ userid }     = "user" . $patron_1->id.$patron_2->id;
319         $newpatron->{ surname }    = "user" . $patron_1->id.$patron_2->id;
320
321         my $result = $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
322           ->status_is(200, 'Patron updated successfully');
323
324         # Put back the RO attributes
325         $newpatron->{patron_id} = $unauthorized_patron->to_api->{patron_id};
326         $newpatron->{restricted} = $unauthorized_patron->to_api->{restricted};
327         $newpatron->{anonymized} = $unauthorized_patron->to_api->{anonymized};
328         is_deeply($result->tx->res->json, $newpatron, 'Returned patron from update matches expected');
329
330         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
331            $newpatron->{ cardnumber }, 'Patron is really updated!');
332
333         $schema->storage->txn_rollback;
334     };
335 };
336
337 subtest 'delete() tests' => sub {
338     plan tests => 2;
339
340     $schema->storage->txn_begin;
341     unauthorized_access_tests('DELETE', 123, undef);
342     $schema->storage->txn_rollback;
343
344     subtest 'librarian access test' => sub {
345         plan tests => 5;
346
347         $schema->storage->txn_begin;
348
349         my $authorized_patron = $builder->build_object(
350             {
351                 class => 'Koha::Patrons',
352                 value => { flags => 2**4 }    # borrowers flag = 4
353             }
354         );
355         my $password = 'thePassword123';
356         $authorized_patron->set_password(
357             { password => $password, skip_validation => 1 } );
358         my $userid = $authorized_patron->userid;
359
360         $t->delete_ok("//$userid:$password@/api/v1/patrons/-1")
361           ->status_is(404, 'Patron not found');
362
363         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
364
365         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
366           ->status_is(204, 'SWAGGER3.2.4')
367           ->content_is('', 'SWAGGER3.3.4');
368
369         $schema->storage->txn_rollback;
370     };
371 };
372
373 subtest 'guarantors_can_see_charges() tests' => sub {
374
375     plan tests => 11;
376
377     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
378     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
379
380     $schema->storage->txn_begin;
381
382     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } });
383     my $password = 'thePassword123';
384     $patron->set_password({ password => $password, skip_validation => 1 });
385     my $userid = $patron->userid;
386     my $patron_id = $patron->borrowernumber;
387
388     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 0 );
389
390     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
391       ->status_is( 403 )
392       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
393
394     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 1 );
395
396     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
397       ->status_is( 200 )
398       ->json_is( {} );
399
400     ok( $patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
401
402     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->false } )
403       ->status_is( 200 )
404       ->json_is( {} );
405
406     ok( !$patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
407
408     $schema->storage->txn_rollback;
409 };
410
411 subtest 'guarantors_can_see_checkouts() tests' => sub {
412
413     plan tests => 11;
414
415     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
416     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
417
418     $schema->storage->txn_begin;
419
420     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } });
421     my $password = 'thePassword123';
422     $patron->set_password({ password => $password, skip_validation => 1 });
423     my $userid = $patron->userid;
424     my $patron_id = $patron->borrowernumber;
425
426     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 0 );
427
428     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
429       ->status_is( 403 )
430       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
431
432     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 1 );
433
434     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
435       ->status_is( 200 )
436       ->json_is( {} );
437
438     ok( $patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
439
440     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->false } )
441       ->status_is( 200 )
442       ->json_is( {} );
443
444     ok( !$patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
445
446     $schema->storage->txn_rollback;
447 };
448
449 # Centralized tests for 401s and 403s assuming the endpoint requires
450 # borrowers flag for access
451 sub unauthorized_access_tests {
452     my ($verb, $patron_id, $json) = @_;
453
454     my $endpoint = '/api/v1/patrons';
455     $endpoint .= ($patron_id) ? "/$patron_id" : '';
456
457     subtest 'unauthorized access tests' => sub {
458         plan tests => 5;
459
460         my $verb_ok = lc($verb) . '_ok';
461
462         $t->$verb_ok($endpoint => json => $json)
463           ->status_is(401);
464
465         my $unauthorized_patron = $builder->build_object(
466             {
467                 class => 'Koha::Patrons',
468                 value => { flags => 0 }
469             }
470         );
471         my $password = "thePassword123!";
472         $unauthorized_patron->set_password(
473             { password => $password, skip_validation => 1 } );
474         my $unauth_userid = $unauthorized_patron->userid;
475
476         $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )
477           ->status_is(403)
478           ->json_has('/required_permissions');
479     };
480 }