Bug 31797: Add DELETE /items/:item_id endpoint
[koha-ffzg.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 => 5;
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 => 6;
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     my $non_existent_code = $library->branchcode;
132     $library->delete;
133
134     $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code )
135       ->status_is(404)
136       ->json_is( '/error' => 'Library not found' );
137
138     $schema->storage->txn_rollback;
139 };
140
141 subtest 'add() tests' => sub {
142
143     plan tests => 17;
144
145     $schema->storage->txn_begin;
146
147     my $authorized_patron = $builder->build_object({
148         class => 'Koha::Patrons',
149         value => { flags => 1 }
150     });
151     my $password = 'thePassword123';
152     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
153     my $auth_userid = $authorized_patron->userid;
154
155     my $unauthorized_patron = $builder->build_object({
156         class => 'Koha::Patrons',
157         value => { flags => 4 }
158     });
159     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
160     my $unauth_userid = $unauthorized_patron->userid;
161
162     my $library_obj = $builder->build_object({ class => 'Koha::Libraries' });
163     my $library     = $library_obj->to_api;
164     $library_obj->delete;
165
166     # Unauthorized attempt to write
167     $t->post_ok( "//$unauth_userid:$password@/api/v1/libraries" => json => $library )
168       ->status_is(403);
169
170     # Authorized attempt to write invalid data
171     my $library_with_invalid_field = { %$library };
172     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
173
174     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library_with_invalid_field )
175       ->status_is(400)
176       ->json_is(
177         "/errors" => [
178             {
179                 message => "Properties not allowed: branchinvalid.",
180                 path    => "/body"
181             }
182         ]
183     );
184
185     # Authorized attempt to write
186     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
187       ->status_is( 201, 'SWAGGER3.2.1' )
188       ->json_is( '' => $library, 'SWAGGER3.3.1' )
189       ->header_is( Location => '/api/v1/libraries/' . $library->{library_id}, 'SWAGGER3.4.1' );
190
191     # save the library_id
192     my $library_id = $library->{library_id};
193     # Authorized attempt to create with null id
194     $library->{library_id} = undef;
195
196     $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
197       ->status_is(400)
198       ->json_has('/errors');
199
200     # Authorized attempt to create with existing id
201     $library->{library_id} = $library_id;
202
203     warning_like {
204         $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )
205           ->status_is(409)
206           ->json_has( '/error' => "Fails when trying to add an existing library_id")
207           ->json_like( '/conflict' => qr/(branches\.)?PRIMARY/ ); }
208         qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(branches\.)?PRIMARY'/;
209
210     $schema->storage->txn_rollback;
211 };
212
213 subtest 'update() tests' => sub {
214     plan tests => 13;
215
216     $schema->storage->txn_begin;
217
218     my $authorized_patron = $builder->build_object({
219         class => 'Koha::Patrons',
220         value => { flags => 1 }
221     });
222     my $password = 'thePassword123';
223     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
224     my $auth_userid = $authorized_patron->userid;
225
226     my $unauthorized_patron = $builder->build_object({
227         class => 'Koha::Patrons',
228         value => { flags => 4 }
229     });
230     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
231     my $unauth_userid = $unauthorized_patron->userid;
232
233     my $library    = $builder->build_object({ class => 'Koha::Libraries' });
234     my $library_id = $library->branchcode;
235
236     # Unauthorized attempt to update
237     $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id"
238                     => json => { name => 'New unauthorized name change' } )
239       ->status_is(403);
240
241     # Attempt partial update on a PUT
242     my $library_with_missing_field = {
243         address1 => "New library address",
244     };
245
246     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field )
247       ->status_is(400)
248       ->json_has( "/errors" =>
249           [ { message => "Missing property.", path => "/body/address2" } ]
250       );
251
252     my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } );
253     my $library_with_updated_field = $deleted_library->to_api;
254     $library_with_updated_field->{library_id} = $library_id;
255     $deleted_library->delete;
256
257     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field )
258       ->status_is(200, 'SWAGGER3.2.1')
259       ->json_is( '' => $library_with_updated_field, 'SWAGGER3.3.3' );
260
261     # Authorized attempt to write invalid data
262     my $library_with_invalid_field = { %$library_with_updated_field };
263     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
264
265     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field )
266       ->status_is(400)
267       ->json_is(
268         "/errors" => [
269             {
270                 message => "Properties not allowed: branchinvalid.",
271                 path    => "/body"
272             }
273         ]
274     );
275
276     my $non_existent_code = 'nope'.int(rand(10000));
277     $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field)
278       ->status_is(404);
279
280     $schema->storage->txn_rollback;
281 };
282
283 subtest 'delete() tests' => sub {
284     plan tests => 7;
285
286     $schema->storage->txn_begin;
287
288     my $authorized_patron = $builder->build_object({
289         class => 'Koha::Patrons',
290         value => { flags => 1 }
291     });
292     my $password = 'thePassword123';
293     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
294     my $auth_userid = $authorized_patron->userid;
295
296     my $unauthorized_patron = $builder->build_object({
297         class => 'Koha::Patrons',
298         value => { flags => 4 }
299     });
300     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
301     my $unauth_userid = $unauthorized_patron->userid;
302
303     my $library_id = $builder->build( { source => 'Branch' } )->{branchcode};
304
305     # Unauthorized attempt to delete
306     $t->delete_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" )
307       ->status_is(403);
308
309     $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" )
310       ->status_is(204, 'SWAGGER3.2.4')
311       ->content_is('', 'SWAGGER3.3.4');
312
313     $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" )
314       ->status_is(404);
315
316     $schema->storage->txn_rollback;
317 };