it.infn.ct.indigo.futuregateway.server.FGServerManagerTest.java Source code

Java tutorial

Introduction

Here is the source code for it.infn.ct.indigo.futuregateway.server.FGServerManagerTest.java

Source

/**
 * *********************************************************************
 * Copyright (c) 2016: Istituto Nazionale di Fisica Nucleare (INFN) -
 * INDIGO-DataCloud
 *
 * See http://www.infn.it and and http://www.consorzio-cometa.it for details on
 * the copyright holders.
 *
 * Licensed 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 it.infn.ct.indigo.futuregateway.server;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import com.liferay.expando.kernel.service.ExpandoValueLocalService;
import com.liferay.portal.json.JSONFactoryImpl;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.servlet.HttpMethods;
import com.liferay.portal.security.sso.iam.IAM;

import it.infn.ct.indigo.futuregateway.constants.FutureGatewayAdminPortletKeys;
import it.infn.ct.indigo.futuregateway.utils.DataTest;

/**
 * FGServerManager tests collection.
 */
@RunWith(MockitoJUnitRunner.class)
public class FGServerManagerTest {

    /**
     * An http connection.
     */
    @Mock
    private HttpURLConnection connection;

    /**
     * The IAM security manager.
     */
    @Mock
    private IAM iam;

    /**
     * The expando value.
     */
    @Mock
    private ExpandoValueLocalService expandoValueService;

    /**
     * The FGServerManager.
     */
    @Spy
    private FGServerManager fgsm;

    /**
     * Prepare the environment.
     * Create some component normally generated by OSGi
     * @throws Exception If the expando service field cannot be replaced
     */
    @Before
    public final void setUp() throws Exception {
        JSONFactoryUtil jsonFactoryUtil = new JSONFactoryUtil();
        jsonFactoryUtil.setJSONFactory(new JSONFactoryImpl());
        Mockito.when(expandoValueService.getData(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString(),
                Mockito.anyString(), Mockito.anyLong(), Mockito.anyString())).thenReturn("http://");
        Field expandoVS = FGServerManager.class.getDeclaredField("expandoValueService");
        expandoVS.setAccessible(true);
        expandoVS.set(fgsm, expandoValueService);
    }

    /**
     * Test getInfrastructures.
     */
    @Test
    public final void testGetInfrastructures() {
        Random rand = new Random();
        int companyId = rand.nextInt();
        int userId = rand.nextInt();
        try {
            Mockito.when(iam.getUserToken(Mockito.anyLong())).thenReturn("");
            fgsm.setIam(iam);
            fgsm.setExpandoValueLocalService(expandoValueService);
            Mockito.doReturn(DataTest.INFRAS).when(fgsm).getCollection(Mockito.anyLong(),
                    Mockito.eq(FGServerConstants.INFRASTRUCTURE_COLLECTION), Mockito.anyString());
            Map<String, String> infras = fgsm.getInfrastructures(companyId, userId);
            Assert.assertArrayEquals(DataTest.INFRAS_ID, infras.keySet().toArray());
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test getFGConnection.
     */
    @Test
    public final void testGetFGConnection() {
        try {
            HttpURLConnection conn = fgsm.getFGConnection(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, "", "",
                    HttpMethods.POST, FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE);
            Assert.assertEquals(HttpMethods.POST, conn.getRequestMethod());
            Assert.assertEquals(FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE,
                    conn.getRequestProperty("Content-Type"));
        } catch (IllegalArgumentException | IOException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test getCollection.
     */
    @Test
    public final void testGetCollection() {
        try {
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
            Mockito.when(connection.getInputStream())
                    .thenReturn(new ByteArrayInputStream(DataTest.INFRAS.getBytes()));
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    (String) Mockito.isNull(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            String collection = fgsm.getCollection(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, "");
            Assert.assertEquals(DataTest.INFRAS, collection);
        } catch (IllegalArgumentException | IOException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test getCollection with problem.
     * The connection status code indicate an error
     * @throws IOException When the connection does not work
     */
    @Test(expected = IOException.class)
    public final void testGetCollectionWithError() throws IOException {
        try {
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR);
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    (String) Mockito.isNull(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            fgsm.getCollection(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, "");
        } catch (IllegalArgumentException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test addResource.
     */
    @Test
    public final void testAddResource() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_CREATED);
            Mockito.when(connection.getOutputStream()).thenReturn(baos);
            Mockito.when(connection.getInputStream())
                    .thenReturn(new ByteArrayInputStream(DataTest.INFRA_RES_CREATED.getBytes()));
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    (String) Mockito.isNull(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            String resourceId = fgsm.addResource(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, null,
                    DataTest.INFRA_RES, "");
            Assert.assertEquals(DataTest.INFRAS_ID[0], resourceId);
            Assert.assertEquals(DataTest.INFRA_RES, baos.toString(Charset.defaultCharset().name()));
        } catch (IllegalArgumentException | IOException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test addResource with problem.
     * The connection status code indicate an error
     * @throws IOException When the connection does not work
     */
    @Test(expected = IOException.class)
    public final void testAddResourceWithError() throws IOException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR);
            Mockito.when(connection.getOutputStream()).thenReturn(baos);
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    (String) Mockito.isNull(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            String resourceId = fgsm.addResource(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, null,
                    DataTest.INFRA_RES, "");
            Assert.assertEquals(DataTest.INFRAS_ID[0], resourceId);
            Assert.assertEquals(DataTest.INFRA_RES, baos.toString(Charset.defaultCharset().name()));
        } catch (IllegalArgumentException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test submitFilesResource.
     */
    @Test
    public final void testSubmitFilesResource() {
        try {
            Map<String, InputStream> files = temporaryRandomFiles();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
            Mockito.when(connection.getOutputStream()).thenReturn(baos);
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            fgsm.submitFilesResource(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, "", files, "");
            String[] stream = baos.toString().split("\\r?\\n");
            int fileId = -1;
            boolean fileContentLine = false;
            for (String line : stream) {
                if (line.contains("form-data")) {
                    String[] formElements = line.split(";");
                    String fileName = formElements[formElements.length - 1].trim();
                    fileName = fileName.substring(fileName.indexOf('"') + 1, fileName.lastIndexOf('"'));
                    Assert.assertNotNull(files.get(fileName));
                    fileId = Integer.parseInt(fileName.substring(0, 1));
                }
                if (fileContentLine) {
                    Assert.assertEquals(DataTest.FILES_CONT[fileId], line);
                    fileContentLine = false;
                }
                if (line.isEmpty()) {
                    fileContentLine = true;
                }
            }
        } catch (IllegalArgumentException | IOException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Test submitFilesResource.
     * @exception IOException  When the connection does not work
     */
    @Test(expected = IOException.class)
    public final void testSubmitFilesResourceWithError() throws IOException {
        try {
            Map<String, InputStream> files = temporaryRandomFiles();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Mockito.when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR);
            Mockito.when(connection.getOutputStream()).thenReturn(baos);
            Mockito.doReturn(connection).when(fgsm).getFGConnection(Mockito.anyLong(), Mockito.anyString(),
                    Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            fgsm.submitFilesResource(0, FGServerConstants.INFRASTRUCTURE_COLLECTION, "", files, "");
        } catch (IllegalArgumentException | PortalException e) {
            Assert.fail(e.getMessage());
        }
    }

    /**
     * Create temporary files for transfer test.
     * @return A map of file names and file objects
     * @throws IOException If temporary files cannot be created
     */
    private Map<String, InputStream> temporaryRandomFiles() throws IOException {
        Map<String, InputStream> files = new HashMap<>();
        for (int i = 0; i < DataTest.FILES_CONT.length; i++) {
            Path tempFile = Files.createTempFile(Integer.toString(i), null);
            tempFile.toFile().deleteOnExit();
            Files.write(tempFile, DataTest.FILES_CONT[i].getBytes(), StandardOpenOption.WRITE);
            files.put(tempFile.getFileName().toString(), new FileInputStream(tempFile.toFile()));
        }
        return files;
    }
}