16848: Adds unit test.
authorLucas Di Pentima <lucas@di-pentima.com.ar>
Wed, 10 Mar 2021 22:24:02 +0000 (19:24 -0300)
committerLucas Di Pentima <lucas@di-pentima.com.ar>
Wed, 10 Mar 2021 22:24:02 +0000 (19:24 -0300)
Arvados-DCO-1.1-Signed-off-by: Lucas Di Pentima <lucas@di-pentima.com.ar>

src/store/auth/auth-action.test.ts
src/store/auth/auth-action.ts

index f1a534c64818cdae5b8b866dbd8fcf7347bb6628..abc2a5a1a438f2237b88e166a884f957ce74dfee 100644 (file)
@@ -2,7 +2,7 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { initAuth } from "./auth-action";
+import { getNewExtraToken, initAuth } from "./auth-action";
 import { API_TOKEN_KEY } from "~/services/auth-service/auth-service";
 
 import 'jest-localstorage-mock';
@@ -16,6 +16,7 @@ import Axios from "axios";
 import MockAdapter from "axios-mock-adapter";
 import { ImportMock } from 'ts-mock-imports';
 import * as servicesModule from "~/services/services";
+import { SessionStatus } from "~/models/session";
 
 describe('auth-actions', () => {
     const axiosInst = Axios.create({ headers: {} });
@@ -42,8 +43,7 @@ describe('auth-actions', () => {
         importMocks.map(m => m.restore());
     });
 
-    it('should initialise state with user and api token from local storage', (done) => {
-
+    it('creates an extra token', async () => {
         axiosMock
             .onGet("/users/current")
             .reply(200, {
@@ -56,15 +56,76 @@ describe('auth-actions', () => {
                 is_active: true,
                 username: "jdoe",
                 prefs: {}
+            })
+            .onGet("/api_client_authorizations/current")
+            .reply(200, {
+                expires_at: "2140-01-01T00:00:00.000Z",
+                api_token: 'extra token',
+            })
+            .onPost("/api_client_authorizations")
+            .replyOnce(200, {
+                uuid: 'zzzzz-gj3su-xxxxxxxxxx',
+                apiToken: 'extra token',
+            })
+            .onPost("/api_client_authorizations")
+            .reply(200, {
+                uuid: 'zzzzz-gj3su-xxxxxxxxxx',
+                apiToken: 'extra additional token',
             });
 
+        importMocks.push(ImportMock.mockFunction(servicesModule, 'createServices', services));
+        sessionStorage.setItem(ACCOUNT_LINK_STATUS_KEY, "0");
+        localStorage.setItem(API_TOKEN_KEY, "token");
+
+        const config: any = {
+            rootUrl: "https://zzzzz.arvadosapi.com",
+            uuidPrefix: "zzzzz",
+            remoteHosts: { },
+            apiRevision: 12345678,
+            clusterConfig: {
+                Login: { LoginCluster: "" },
+            },
+        };
+
+        // Set up auth, confirm that no extra token was requested
+        await store.dispatch(initAuth(config))
+        expect(store.getState().auth.apiToken).toBeDefined();
+        expect(store.getState().auth.extraApiToken).toBeUndefined();
+
+        // Ask for an extra token
+        await store.dispatch(getNewExtraToken());
+        expect(store.getState().auth.apiToken).toBeDefined();
+        expect(store.getState().auth.extraApiToken).toBeDefined();
+        const extraToken = store.getState().auth.extraApiToken;
+
+        // Ask for a cached extra token
+        await store.dispatch(getNewExtraToken(true));
+        expect(store.getState().auth.extraApiToken).toBe(extraToken);
+
+        // Ask for a new extra token, should make a second api request
+        await store.dispatch(getNewExtraToken(false));
+        expect(store.getState().auth.extraApiToken).toBeDefined();
+        expect(store.getState().auth.extraApiToken).not.toBe(extraToken);
+    });
+
+    it('should initialise state with user and api token from local storage', (done) => {
         axiosMock
+            .onGet("/users/current")
+            .reply(200, {
+                email: "test@test.com",
+                first_name: "John",
+                last_name: "Doe",
+                uuid: "zzzzz-tpzed-abcefg",
+                owner_uuid: "ownerUuid",
+                is_admin: false,
+                is_active: true,
+                username: "jdoe",
+                prefs: {}
+            })
             .onGet("/api_client_authorizations/current")
             .reply(200, {
                 expires_at: "2140-01-01T00:00:00.000Z"
-            });
-
-        axiosMock
+            })
             .onGet("https://xc59z.arvadosapi.com/discovery/v1/apis/arvados/v1/rest")
             .reply(200, {
                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
@@ -101,8 +162,8 @@ describe('auth-actions', () => {
             const auth = store.getState().auth;
             if (auth.apiToken === "token" &&
                 auth.sessions.length === 2 &&
-                auth.sessions[0].status === 2 &&
-                auth.sessions[1].status === 2
+                auth.sessions[0].status === SessionStatus.VALIDATED &&
+                auth.sessions[1].status === SessionStatus.VALIDATED
             ) {
                 try {
                     expect(auth).toEqual({
@@ -192,7 +253,7 @@ describe('auth-actions', () => {
                     });
                     done();
                 } catch (e) {
-                    console.log(e);
+                    fail(e);
                 }
             }
         });
index 4f576fe4efcd83df36ef8641f330daddeeb9315e..8c44aec448754ad9115a25c0730a911664a9b23a 100644 (file)
@@ -38,21 +38,18 @@ export const authActions = unionize({
     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
 });
 
-export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+export const initAuth = (config: Config) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
     // Cancel any link account ops in progress unless the user has
     // just logged in or there has been a successful link operation
     const data = services.linkAccountService.getLinkOpStatus();
     if (!matchTokenRoute(location.pathname) &&
         (!matchFedTokenRoute(location.pathname)) && data === undefined) {
-        dispatch<any>(cancelLinking()).then(() => {
-            dispatch<any>(init(config));
-        });
-    } else {
-        dispatch<any>(init(config));
+        await dispatch<any>(cancelLinking());
     }
+    return dispatch<any>(init(config));
 };
 
-const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+const init = (config: Config) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
     const remoteHosts = () => getState().auth.remoteHosts;
     const token = services.authService.getApiToken();
     let homeCluster = services.authService.getHomeCluster();
@@ -70,11 +67,12 @@ const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState,
 
     if (token && token !== "undefined") {
         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
-        dispatch<any>(saveApiToken(token)).then(() => {
-            dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
-        }).catch(() => {
+        try {
+            await dispatch<any>(saveApiToken(token)); // .then(() => {
+            await dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
+        } catch (e) {
             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
-        });
+        }
     }
 };