From cc7ba3ccfb4d000e745eab835e0fac42dc958dd5 Mon Sep 17 00:00:00 2001
From: Lari Taskula <lari.taskula@hypernova.fi>
Date: Fri, 8 Nov 2019 14:43:21 +0000
Subject: [PATCH] Bug 24003: Add a failing test for missing userenv for REST
 basic auth

When using REST API via basic authentication method, C4::Context->userenv
returns undef.

This patch adds a failing test to prove it.

To test:
1. prove t/db_dependent/api/v1/auth_basic.t
2. Observe failures:

    not ok 5 - exact match for JSON Pointer "/userenv/number"
       Failed test 'exact match for JSON Pointer "/userenv/number"'
       at t/db_dependent/api/v1/auth_basic.t line 52.
              got: undef
         expected: '1054'
    not ok 6 - exact match for JSON Pointer "/userenv/id"
       Failed test 'exact match for JSON Pointer "/userenv/id"'
       at t/db_dependent/api/v1/auth_basic.t line 52.
              got: undef
         expected: 'tomasito'
---
 t/db_dependent/api/v1/auth_basic.t | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/t/db_dependent/api/v1/auth_basic.t b/t/db_dependent/api/v1/auth_basic.t
index 4fb48f0277..c077988e4b 100644
--- a/t/db_dependent/api/v1/auth_basic.t
+++ b/t/db_dependent/api/v1/auth_basic.t
@@ -19,6 +19,7 @@ use Modern::Perl;
 
 use Test::More tests => 2;
 use Test::Mojo;
+use Test::MockModule;
 
 use t::lib::TestBuilder;
 use t::lib::Mocks;
@@ -26,11 +27,13 @@ use t::lib::Mocks;
 my $schema  = Koha::Database->new->schema;
 my $builder = t::lib::TestBuilder->new;
 
+my $mock = create_a_test_endpoint();
+
 my $t = Test::Mojo->new('Koha::REST::V1');
 
 subtest 'success tests' => sub {
 
-    plan tests => 5;
+    plan tests => 9;
 
     $schema->storage->txn_begin;
 
@@ -46,6 +49,11 @@ subtest 'success tests' => sub {
     $t->get_ok("//$userid:$password@/api/v1/patrons")
       ->status_is( 200, 'Successful authentication and permissions check' );
 
+    $t->post_ok("//$userid:$password@/api/v1/oauth/token")
+      ->status_is( 418, 'Successful authentication and not enough permissions' )
+      ->json_is('/userenv/number'   => $patron->borrowernumber)
+      ->json_is('/userenv/id'       => $userid);
+
     $patron->flags(undef)->store;
 
     $t->get_ok("//$userid:$password@/api/v1/patrons")
@@ -90,4 +98,16 @@ subtest 'failure tests' => sub {
     $schema->storage->txn_rollback;
 };
 
+sub create_a_test_endpoint {
+    # Mock POST /oauth/token endpoint to return userenv
+    # (it could be any other endpoint that doesn't require authentication too)
+    my $mock = Test::MockModule->new('Koha::REST::V1::OAuth');
+    $mock->mock(token => sub {
+        my $c = shift;
+        return $c->render( status => 418,
+                           json => { userenv => C4::Context->userenv });
+    });
+    return $mock;
+}
+
 1;
-- 
2.17.1