Bug 36482: Add embed tests
[koha.git] / t / db_dependent / api / v1 / libraries.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 List::Util qw(min);
28
29 use Koha::Libraries;
30 use Koha::Database;
31
32 my $schema  = Koha::Database->new->schema;
33 my $builder = t::lib::TestBuilder->new;
34
35 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
36
37 my $t = Test::Mojo->new('Koha::REST::V1');
38
39 subtest 'list() tests' => sub {
40     plan tests => 7;
41
42     $schema->storage->txn_begin;
43
44     my $patron = $builder->build_object({
45         class => 'Koha::Patrons',
46         value => { flags => 4 }
47     });
48     my $password = 'thePassword123';
49     $patron->set_password({ password => $password, skip_validation => 1 });
50     my $userid = $patron->userid;
51
52     # Create test context
53     my $library = $builder->build_object({ class => 'Koha::Libraries' });
54     my $another_library = $library->unblessed; # create a copy of $library but make
55     delete $another_library->{branchcode};     # sure branchcode will be regenerated
56     $another_library = $builder->build_object({ class => 'Koha::Libraries', value => $another_library });
57
58     ## Authorized user tests
59     # Make sure we are returned with the correct amount of libraries
60     $t->get_ok( "//$userid:$password@/api/v1/libraries" )
61       ->status_is( 200, 'SWAGGER3.2.2' );
62
63     my $response_count = scalar @{ $t->tx->res->json };
64     my $expected_count = min( Koha::Libraries->count, C4::Context->preference('RESTdefaultPageSize') );
65     is( $response_count, $expected_count, 'Results count is paginated');
66
67     subtest 'query parameters' => sub {
68
69         my $fields = {
70             name              => 'branchname',
71             address1          => 'branchaddress1',
72             address2          => 'branchaddress2',
73             address3          => 'branchaddress3',
74             postal_code       => 'branchzip',
75             city              => 'branchcity',
76             state             => 'branchstate',
77             country           => 'branchcountry',
78             phone             => 'branchphone',
79             fax               => 'branchfax',
80             email             => 'branchemail',
81             reply_to_email    => 'branchreplyto',
82             return_path_email => 'branchreturnpath',
83             url               => 'branchurl',
84             ip                => 'branchip',
85             notes             => 'branchnotes',
86         };
87
88         my $size = keys %{$fields};
89
90         plan tests => $size * (2 + 2 * $size);
91
92         foreach my $field ( keys %{$fields} ) {
93             my $model_field = $fields->{ $field };
94             my $result = $t->get_ok("//$userid:$password@/api/v1/libraries?$field=" . $library->$model_field)
95               ->status_is(200);
96             foreach my $key ( keys %{$fields} ) {
97               my $key_field = $fields->{ $key };
98               $result->json_is( "/0/$key", $library->$key_field );
99               $result->json_is( "/1/$key", $another_library->$key_field );
100             }
101         }
102     };
103
104     # Warn on unsupported query parameter
105     $t->get_ok( "//$userid:$password@/api/v1/libraries?library_blah=blah" )
106       ->status_is(400)
107       ->json_is( [{ path => '/query/library_blah', message => 'Malformed query string'}] );
108
109     $schema->storage->txn_rollback;
110 };
111
112 subtest 'get() tests' => sub {
113
114     plan tests => 12;
115
116     $schema->storage->txn_begin;
117
118     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
119     my $patron = $builder->build_object({
120         class => 'Koha::Patrons',
121         value => { flags => 4 }
122     });
123     my $password = 'thePassword123';
124     $patron->set_password({ password => $password, skip_validation => 1 });
125     my $userid = $patron->userid;
126
127     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode )
128       ->status_is( 200, 'SWAGGER3.2.2' )
129       ->json_is( '' => $library->to_api, 'SWAGGER3.3.2' );
130
131     $t->get_ok( "//$userid:$password@/api/v1/libraries/"
132             . $library->branchcode => { 'x-koha-embed' => 'cash_registers,desks' } )->status_is(200)
133         ->json_is( { %{ $library->to_api }, desks => [], cash_registers => [] } );
134
135     my $desk = $builder->build_object( { class => 'Koha::Desks', value => { branchcode => $library->id } } );
136     my $cash_register =
137         $builder->build_object( { class => 'Koha::Cash::Registers', value => { branch => $library->id } } );
138
139     $t->get_ok( "//$userid:$password@/api/v1/libraries/"
140             . $library->branchcode => { 'x-koha-embed' => 'cash_registers,desks' } )->status_is(200)
141         ->json_is(
142         { %{ $library->to_api }, desks => [ $desk->to_api ], cash_registers => [ $cash_register->to_api ] } );
143
144     my $non_existent_code = $library->branchcode;
145     $library->delete;
146
147     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code )
148       ->status_is(404)
149       ->json_is( '/error' => 'Library not found' );
150
151     $schema->storage->txn_rollback;
152 };
153
154 subtest 'add() tests' => sub {
155
156     plan tests => 17;
157
158     $schema->storage->txn_begin;
159
160     my $authorized_patron = $builder->build_object({
161         class => 'Koha::Patrons',
162         value => { flags => 1 }
163     });
164     my $password = 'thePassword123';
165     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
166     my $auth_userid = $authorized_patron->userid;
167
168     my $unauthorized_patron = $builder->build_object({
169         class => 'Koha::Patrons',
170         value => { flags => 4 }
171     });
172     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
173     my $unauth_userid = $unauthorized_patron->userid;
174
175     my $library_obj = $builder->build_object({ class => 'Koha::Libraries' });
176     my $library     = $library_obj->to_api;
177     $library_obj->delete;
178
179     # Unauthorized attempt to write
180     $t->post_ok( "//$unauth_userid:$password@/api/v1/libraries" => json => $library )
181       ->status_is(403);
182
183     # Authorized attempt to write invalid data
184     my $library_with_invalid_field = { %$library };
185     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
186
187     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library_with_invalid_field )
188       ->status_is(400)
189       ->json_is(
190         "/errors" => [
191             {
192                 message => "Properties not allowed: branchinvalid.",
193                 path    => "/body"
194             }
195         ]
196     );
197
198     # Authorized attempt to write
199     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
200       ->status_is( 201, 'SWAGGER3.2.1' )
201       ->json_is( '' => $library, 'SWAGGER3.3.1' )
202       ->header_is( Location => '/api/v1/libraries/' . $library->{library_id}, 'SWAGGER3.4.1' );
203
204     # save the library_id
205     my $library_id = $library->{library_id};
206     # Authorized attempt to create with null id
207     $library->{library_id} = undef;
208
209     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
210       ->status_is(400)
211       ->json_has('/errors');
212
213     # Authorized attempt to create with existing id
214     $library->{library_id} = $library_id;
215
216     warning_like {
217         $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
218           ->status_is(409)
219           ->json_has( '/error' => "Fails when trying to add an existing library_id")
220           ->json_like( '/conflict' => qr/(branches\.)?PRIMARY/ ); }
221         qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(branches\.)?PRIMARY'/;
222
223     $schema->storage->txn_rollback;
224 };
225
226 subtest 'update() tests' => sub {
227     plan tests => 13;
228
229     $schema->storage->txn_begin;
230
231     my $authorized_patron = $builder->build_object({
232         class => 'Koha::Patrons',
233         value => { flags => 1 }
234     });
235     my $password = 'thePassword123';
236     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
237     my $auth_userid = $authorized_patron->userid;
238
239     my $unauthorized_patron = $builder->build_object({
240         class => 'Koha::Patrons',
241         value => { flags => 4 }
242     });
243     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
244     my $unauth_userid = $unauthorized_patron->userid;
245
246     my $library    = $builder->build_object({ class => 'Koha::Libraries' });
247     my $library_id = $library->branchcode;
248
249     # Unauthorized attempt to update
250     $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id"
251                     => json => { name => 'New unauthorized name change' } )
252       ->status_is(403);
253
254     # Attempt partial update on a PUT
255     my $library_with_missing_field = {
256         address1 => "New library address",
257     };
258
259     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field )
260       ->status_is(400)
261       ->json_has( "/errors" =>
262           [ { message => "Missing property.", path => "/body/address2" } ]
263       );
264
265     my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } );
266     my $library_with_updated_field = $deleted_library->to_api;
267     $library_with_updated_field->{library_id} = $library_id;
268     $deleted_library->delete;
269
270     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field )
271       ->status_is(200, 'SWAGGER3.2.1')
272       ->json_is( '' => $library_with_updated_field, 'SWAGGER3.3.3' );
273
274     # Authorized attempt to write invalid data
275     my $library_with_invalid_field = { %$library_with_updated_field };
276     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
277
278     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field )
279       ->status_is(400)
280       ->json_is(
281         "/errors" => [
282             {
283                 message => "Properties not allowed: branchinvalid.",
284                 path    => "/body"
285             }
286         ]
287     );
288
289     my $non_existent_code = 'nope'.int(rand(10000));
290     $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field)
291       ->status_is(404);
292
293     $schema->storage->txn_rollback;
294 };
295
296 subtest 'delete() tests' => sub {
297     plan tests => 7;
298
299     $schema->storage->txn_begin;
300
301     my $authorized_patron = $builder->build_object({
302         class => 'Koha::Patrons',
303         value => { flags => 1 }
304     });
305     my $password = 'thePassword123';
306     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
307     my $auth_userid = $authorized_patron->userid;
308
309     my $unauthorized_patron = $builder->build_object({
310         class => 'Koha::Patrons',
311         value => { flags => 4 }
312     });
313     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
314     my $unauth_userid = $unauthorized_patron->userid;
315
316     my $library_id = $builder->build( { source => 'Branch' } )->{branchcode};
317
318     # Unauthorized attempt to delete
319     $t->delete_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" )
320       ->status_is(403);
321
322     $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" )
323       ->status_is(204, 'SWAGGER3.2.4')
324       ->content_is('', 'SWAGGER3.3.4');
325
326     $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" )
327       ->status_is(404);
328
329     $schema->storage->txn_rollback;
330 };
331
332 subtest 'list_desks() tests' => sub {
333
334     plan tests => 11;
335
336     $schema->storage->txn_begin;
337
338     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
339     my $patron  = $builder->build_object(
340         {
341             class => 'Koha::Patrons',
342             value => { flags => 4 }
343         }
344     );
345     my $password = 'thePassword123';
346     $patron->set_password( { password => $password, skip_validation => 1 } );
347     my $userid = $patron->userid;
348
349     t::lib::Mocks::mock_preference( 'UseCirculationDesks', 0 );
350
351     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode . "/desks" )->status_is(404)
352         ->json_is( '/error' => q{Feature disabled} );
353
354     my $non_existent_code = $library->branchcode;
355     $library->delete;
356
357     t::lib::Mocks::mock_preference( 'UseCirculationDesks', 1 );
358
359     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code . "/desks" )->status_is(404)
360         ->json_is( '/error' => 'Library not found' );
361
362     my $desk_1 = $builder->build_object( { class => 'Koha::Desks', value => { branchcode => $library->id } } );
363     my $desk_2 = $builder->build_object( { class => 'Koha::Desks', value => { branchcode => $library->id } } );
364
365     my $res = $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode . "/desks" )->status_is(200)
366         ->json_is( '/0/desk_id' => $desk_1->id )->json_is( '/1/desk_id' => $desk_2->id )->tx->res->json;
367
368     is( scalar @{$res}, 2 );
369
370     $schema->storage->txn_rollback;
371 };
372
373 subtest 'list_cash_registers() tests' => sub {
374
375     plan tests => 11;
376
377     $schema->storage->txn_begin;
378
379     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
380     my $patron  = $builder->build_object(
381         {
382             class => 'Koha::Patrons',
383             value => { flags => 4 }
384         }
385     );
386     my $password = 'thePassword123';
387     $patron->set_password( { password => $password, skip_validation => 1 } );
388     my $userid = $patron->userid;
389
390     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
391
392     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode . "/cash_registers" )->status_is(404)
393         ->json_is( '/error' => q{Feature disabled} );
394
395     my $non_existent_code = $library->branchcode;
396     $library->delete;
397
398     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
399
400     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code . "/cash_registers" )->status_is(404)
401         ->json_is( '/error' => 'Library not found' );
402
403     my $cash_register_1 =
404         $builder->build_object( { class => 'Koha::Cash::Registers', value => { branch => $library->id } } );
405     my $cash_register_2 =
406         $builder->build_object( { class => 'Koha::Cash::Registers', value => { branch => $library->id } } );
407
408     my $res =
409         $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode . "/cash_registers" )
410         ->status_is(200)->json_is( '/0/cash_register_id' => $cash_register_1->id )
411         ->json_is( '/1/cash_register_id' => $cash_register_2->id )->tx->res->json;
412
413     is( scalar @{$res}, 2 );
414
415     $schema->storage->txn_rollback;
416 };