services/self-service/src/test/java/com/epam/datalab/backendapi/service/KeycloakServiceImplTest.java
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.epam.datalab.backendapi.service;

import com.epam.datalab.backendapi.conf.SelfServiceApplicationConfiguration;
import com.epam.datalab.backendapi.dao.SecurityDAO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.keycloak.representations.AccessTokenResponse;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class KeycloakServiceImplTest {
    private static final String ACCESS_TOKEN = "se2xy1bknelxn4y8xzxu3trosptip3q5" +
            "np3R0RqQjdCeW9aNGpaV05QTjJ3X25uS1BkTnQ4In0.eyJqdGkiOiJlYTgzZTQ2OS0xNjFhLTQ1ZDUtYWI4YS1mZDUxYThmMzMwMzYiL" +
            "se2xy1bknelxn4y8xzxu3trosptip3q5" +
            "949d1u22cbffbrarjh182eig55721odj" +
            "caf86f4uutaoxfysmf7anj01xl6sv3ps" +
            "caf86f4uutaoxfysmf7anj01xl6sv3ps" +
            "se2xy1bknelxn4y8xzxu3trosptip3q5" +
            "74t3tndxag9o7h0890bnpfzh4olk2h9x" +
            "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" +
            "WlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoidGVzdCJ9.jXjqFP1xmG32NahYnw1spO7fhEyGiqeu0QdBYuo9" +
            "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" +
            "9jnerlff23u8ed01np9g6ysbhsh0dvcs" +
            "caf86f4uutaoxfysmf7anj01xl6sv3ps";
    private static final String REFRESH_TOKEN = "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2" +
            "OS05NDUwLTdjNDQ4MTdjY2RkMCJ9.eyJqdGkiOiI0NmNiMzczMy1mM2IzLTRiYjItYmQyZC02N2FjNzg5N2VmNTUiLCJleHAiOjE1NzA" +
            "949d1u22cbffbrarjh182eig55721odj" +
            "9jnerlff23u8ed01np9g6ysbhsh0dvcs" +
            "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" +
            "9jnerlff23u8ed01np9g6ysbhsh0dvcs" +
            "9q3vfhm7l33rus21toc8fndupq76itje" +
            "ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b" +
            "uYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIn0.rzkrAprIt0-" +
            "kgfhvu9qnh3mr6eel97y6fq2hezzol8z";
    @Mock
    private Client httpClient;
    @Mock
    private SecurityDAO securityDAO;
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private SelfServiceApplicationConfiguration conf;

    private KeycloakServiceImpl keycloakService;

    @Before
    public void setUp() {
        keycloakService = new KeycloakServiceImpl(httpClient, conf, securityDAO);
    }

    @Test
    public void generateAccessToken() {
        WebTarget webTarget = mock(WebTarget.class);
        Invocation.Builder builder = mock(Invocation.Builder.class);
        Response response = mock(Response.class);
        Response.StatusType statusType = mock(Response.StatusType.class);
        AccessTokenResponse tokenResponse = mock(AccessTokenResponse.class);

        when(httpClient.target(anyString())).thenReturn(webTarget);
        when(webTarget.request()).thenReturn(builder);
        when(builder.header(any(), anyString())).thenReturn(builder);
        when(builder.post(any())).thenReturn(response);
        when(response.getStatusInfo()).thenReturn(statusType);
        when(response.readEntity(AccessTokenResponse.class)).thenReturn(tokenResponse);
        when(statusType.getFamily()).thenReturn(Response.Status.Family.SUCCESSFUL);
        when(tokenResponse.getToken()).thenReturn(ACCESS_TOKEN);
        doNothing().when(securityDAO).updateUser(anyString(), any(AccessTokenResponse.class));

        keycloakService.generateAccessToken(REFRESH_TOKEN);

        verify(httpClient).target(anyString());
        verify(securityDAO).updateUser("test", tokenResponse);
        verifyNoMoreInteractions(securityDAO, httpClient);
    }
}