Bug 36687: (RM follow-up) Fix unit tests
[koha.git] / t / db_dependent / api / v1 / items.t
1 #!/usr/bin/env perl
2
3 # Copyright 2016 Koha-Suomi
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 5;
23 use Test::MockModule;
24 use Test::Mojo;
25 use Test::Warn;
26
27 use t::lib::TestBuilder;
28 use t::lib::Mocks;
29
30 use Mojo::JSON qw(encode_json);
31
32 use C4::Auth;
33 use Koha::Items;
34 use Koha::Database;
35
36 my $schema  = Koha::Database->new->schema;
37 my $builder = t::lib::TestBuilder->new;
38
39 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
40
41 my $t = Test::Mojo->new('Koha::REST::V1');
42
43 subtest 'list() tests' => sub {
44
45     plan tests => 15;
46
47     $schema->storage->txn_begin;
48
49     my $item   = $builder->build_sample_item;
50     my $patron = $builder->build_object(
51         {
52             class => 'Koha::Patrons',
53             value => { flags => 4 }
54         }
55     );
56
57     # Make sure we have at least 10 items
58     for ( 1..10 ) {
59         $builder->build_sample_item;
60     }
61
62     my $nonprivilegedpatron = $builder->build_object(
63         {
64             class => 'Koha::Patrons',
65             value => { flags => 0 }
66         }
67     );
68
69     my $password = 'thePassword123';
70
71     $nonprivilegedpatron->set_password(
72         { password => $password, skip_validation => 1 } );
73     my $userid = $nonprivilegedpatron->userid;
74
75     $t->get_ok( "//$userid:$password@/api/v1/items" )
76       ->status_is(403)
77       ->json_is(
78         '/error' => 'Authorization failure. Missing required permission(s).' );
79
80     $patron->set_password( { password => $password, skip_validation => 1 } );
81     $userid = $patron->userid;
82
83     $t->get_ok( "//$userid:$password@/api/v1/items?_per_page=10" )
84       ->status_is( 200, 'SWAGGER3.2.2' );
85
86     my $response_count = scalar @{ $t->tx->res->json };
87
88     is( $response_count, 10, 'The API returns 10 items' );
89
90     $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )
91       ->status_is(200)
92       ->json_is( '' => [ $item->to_api ], 'SWAGGER3.3.2');
93
94     $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode => {'x-koha-embed' => 'biblio'} )
95       ->status_is(200)
96       ->json_is( '' => [ { %{$item->to_api}, biblio => $item->biblio->to_api } ], 'SWAGGER3.3.2');
97
98
99     my $barcode = $item->barcode;
100     $item->delete;
101
102     $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )
103       ->status_is(200)
104       ->json_is( '' => [] );
105
106     $schema->storage->txn_rollback;
107 };
108
109 subtest 'list_public() tests' => sub {
110
111     plan tests => 2;
112
113     $schema->storage->txn_begin;
114
115     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
116
117     my $exception = 1;
118
119     my $mocked_category = Test::MockModule->new('Koha::Patron::Category');
120     $mocked_category->mock(
121         'override_hidden_items',
122         sub {
123             return $exception;
124         }
125     );
126
127     my $password = 'thePassword123';
128     $patron->set_password( { password => $password, skip_validation => 1 } );
129     my $userid = $patron->userid;
130
131     # have a fresh biblio
132     my $biblio = $builder->build_sample_biblio;
133     # have two itemtypes
134     my $itype_1 = $builder->build_object({ class => 'Koha::ItemTypes' });
135     my $itype_2 = $builder->build_object({ class => 'Koha::ItemTypes' });
136     # have 5 items on that biblio
137     my $item_1 = $builder->build_sample_item(
138         {
139             biblionumber => $biblio->biblionumber,
140             itemlost     => -1,
141             itype        => $itype_1->itemtype,
142             withdrawn    => 1,
143             copynumber   => undef
144         }
145     );
146     my $item_2 = $builder->build_sample_item(
147         {
148             biblionumber => $biblio->biblionumber,
149             itemlost     => 0,
150             itype        => $itype_2->itemtype,
151             withdrawn    => 2,
152             copynumber   => undef
153         }
154     );
155     my $item_3 = $builder->build_sample_item(
156         {
157             biblionumber => $biblio->biblionumber,
158             itemlost     => 1,
159             itype        => $itype_1->itemtype,
160             withdrawn    => 3,
161             copynumber   => undef
162         }
163     );
164     my $item_4 = $builder->build_sample_item(
165         {
166             biblionumber => $biblio->biblionumber,
167             itemlost     => 0,
168             itype        => $itype_2->itemtype,
169             withdrawn    => 4,
170             copynumber   => undef
171         }
172     );
173     my $item_5 = $builder->build_sample_item(
174         {
175             biblionumber => $biblio->biblionumber,
176             itemlost     => 0,
177             itype        => $itype_1->itemtype,
178             withdrawn    => 5,
179             copynumber   => undef
180         }
181     );
182     my $item_6 = $builder->build_sample_item(
183         {
184             biblionumber => $biblio->biblionumber,
185             itemlost     => 2,
186             itype        => $itype_1->itemtype,
187             withdrawn    => 5,
188             copynumber   => undef
189         }
190     );
191
192     my $rules = undef;
193     my $mocked_context = Test::MockModule->new('C4::Context');
194     $mocked_context->mock( 'yaml_preference', sub {
195         return $rules;
196     });
197
198     my $query = encode_json({ item_id => [ $item_1->id, $item_2->id, $item_3->id, $item_4->id, $item_5->id, $item_6->id ] });
199
200     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
201     subtest 'anonymous access' => sub {
202         plan tests => 21;
203
204         t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 );
205
206         t::lib::Mocks::mock_preference( 'hidelostitems', 0 );
207         my $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json;
208         is( scalar @{ $res }, 6, 'No rules set, hidelostitems unset, all items returned');
209
210         t::lib::Mocks::mock_preference( 'hidelostitems', 1 );
211         $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json;
212         is( scalar @{ $res }, 3, 'No rules set, hidelostitems set, 3 items hidden');
213
214         t::lib::Mocks::mock_preference( 'hidelostitems', 0 );
215         $rules = { biblionumber => [ $biblio->biblionumber ] };
216         $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json;
217         is( scalar @{ $res }, 0, 'Biblionumber rule set, hidelostitems unset, all items hidden');
218
219         $rules = { withdrawn => [ 1, 2 ] };
220         $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json;
221         is( scalar @{ $res }, 4, 'Withdrawn rule set, hidelostitems unset, 2 items hidden');
222
223         $rules = { itype => [ $itype_1->itemtype ] };
224         $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json;
225         is( scalar @{ $res }, 2, 'Itype rule set, hidelostitems unset, 4 items hidden');
226
227         $rules = { withdrawn => [ 1 ] };
228         $res = $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode )
229           ->status_is(200)->tx->res->json;
230         is( scalar @{ $res }, 0, 'Withdrawn rule set, hidelostitems unset, search on barcode returns no item');
231
232         $rules = undef;
233         $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode )
234           ->status_is(200)->json_is(
235             '/0' => $item_1->to_api( { public => 1 } ),
236 'No rules set, hidelostitems unset, public form of item returned on barcode search'
237           );
238     };
239
240     subtest 'logged in user access' => sub {
241         plan tests => 3;
242
243         t::lib::Mocks::mock_preference( 'hidelostitems', 1 );
244         $rules = { withdrawn => [ 1, 2 ] };
245         my $res = $t->get_ok("//$userid:$password@/api/v1/public/items?q=" . $query)
246           ->status_is(200)->tx->res->json;
247         is(
248             scalar @{$res},
249             3,
250 'Rules on withdrawn but patron with override passed, hidelostitems set'
251         );
252     };
253
254     $schema->storage->txn_rollback;
255 };
256
257 subtest 'get() tests' => sub {
258
259     plan tests => 34;
260
261     $schema->storage->txn_begin;
262
263     my $item = $builder->build_sample_item;
264     my $patron = $builder->build_object({
265         class => 'Koha::Patrons',
266         value => { flags => 4 }
267     });
268
269     my $nonprivilegedpatron = $builder->build_object({
270         class => 'Koha::Patrons',
271         value => { flags => 0 }
272     });
273
274     my $password = 'thePassword123';
275
276     $nonprivilegedpatron->set_password({ password => $password, skip_validation => 1 });
277     my $userid = $nonprivilegedpatron->userid;
278
279     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
280       ->status_is(403)
281       ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' );
282
283     $patron->set_password({ password => $password, skip_validation => 1 });
284     $userid = $patron->userid;
285
286     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
287       ->status_is( 200, 'SWAGGER3.2.2' )
288       ->json_is( '' => $item->to_api, 'SWAGGER3.3.2' );
289
290     my $non_existent_code = $item->itemnumber;
291     $item->delete;
292
293     $t->get_ok( "//$userid:$password@/api/v1/items/" . $non_existent_code )
294       ->status_is(404)
295       ->json_is( '/error' => 'Item not found' );
296
297     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
298
299     my $biblio = $builder->build_sample_biblio;
300     my $itype =
301       $builder->build_object( { class => 'Koha::ItemTypes' } );
302     $item = $builder->build_sample_item(
303         { biblionumber => $biblio->biblionumber, itype => $itype->itemtype } );
304
305     isnt( $biblio->itemtype, $itype->itemtype, "Test biblio level itemtype and item level itemtype do not match");
306
307     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
308       ->status_is( 200, 'SWAGGER3.2.2' )
309       ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itypes:0' )
310       ->json_is( '/effective_item_type_id' => $biblio->itemtype, 'item-level_itypes:0' );
311
312     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
313
314     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
315       ->status_is( 200, 'SWAGGER3.2.2' )
316       ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itype:1' )
317       ->json_is( '/effective_item_type_id' => $itype->itemtype, 'item-level_itypes:1' );
318
319
320     my $biblio_itype = Koha::ItemTypes->find($biblio->itemtype);
321     $biblio_itype->notforloan(3)->store();
322     $itype->notforloan(2)->store();
323     $item->notforloan(1)->store();
324
325     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
326       ->status_is( 200, 'SWAGGER3.2.2' )
327       ->json_is( '/not_for_loan_status' => 1, 'not_for_loan_status is 1' )
328       ->json_is( '/effective_not_for_loan_status' => 1, 'effective_not_for_loan_status picks up item level' );
329
330     $item->notforloan(0)->store();
331     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
332       ->status_is( 200, 'SWAGGER3.2.2' )
333       ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )
334       ->json_is( '/effective_not_for_loan_status' => 2, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:1' );
335
336     $itype->notforloan(0)->store();
337     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'SWAGGER3.2.2' )
338         ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )->json_is(
339         '/effective_not_for_loan_status' => 0,
340         'effective_not_for_loan_status now picks up itemtype level and falls back to 0 because undef'
341         );
342
343     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
344     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
345       ->status_is( 200, 'SWAGGER3.2.2' )
346       ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )
347       ->json_is( '/effective_not_for_loan_status' => 3, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:0' );
348
349     $schema->storage->txn_rollback;
350 };
351
352 subtest 'delete() tests' => sub {
353
354     plan tests => 23;
355
356     $schema->storage->txn_begin;
357
358     my $fail = 0;
359     my $expected_error;
360
361     # we want to control all the safe_to_delete use cases
362     my $item_class = Test::MockModule->new('Koha::Item');
363     $item_class->mock( 'safe_to_delete', sub {
364         if ( $fail ) {
365             return Koha::Result::Boolean->new(0)->add_message({ message => $expected_error });
366         }
367         else {
368             return Koha::Result::Boolean->new(1);
369         }
370     });
371
372     my $librarian = $builder->build_object(
373         {
374             class => 'Koha::Patrons',
375             value => { flags => 2**9 }    # catalogue flag = 2
376         }
377     );
378     my $password = 'thePassword123';
379     $librarian->set_password( { password => $password, skip_validation => 1 } );
380     my $userid = $librarian->userid;
381
382     my $item = $builder->build_sample_item;
383
384     my $errors = {
385         book_on_loan       => { code => 'checked_out',        description => 'The item is checked out' },
386         book_reserved      => { code => 'found_hold',         description => 'Waiting or in-transit hold for the item' },
387         last_item_for_hold => { code => 'last_item_for_hold', description => 'The item is the last one on a record on which a biblio-level hold is placed' },
388         linked_analytics   => { code => 'linked_analytics',   description => 'The item has linked analytic records' },
389         not_same_branch    => { code => 'not_same_branch',    description => 'The item is blocked by independent branches' },
390     };
391
392     $fail = 1;
393
394     foreach my $error_code ( keys %{$errors} ) {
395
396         $expected_error = $error_code;
397
398         $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )
399           ->status_is(409)
400           ->json_is(
401             { error      => $errors->{$error_code}->{description},
402               error_code => $errors->{$error_code}->{code},
403             }
404         );
405     }
406
407     $expected_error = 'unknown_error';
408     $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )
409       ->status_is(500, 'unhandled error case generated default unhandled exception message')
410       ->json_is(
411         { error      => 'Something went wrong, check Koha logs for details.',
412           error_code => 'internal_server_error',
413         }
414     );
415
416     $fail = 0;
417
418     $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id)
419       ->status_is(204, 'SWAGGER3.2.4')
420       ->content_is('', 'SWAGGER3.3.4');
421
422     $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id)
423       ->status_is(404);
424
425     $schema->storage->txn_rollback;
426 };
427
428 subtest 'pickup_locations() tests' => sub {
429
430     plan tests => 16;
431
432     $schema->storage->txn_begin;
433
434     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
435
436     # Small trick to ease testing
437     Koha::Libraries->search->update({ pickup_location => 0 });
438
439     my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } });
440     my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } });
441     my $library_3 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } });
442
443     my $library_1_api = $library_1->to_api();
444     my $library_2_api = $library_2->to_api();
445     my $library_3_api = $library_3->to_api();
446
447     $library_1_api->{needs_override} = Mojo::JSON->false;
448     $library_2_api->{needs_override} = Mojo::JSON->false;
449     $library_3_api->{needs_override} = Mojo::JSON->true;
450
451     my $patron = $builder->build_object(
452         {
453             class => 'Koha::Patrons',
454             value => { userid => 'tomasito', flags => 0 }
455         }
456     );
457     my $password = 'thePassword123';
458     $patron->set_password( { password => $password, skip_validation => 1 } );
459     my $userid = $patron->userid;
460     $builder->build(
461         {
462             source => 'UserPermission',
463             value  => {
464                 borrowernumber => $patron->borrowernumber,
465                 module_bit     => 6,
466                 code           => 'place_holds',
467             },
468         }
469     );
470
471     my $item = $builder->build_sample_item();
472
473     my $item_class = Test::MockModule->new('Koha::Item');
474     $item_class->mock(
475         'pickup_locations',
476         sub {
477             my ( $self, $params ) = @_;
478             my $mock_patron = $params->{patron};
479             is( $mock_patron->borrowernumber,
480                 $patron->borrowernumber, 'Patron passed correctly' );
481             return Koha::Libraries->search(
482                 {
483                     branchcode => {
484                         '-in' => [
485                             $library_1->branchcode,
486                             $library_2->branchcode
487                         ]
488                     }
489                 },
490                 {   # we make sure no surprises in the order of the result
491                     order_by => { '-asc' => 'marcorgcode' }
492                 }
493             );
494         }
495     );
496
497     $t->get_ok( "//$userid:$password@/api/v1/items/"
498           . $item->id
499           . "/pickup_locations?patron_id=" . $patron->id )
500       ->json_is( [ $library_1_api, $library_2_api ] );
501
502     # filtering works!
503     $t->get_ok( "//$userid:$password@/api/v1/items/"
504           . $item->id
505           . '/pickup_locations?'
506           . 'patron_id=' . $patron->id . '&q={"marc_org_code": { "-like": "A%" }}' )
507       ->json_is( [ $library_1_api ] );
508
509     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
510
511     my $library_4 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } });
512     my $library_5 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } });
513
514     my $library_5_api = $library_5->to_api();
515     $library_5_api->{needs_override} = Mojo::JSON->true;
516
517     $t->get_ok( "//$userid:$password@/api/v1/items/"
518           . $item->id
519           . "/pickup_locations?"
520           . "patron_id=" . $patron->id . "&_order_by=marc_org_code" )
521       ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] );
522
523     subtest 'Pagination and AllowHoldPolicyOverride tests' => sub {
524
525         plan tests => 27;
526
527         t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
528
529         $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" )
530           ->json_is( [$library_1_api] )
531           ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
532           ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
533           ->header_unlike( 'Link', qr|rel="prev"| )
534           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# )
535           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
536           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# );
537
538         $t->get_ok( "//$userid:$password@/api/v1/items/"
539               . $item->id
540               . "/pickup_locations?"
541               . "patron_id="
542               . $patron->id
543               . "&_order_by=marc_org_code"
544               . "&_per_page=1&_page=3" )    # force the needs_override=1 check
545           ->json_is( [$library_3_api] )
546           ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
547           ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
548           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# )
549           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# )
550           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
551           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# );
552
553         t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
554
555         $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" )
556           ->json_is( [$library_1_api] )
557           ->header_is( 'X-Total-Count', '2' )
558           ->header_is( 'X-Base-Total-Count', '2' )
559           ->header_unlike( 'Link', qr|rel="prev"| )
560           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# )
561           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
562           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# );
563     };
564
565     my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' });
566     my $deleted_patron_id = $deleted_patron->id;
567     $deleted_patron->delete;
568
569     $t->get_ok( "//$userid:$password@/api/v1/items/"
570           . $item->id
571           . "/pickup_locations?"
572           . "patron_id=" . $deleted_patron_id )
573       ->status_is( 400 )
574       ->json_is( '/error' => 'Patron not found' );
575
576     $item->delete;
577
578     $t->get_ok( "//$userid:$password@/api/v1/items/"
579           . $item->id
580           . "/pickup_locations?"
581           . "patron_id=" . $patron->id )
582       ->status_is( 404 )
583       ->json_is( '/error' => 'Item not found' );
584
585     $schema->storage->txn_rollback;
586 };