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