fr.mailjet.rest.impl.AbstractServiceTestBase.java Source code

Java tutorial

Introduction

Here is the source code for fr.mailjet.rest.impl.AbstractServiceTestBase.java

Source

package fr.mailjet.rest.impl;

/*
 * 
 * Mailjet
 * %%
 * Copyright (C) 2012 Pitton Olivier - olivier dot pitton at gmail dot com
 * %%
 * 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.
 * #L%
 */

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.math.NumberUtils;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.sun.jersey.api.client.Client;

import fr.mailjet.context.MailjetContext;
import fr.mailjet.rest.parameters.EnumReturnType;

/**
 * Classe abstraite permettant de factoriser le {@link MailjetContext} et le
 * {@link Client} propre  tous les services. Pour lancer les tests, il faut
 * penser  mettre  jour les cls publique et secrte :
 * {@link AbstractServiceTestBase#getPublicKey()} et
 * {@link AbstractServiceTestBase#getSecretKey()}
 * 
 * @author Pitton Olivier
 * 
 */
@RunWith(Parameterized.class)
public abstract class AbstractServiceTestBase {

    /**
     * Fichier de proprits pour les tests
     */
    final private static Properties _testProperties = initTests();
    /**
     * Une cl publique pour les tests
     */
    final private String API_KEY = _testProperties.getProperty("api_key");
    /**
     * Une cl secrte pour les tests
     */
    final private String SECRET_KEY = _testProperties.getProperty("secret_key");
    /**
     * Un identifiant de campagne spcifique pour les tests
     */
    final Integer CAMPAIGN_ID = NumberUtils.createInteger(_testProperties.getProperty("campaign_id"));
    /**
     * Un identifiant de campagne stats spcifique pour les tests
     */
    final Integer STATS_CAMPAIGN_ID = NumberUtils.createInteger(_testProperties.getProperty("stats_campaign_id"));
    /**
     * Un identifiant de contact spcifique pour les tests
     */
    final Integer CONTACT_ID = NumberUtils.createInteger(_testProperties.getProperty("contact_id"));
    /**
     * Un identifiant de liste spcifique pour les tests
     */
    final Integer LIST_ID = NumberUtils.createInteger(_testProperties.getProperty("list_id"));
    /**
     * Un mail spcifique pour les tests
     */
    final String MAIL = _testProperties.getProperty("mail");

    /**
     * La liste des paramtres pour lancer les tests n fois. Les paramtres
     * correspondent  toutes les valeurs de {@link EnumReturnType}
     * 
     * @return {@link List} la liste des paramtres pour chaque tests
     * @see EnumReturnType
     * @see Parameterized
     */
    @Parameters
    static final public Collection<Object[]> parameters() {
        EnumReturnType[] locReturnTypeValues = EnumReturnType.values();
        List<Object[]> locParameters = new ArrayList<Object[]>(locReturnTypeValues.length);
        for (EnumReturnType locReturnType : locReturnTypeValues) {
            locParameters.add(new Object[] { locReturnType });
        }
        return locParameters;
    }

    /**
     * Retourne la cl publique en dur pour les tests unitaires.
     * 
     * @return {@link String} la cl publique en dur pour les tests unitaires.
     */
    final public String getPublicKey() {
        return this.API_KEY;
    }

    /**
     * Retourne la cl secrte en dur pour les tests unitaires.
     * 
     * @return {@link String} la cl secrte en dur pour les tests unitaires.
     */
    final public String getSecretKey() {
        return this.SECRET_KEY;
    }

    /**
     * Le contexte courant pour les tests
     */
    protected MailjetContext _context = new MailjetContext(this.getPublicKey(), this.getSecretKey());
    /**
     * Le type test
     */
    protected EnumReturnType _type;
    /**
     * Un logger pour les tests non finaliss
     */
    protected Logger _logger = Logger.getLogger("DEBUG");

    /**
     * Constructeur
     * 
     * @param parType
     *          {@link EnumReturnType} le type courant test
     */
    AbstractServiceTestBase(EnumReturnType parType) {
        this._type = parType;
    }

    /**
     * Vrifie que le status de la requte spcifie est valide
     * 
     * @param parResult
     *          {@link String} la requte
     */
    protected void checkStatus(String parResult) {
        assertNotNull(parResult);
        assertFalse(parResult.isEmpty());
        this.checkParameter(parResult, "status", "OK");
    }

    /**
     * Vrifie que le paramtre spcifi a bien la valeur spcifie pour la
     * rponse donne. Exemple : Si l'on doit vrifier que le status est "OK", la
     * mthode va vrifier qu'il existe "status:"OK" en JSON, de mme pour le XML.
     * Si le type {@link EnumReturnType} n'est pas test, une assertion est leve
     * volontairement.
     * 
     * @param parResult
     *          {@link String} la rponse du serveur
     * @param parKey
     *          {@link String} la cl
     * @param parValue
     *          {@link Object} la valeur
     */
    protected void checkParameter(String parResult, String parKey, Object parValue) {
        assertNotNull(parKey);
        assertFalse(parKey.trim().isEmpty());
        assertNotNull(parValue);
        switch (this._type) {
        case JSON:
            String locRealValue = parValue instanceof String ? "\"" + parValue + "\"" : parValue.toString();
            String locJSONProperty = "\"" + parKey + "\":" + locRealValue;
            assertTrue(parResult.contains(locJSONProperty));
            break;
        case XML:
            String locXMLProperty = "<" + parKey + ">" + parValue + "</" + parKey + ">";
            assertTrue(parResult.contains(locXMLProperty));
            break;
        default:
            assertFalse("Le paramtre " + this._type + " n'est pas vrifi", true);
        }
    }

    /**
     * Vrifie que le paramtre spcifi a un nombre entier comme valeur et que
     * ce-dernier est suprieur ou gal  la valeur spcifie.
     * 
     * @param parResult
     *          {@link String} la rponse du serveur
     * @param parKey
     *          {@link String} la cl
     * @param parMinimum
     *          {@link Integer} la valeur minimum que doit avoir le valeur du
     *          paramtre
     * @see #doMinimumInteger(String, String, Integer, String, String, int)
     */
    protected void checkMinimumIntegerParameter(String parResult, String parKey, Integer parMinimum) {
        this.checkMinimumIntegerParameter(parResult, parKey, parMinimum, true);
    }

    protected void checkMinimumIntegerParameter(String parResult, String parKey, Integer parMinimum,
            final boolean parIsText) {
        assertNotNull(parKey);
        assertFalse(parKey.trim().isEmpty());
        assertNotNull(parMinimum);

        switch (this._type) {
        case JSON:
            // Dans certains cas le nombre est un string et d'autres un int
            String locRegExp = parIsText ? "\"" + parKey + "\":\"[0-9]*\"" : "\"" + parKey + "\":[0-9]*";
            String locFirstIndex = parIsText ? ":\"" : ":";
            int locAdd = parIsText ? 2 : 1;
            this.doMinimumInteger(locRegExp, parResult, parMinimum, locFirstIndex, "\"", locAdd, parIsText);
            break;
        case XML:
            this.doMinimumInteger("<" + parKey + ">[0-9]*</" + parKey + ">", parResult, parMinimum, ">", "<", 1,
                    true);
            break;
        default:
            assertFalse(true);
        }
    }

    private void doMinimumInteger(String parRegExp, String parResult, Integer parMinimum, String parFirstIndexOf,
            String parLastIndexOf, int parAddToStart, boolean parUseLastIndexOf) {
        Pattern locPattern = Pattern.compile(parRegExp);
        Matcher locMatcher = locPattern.matcher(parResult);
        while (locMatcher.find()) {
            String locValue = locMatcher.group();
            int locStart = locValue.indexOf(parFirstIndexOf) + parAddToStart;
            int locEnd = parUseLastIndexOf ? locValue.lastIndexOf(parLastIndexOf) : locValue.length();
            int locRealIntegerValue = NumberUtils.toInt(locValue.substring(locStart, locEnd));
            assertTrue(parMinimum.intValue() <= locRealIntegerValue);
            return;
        }
        // Si la valeur n'a pas t trouv on lve une erreur
        assertFalse("La regexp " + parRegExp + " n'a rien trouv pour la valeur : \n" + parResult, true);
    }

    /**
     * Charge le fichier de tests
     * 
     * @return {@link Properties} les proprits charges
     */
    static private Properties initTests() {
        FileInputStream locStream = null;
        try {
            Properties locProperties = new Properties();
            locStream = new FileInputStream("test.properties");
            locProperties.load(locStream);
            return locProperties;
        } catch (IOException locException) {
            String locMessage = "Impossible de charger le fichier test.properties.";
            assertFalse(locMessage, true);
            throw new RuntimeException(locMessage, locException);
        } finally {
            if (locStream != null) {
                try {
                    locStream.close();
                } catch (IOException locException) {
                }
            }
        }
    }

}