Bug 20624: (QA follow-up) Unit tests for missing deps situation
authorTomas Cohen Arazi <tomascohen@theke.io>
Thu, 3 May 2018 18:24:56 +0000 (15:24 -0300)
committerJonathan Druart <jonathan.druart@bugs.koha-community.org>
Wed, 9 May 2018 15:56:02 +0000 (12:56 -0300)
This patch tests the situation in which Net::OAuth2::AuthorizationServer
is missing. It mocks Module::Load::Conditional::can_load and expects the
/token endpoint answers 'Unimplemented grant type' to all requests, and
the 'authenticate_api_request' in 'under' exit with unauthorized (403)
to requests in which the Authorization header is passed containing a
Bearer token, but OAuth2 is not really available.

To test:
- Apply this patch
- Run:
  $ kshell
 k$ prove t/db_dependent/api/v1/oauth.t
=> FAIL: Tests fail because our REST endpoints don't support this
behaviour.

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>
Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
t/db_dependent/api/v1/oauth.t

index e5762a2..2748fe2 100755 (executable)
@@ -17,7 +17,8 @@
 
 use Modern::Perl;
 
-use Test::More tests => 1;
+use Test::More tests => 2;
+use Test::MockModule;
 use Test::Mojo;
 
 use Koha::Database;
@@ -113,3 +114,40 @@ subtest '/oauth/token tests' => sub {
 
     $schema->storage->txn_rollback;
 };
+
+subtest 'Net::OAuth2::AuthorizationServer missing tests' => sub {
+
+    plan tests => 10;
+
+    my $load_conditional = Test::MockModule->new('Module::Load::Conditional');
+
+    # Enable the client credentials grant syspref
+    t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 );
+
+    my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 2**4 } });
+    my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
+
+    my $form_data = {
+        grant_type    => 'client_credentials',
+        client_id     => $api_key->client_id,
+        client_secret => $api_key->secret
+    };
+
+    $t->post_ok( '/api/v1/oauth/token', form => $form_data )->status_is(200)
+      ->json_is( '/expires_in' => 3600 )->json_is( '/token_type' => 'Bearer' )
+      ->json_has('/access_token');
+
+    my $access_token = $t->tx->res->json->{access_token};
+
+    $load_conditional->mock( 'can_load', sub { return 0; } );
+
+    my $tx = $t->ua->build_tx( GET => '/api/v1/patrons' );
+    $tx->req->headers->authorization("Bearer $access_token");
+    $t->request_ok($tx)
+      ->status_is(403);
+
+    $t->post_ok( '/api/v1/oauth/token', form => $form_data )
+      ->status_is(400)
+      ->json_is( { error => 'Unimplemented grant type' } );
+
+};