All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.behaviortest.api.BehaviorTest Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package br.com.behaviortest.api;

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.util.Map;

import org.openqa.selenium.WebDriver;

import br.com.behaviortest.api.common.LogExecution;
import br.com.behaviortest.api.engine.ExecutionTest;
import br.com.behaviortest.api.engine.holder.ExecutionHolder;
import br.com.behaviortest.api.engine.inicializer.BrowserInicializer;
import br.com.behaviortest.api.engine.loader.ConfigurationLoader;
import br.com.behaviortest.api.engine.loader.ParamsLoader;
import br.com.behaviortest.api.engine.loader.TestLoader;
import br.com.behaviortest.api.engine.validate.TestValidate;
import br.com.behaviortest.api.integration.BehaviorTestWeb;
import br.com.behaviortest.model.design.Result;
import br.com.behaviortest.model.design.Script;
import br.com.behaviortest.model.dto.Browser;
import br.com.behaviortest.model.dto.Configuration;
import br.com.behaviortest.model.dto.Delay;
import br.com.behaviortest.model.dto.Dimension;
import br.com.behaviortest.model.dto.Error;
import br.com.behaviortest.model.dto.Execution;
import br.com.behaviortest.model.dto.Failure;
import br.com.behaviortest.model.dto.Project;
import br.com.behaviortest.model.dto.Response;
import br.com.behaviortest.model.dto.Success;
import br.com.behaviortest.model.exception.IntegrationException;
import br.com.behaviortest.model.exception.IntegrityException;
import br.com.behaviortest.model.exception.LoadProjectException;
import br.com.behaviortest.model.type.BrowserType;
import br.com.behaviortest.model.type.DimensionMode;
import br.com.behaviortest.util.FileUtil;
import br.com.behaviortest.util.MessageUtil;
import br.com.behaviortest.util.ObjectUtil;
import br.com.behaviortest.util.StringUtil;

/**
 * @author 		Felipe Rudolfe
 * @since  		7 de jan de 2020
 */
public final class BehaviorTest {

	private BehaviorTest() {}

	public static final void run(Class mainClass, String ... params) {

		try {

			LogExecution.start();

			// Ler parametros da execução
			loadConfiguraton(mainClass, params);

			// Validar configurações do projeto
			Map> mapTest = loadScripts();

			// Validar execução de projeto web
			validate(mapTest);

			// Executar testes
			execute(mapTest);

			// Submeter resultados para a aplicação web
			resultSubmit();

			MessageUtil.printInfo("Successful execution", ConfigurationLoader.getConfiguration());

		} catch (IntegrityException | LoadProjectException e) {
			MessageUtil.printWarn(e.getMessage(), ConfigurationLoader.getConfiguration());
		} catch (Exception e) {
			MessageUtil.printError(e.getMessage(), ConfigurationLoader.getConfiguration());
		}
	}

	private static void loadConfiguraton(Class mainClass, String[] params) {

		ConfigurationLoader.loadConfiguration(mainClass);

		if (params != null && params.length > 0) {
			LogExecution.params(params);

			for (int i = 0; i < params.length; i++) {
				ParamsLoader.read(params[i]);
			}
		}
	}

	private static Map> loadScripts() {
		verifyDeclaredProperties();
		return loadTestClass();
	}

	private static void validate(Map> mapTest) {

		Configuration configuration = ConfigurationLoader.getConfiguration();

		LogExecution.testValidate();

		TestValidate.validate(mapTest);

		if (configuration.getExecution().getIncrement() != null) {

			ExecutionHolder.setIncrement(configuration.getExecution().getIncrement());

			Response responseExistIncrement = BehaviorTestWeb.existIncrement(configuration.getExecution().getIncrement());
			if (responseExistIncrement != null && responseExistIncrement.getData()) {

				ExecutionHolder.setIncrement(configuration.getExecution().getIncrement());
			} else {

				Response responseIncrement = BehaviorTestWeb.getNextIncrement();
				if (responseIncrement != null) {
					ExecutionHolder.setIncrement(responseIncrement.getData().longValue());
					configuration.getExecution().setIncrement(responseIncrement.getData().longValue());
				}
			}

		} else {

			Response responseIncrement = BehaviorTestWeb.getNextIncrement();
			if (responseIncrement != null) {
				ExecutionHolder.setIncrement(responseIncrement.getData().longValue());
				configuration.getExecution().setIncrement(responseIncrement.getData().longValue());
			}
		}

		Response responseVersion = BehaviorTestWeb.getVersionByIncrement(ExecutionHolder.getIncrement());
		if (responseVersion != null && responseVersion.getData() != null) {

			if (!configuration.getProject().getVersion().equals(responseVersion.getData())) {
                throw new LoadProjectException(
                		"Property 'project.version' ("
                				+ configuration.getProject().getVersion()
                				+ ") declared in configuration.yml file diferent than registered execution ("
                				+ responseVersion.getData()
                				+ ")");
            }

			ExecutionHolder.setVersion(responseVersion.getData());
		}

		LogExecution.testValidated();
	}

	private static void execute(Map> mapTest) {

		LogExecution.loadclasss(mapTest);
		ExecutionTest.start(mapTest);
	}

	private static void resultSubmit() {

		Configuration configuration = ConfigurationLoader.getConfiguration();
		if (configuration.getExecution().getSubmit()) {

			try {

				Long increment = ExecutionHolder.getIncrement();
				for (File file : FileUtil.getFiles(configuration.getTempDir() + "/results", "json")) {

					Result result = null;
					String json = FileUtil.getContent(file);
					if (json.contains("\"evaluation\":\"SUCCESS\"")) {
						result = StringUtil.fromJson(json, Success.class);
					} else if (json.contains("\"evaluation\":\"FAILURE\"")) {
						result = StringUtil.fromJson(json, Failure.class);
					} else if (json.contains("\"evaluation\":\"ERROR\"") || json.contains("\"evaluation\":\"PENDING\"")) {
						result = StringUtil.fromJson(json, Error.class);
					}

					result.setIncrement(increment);
					BehaviorTestWeb.saveResult(result);
				}

				BehaviorTestWeb.reportCollaborators(increment);

				FileUtil.deleteRecursive(new File(configuration.getTempDir() + "/results"));
				FileUtil.deleteRecursive(new File(configuration.getTempDir() + "/videos"));
				FileUtil.deleteRecursive(new File(configuration.getTempDir() + "/images"));

			} catch (Exception e) {
				e.printStackTrace();
				throw new IntegrationException("There was an error reading results");
			}
		}
	}

	private static void verifyDeclaredProperties() {

        try {

        	Configuration configuration = ConfigurationLoader.getConfiguration();

            if (ObjectUtil.isNull(configuration)) {
                throw new LoadProjectException("Configuration is null or empty");
            }

			verifyExecutionConfig(configuration);
			verifyProjectConfig(configuration);
			verifyDelayConfig(configuration);
            verifyBrowserConfig(configuration);

            if (ObjectUtil.isNullOrEmpty(configuration.getTempDir())) {
                throw new LoadProjectException("Property 'tempDir' not declared in configuration.yml file");
            }

        } catch (Exception e) {
            throw new LoadProjectException(e.getMessage());
        }
    }

	private static void verifyExecutionConfig(Configuration configuration) {

		Execution execution = configuration.getExecution();
		if (execution.getSubmit()) {

			if (ObjectUtil.isNullOrEmpty(execution.getApp())) {
				throw new LoadProjectException("Property 'execution.app' not declared in configuration.yml file");
			}

			if (ObjectUtil.isNullOrEmpty(execution.getToken())) {
				throw new LoadProjectException("Property 'execution.token' not declared in configuration.yml file");
			}

			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			GraphicsDevice[] screens = ge.getScreenDevices();

			if (ObjectUtil.isNull(screens) || screens.length == 0) {
				throw new LoadProjectException("Screen not found. You should run as 'CONSOLE' mode");
			}
		}
	}

	private static void verifyProjectConfig(Configuration configuration) {

		Project project = configuration.getProject();
		if (ObjectUtil.isNullOrEmpty(project.getUrl())) {
			throw new LoadProjectException("Property 'project.url' not declared in configuration.yml file");
		}

		if (ObjectUtil.isNullOrEmpty(project.getVersion())) {
			throw new LoadProjectException("Property 'project.version' not declared in configuration.yml file");
		}
	}

	private static void verifyDelayConfig(Configuration configuration) {

		Delay delay = configuration.getDelay();
		if (ObjectUtil.isNullOrEmpty(delay.getClickTimeout())) {
		    throw new LoadProjectException("Property 'delay.clickTimeout' not declared in configuration.yml file");
		}

		if (ObjectUtil.isNullOrEmpty(delay.getWritingTimeout())) {
		    throw new LoadProjectException("Property 'delay.writingTimeout' not declared in configuration.yml file");
		}

		if (ObjectUtil.isNullOrEmpty(delay.getCheckTimeout())) {
		    throw new LoadProjectException("Property 'delay.checkTimeout' not declared in configuration.yml file");
		}

		if (ObjectUtil.isNullOrEmpty(delay.getWaitingTimeout())) {
		    throw new LoadProjectException("Property 'delay.waitingTimeout' not declared in configuration.yml file");
		}
	}

	private static void verifyBrowserConfig(Configuration configuration) {

		LogExecution.browsersValidate();

		Browser [] browsers = configuration.getBrowsers();
		if (ObjectUtil.isNull(browsers) || browsers.length == 0) {
		    throw new LoadProjectException("Property 'browsers' not declared or empty in configuration.yml file");
		}

		for (int i = 0; i < browsers.length; i++) {

			LogExecution.browser(browsers[i]);

		    if (ObjectUtil.isNullOrEmpty(browsers[i].getType())) {

		    	throw new LoadProjectException(
		    			"Property 'browsers > ["
		    			+ i
		    			+ "].type' not declared in configuration.yml file");
		    }

		    if (ObjectUtil.isNullOrEmpty(browsers[i].getDriver())) {

				throw new LoadProjectException("Property 'browsers > [" + i + "].driver' not declared in configuration.yml file");

		    } else if (!FileUtil.existsInResources(browsers[i].getDriver())) {

		    	throw new LoadProjectException(
		    			"Property 'browsers > ["
						+ i
						+ "].driver' declared in configuration.yml file, serve file not found in path '"
		        		+ browsers[i].getDriver()
		        		+ "'");
		    }

		    Dimension dimension = browsers[i].getDimension();
		    if (ObjectUtil.isNull(dimension) || ObjectUtil.isNull(dimension.getMode())) {

		    	throw new LoadProjectException(
		    			"Property browsers > ["
		    			+ i
		    			+ "].dimension.mode should be declared in configuration.yml file");

			} else if (DimensionMode.CUSTOM.equals(dimension.getMode())
					&& (ObjectUtil.isNull(dimension.getHeight()) || ObjectUtil.isNull(dimension.getWidth()))) {

		    	throw new LoadProjectException(
		    			"Property 'browsers > ["
		    			+ i
		    			+ "].dimension.height' and/or browsers > ["
		    			+ i
		    			+ "].dimension.width'"
		    			+ "\n should be declared in configuration.yml file when browsers > ["
		    			+ i
		    			+ "].dimension.mode\n"
		    			+ "equals CUSTOM");
		    }

			if (BrowserType.INTERNET_EXPLORER.equals(browsers[i].getType()) && browsers[i].getHeadless()) {
				throw new LoadProjectException("'INTERNET_EXPLORER' browser unsuported 'headless' mode");
			}

			WebDriver driver = BrowserInicializer.get(browsers[i]);

			driver.quit();
			BrowserInicializer.destroy(browsers[i]);
		}
	}

	private static Map> loadTestClass() {
		return TestLoader.load();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy