org.apigw.authserver.web.controller.CertifiedClientsControllerTest.java Source code

Java tutorial

Introduction

Here is the source code for org.apigw.authserver.web.controller.CertifiedClientsControllerTest.java

Source

/**
 *   Copyright 2013 Stockholm County Council
 *
 *   This file is part of APIGW
 *
 *   APIGW is free software; you can redistribute it and/or modify
 *   it under the terms of version 2.1 of the GNU Lesser General Public
 *   License as published by the Free Software Foundation.
 *
 *   APIGW is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with APIGW; if not, write to the
 *   Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 *   Boston, MA 02111-1307  USA
 *
 */

package org.apigw.authserver.web.controller;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.not;
import static org.mockito.Matchers.anyString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apigw.authserver.svc.CertifiedClientDetailsService;
import org.apigw.authserver.svc.PermissionServices;
import org.apigw.authserver.svc.encrypted.EncryptedConsumerTokenService;
import org.apigw.authserver.svc.encrypted.EncryptedMonitoringService;
import org.apigw.authserver.svc.encrypted.EncryptedResourceOwnerServices;
import org.apigw.authserver.types.domain.CertifiedClient;
import org.apigw.authserver.types.domain.Permission;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:apigw-resources-test-config.xml")
@WebAppConfiguration
public class CertifiedClientsControllerTest {

    @Mock
    private CertifiedClientDetailsService clientDetailsService;

    @Mock
    private EncryptedConsumerTokenService encryptedConsumerTokenService;

    @Mock
    private PermissionServices permissionServices;

    @Mock
    private EncryptedMonitoringService monitoringService;

    @Mock
    private EncryptedResourceOwnerServices encryptedResourceOwnerServices;

    @InjectMocks
    private CertifiedClientsController clientController;

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    private Authentication authentication;

    private SecurityContext securityContext;

    @Before
    public void setup() {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);

        // Setup Spring test in standalone mode
        this.mockMvc = MockMvcBuilders.standaloneSetup(clientController).build();

        mockSecurityContext();
    }

    private void mockSecurityContext() {
        //SecurityContext access is done the static why hence we need
        //to mock it.
        authentication = Mockito.mock(Authentication.class);
        // Mockito.whens() for your authorization object
        securityContext = Mockito.mock(SecurityContext.class);
        Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
        Mockito.when(securityContext.getAuthentication().getPrincipal()).thenReturn(new UserDetails() {
            @Override
            public boolean isEnabled() {
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return false;
            }

            @Override
            public boolean isAccountNonLocked() {
                return false;
            }

            @Override
            public boolean isAccountNonExpired() {
                return false;
            }

            @Override
            public String getUsername() {
                return "USER";
            }

            @Override
            public String getPassword() {
                return "PASSWORD";
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                authorities.add(new GrantedAuthorityImpl("A_ROLE"));
                return authorities;
            }
        });

        //Set the Securitycontext for this test
        SecurityContextHolder.setContext(securityContext);
    }

    @Test
    public void happy_days() throws Exception {

        commonMocks();

        mockMvc.perform(get("/oauth/clients")).andExpect(status().isOk())
                .andExpect(
                        model().attribute("certifiedClients",
                                hasItem(allOf(hasProperty("clientId", equalTo("INSTALLED_CLIENT_ID")),
                                        hasProperty("clientName", equalTo("INSTALLED_CLIENT_NAME")),
                                        hasProperty("organization", equalTo("INSTALLED_CLIENT_ORGANIZATION")),
                                        hasProperty("description", equalTo("A description")),
                                        hasProperty("userDetails", allOf(
                                                hasItem(allOf(hasProperty("residentId", equalTo("USER")),
                                                        hasProperty("scopes", equalTo(
                                                                "MOCK_ROLE_DESCRIPTION, MOCK_ROLE_DESCRIPTION")),
                                                        hasProperty("grantId", equalTo("MOCK_GRANT_ID")))),
                                                not(hasItem(hasProperty("residentId", equalTo("CHILD_1")))),
                                                not(hasItem(hasProperty("residentId", equalTo("CHILD_2"))))))))));
    }

    @Test
    public void include_info_about_children_for_a_legal_guardian() throws Exception {

        commonMocks();

        //Collection of children
        Collection<String> children = new HashSet<String>();
        children.add("CHILD_1");
        children.add("CHILD_2");

        //Mock ResourceOwnerServices
        Mockito.when(encryptedResourceOwnerServices.findChildrenOfLegalGuardian("USER")).thenReturn(children);

        mockMvc.perform(get("/oauth/clients")).andExpect(status().isOk())
                .andExpect(model().attribute("certifiedClients",
                        hasItem(allOf(hasProperty("clientId", equalTo("INSTALLED_CLIENT_ID")),
                                hasProperty("clientName", equalTo("INSTALLED_CLIENT_NAME")),
                                hasProperty("organization", equalTo("INSTALLED_CLIENT_ORGANIZATION")),
                                hasProperty("description", equalTo("A description")),
                                hasProperty(
                                        "userDetails", allOf(
                                                hasItem(allOf(hasProperty("residentId", equalTo("USER")),
                                                        hasProperty("scopes", equalTo(
                                                                "MOCK_ROLE_DESCRIPTION, MOCK_ROLE_DESCRIPTION")),
                                                        hasProperty("grantId", equalTo("MOCK_GRANT_ID")))),
                                                hasItem(allOf(hasProperty("residentId", equalTo("CHILD_1")),
                                                        hasProperty("scopes", equalTo(
                                                                "MOCK_ROLE_DESCRIPTION, MOCK_ROLE_DESCRIPTION")),
                                                        hasProperty("grantId", equalTo("MOCK_GRANT_ID")))),
                                                hasItem(allOf(hasProperty("residentId", equalTo("CHILD_2")),
                                                        hasProperty("scopes", equalTo(
                                                                "MOCK_ROLE_DESCRIPTION, MOCK_ROLE_DESCRIPTION")),
                                                        hasProperty("grantId", equalTo("MOCK_GRANT_ID"))))))))));
    }

    private void commonMocks() {
        //Collection of Oauthtokens to return when asked for in the controller
        Collection<OAuth2AccessToken> tokens = new ArrayList<OAuth2AccessToken>();
        DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("MOCK_TOKEN_VALUE");
        //Add some scopes
        Set<String> scope = new HashSet<String>();
        scope.add("MOCK_SCOPE_ITEM_1");
        scope.add("MOCK_SCOPE_ITEM_2");

        //Placeholder for additionalInformation
        Map<String, Object> addInfo = new HashMap<String, Object>();
        addInfo.put("authorization_grant_id", "MOCK_GRANT_ID");

        //Set all relevant things on this accessToken
        accessToken.setScope(scope);
        accessToken.setExpiration(new DateTime().plusDays(1).toDate());
        accessToken.setAdditionalInformation(addInfo);

        tokens.add(accessToken);

        //Mock encryptedConsumerTokenService interactions
        Mockito.when(encryptedConsumerTokenService.findTokensByUserName(anyString())).thenReturn(tokens);
        Mockito.when(encryptedConsumerTokenService.getClientId("MOCK_TOKEN_VALUE"))
                .thenReturn("INSTALLED_CLIENT_ID");

        //CertifiedClients to return from clientDetailsServices mock
        List<CertifiedClient> clients = new ArrayList<CertifiedClient>();
        CertifiedClient installedClient = new CertifiedClient();
        CertifiedClient availableClient = new CertifiedClient();
        installedClient.setName("INSTALLED_CLIENT_NAME");
        installedClient.setClientId("INSTALLED_CLIENT_ID");
        installedClient.setOrganization("INSTALLED_CLIENT_ORGANIZATION");
        installedClient.setDescription("A description");

        availableClient.setName("AVAILABLE_CLIENT_NAME");
        availableClient.setClientId("AVAILABLE_CLIENT_ID");
        availableClient.setOrganization("AVAILABLE_CLIENT_ORGANIZATION");
        availableClient.setDescription("A description");
        availableClient.setClientUrl("http://somewhere");

        clients.add(installedClient);
        clients.add(availableClient);

        //Mock clientDetailsService interactions
        Mockito.when(clientDetailsService.findAllClients()).thenReturn(clients);
        Mockito.when(clientDetailsService.loadClientByClientId("INSTALLED_CLIENT_ID")).thenReturn(installedClient);

        //Permission to return from permissionServices mock
        Permission mockPermission = new Permission();
        mockPermission.setDescription("MOCK_ROLE_DESCRIPTION");

        //Mock scopeservices
        Mockito.when(permissionServices.getPermissionByName(anyString())).thenReturn(mockPermission);
    }
}