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

net.thucydides.core.csv.CSVTestDataSource Maven / Gradle / Ivy

There is a newer version: 0.9.275
Show newest version
package net.thucydides.core.csv;

import au.com.bytecode.opencsv.CSVReader;
import net.thucydides.core.steps.ScenarioSteps;
import net.thucydides.core.steps.StepFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Test data from a CSV file.
 */
public class CSVTestDataSource implements TestDataSource {
    
    private final List> testData;
    private final char separator;

    private static final Logger LOGGER = LoggerFactory.getLogger(CSVTestDataSource.class);

    public CSVTestDataSource(final String path, final char separatorValue) throws IOException {
        this.separator = separatorValue;
        testData = loadTestDataFrom(getDataFileFor(path));
    }

    public CSVTestDataSource(final String path) throws IOException {
        this(path, CSVReader.DEFAULT_SEPARATOR);
    }    
    
    private Reader getDataFileFor(final String path) throws FileNotFoundException {
        if (isAClasspathResource(path)) {
            return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(path));
        }
        return new FileReader(new File(path));
    }

    private boolean isAClasspathResource(final String path) {
        return (!validFileSystemPath(path));
    }

    private boolean validFileSystemPath(final String path) {
        File file = new File(path);
        return file.exists();
    }

    protected List> loadTestDataFrom(final Reader testDataReader) throws IOException {

        CSVReader reader = new CSVReader(testDataReader, separator);
        List rows = reader.readAll();

        List> loadedData = new ArrayList>();
        String[] titleRow = rows.get(0);

        for (int i = 1; i < rows.size(); i++) {
            String[] dataRow = rows.get(i);
            loadedData.add(dataEntryFrom(titleRow, dataRow));
        }
        return loadedData;
    }

    private Map dataEntryFrom(final String[] titleRow, final String[] dataRow) {
        Map dataset = new HashMap();

        for (int column = 0; column < titleRow.length; column++) {
            if (column < dataRow.length) {
                String title = titleRow[column].trim();
                String value = dataRow[column].trim();
                dataset.put(title, value);
            }
        }

        return dataset;
    }

    public List> getData() {
        return testData;
    }

    /**
     * Returns the test data as a list of JavaBean instances.
     */
    public  List getDataAsInstancesOf(final Class clazz, final Object... constructorArgs) {
        List> data = getData();

        List resultsList = new ArrayList();
        for (Map rowData : data) {
            resultsList.add(newInstanceFrom(clazz, rowData, constructorArgs));
        }
        return resultsList;
    }

    public  List getInstanciatedInstancesFrom(final Class clazz,
                                                                          final StepFactory factory) {
        List> data = getData();

        List resultsList = new ArrayList();
        for (Map rowData : data) {
            resultsList.add(newInstanceFrom(clazz, factory, rowData));
        }
        return resultsList;
    }

    private  T newInstanceFrom(final Class clazz,
                                  final Map rowData,
                                  final Object... constructorArgs) {

        T newObject = createNewInstanceOf(clazz, constructorArgs);
        assignPropertiesFromTestData(clazz, rowData, newObject);
        return newObject;
    }

    private  T newInstanceFrom(final Class clazz,
                                                        final StepFactory factory,
                                                        final Map rowData) {
        T newObject = factory.newSteps(clazz);
        assignPropertiesFromTestData(clazz, rowData, newObject);
        return newObject;
    }

    private  void assignPropertiesFromTestData(final Class clazz,
                                                  final Map rowData,
                                                  final T newObject) {
        Set propertyNames = rowData.keySet();

        boolean validPropertyFound = false;
        for (String columnHeading : propertyNames) {
            String value = rowData.get(columnHeading);
            String property = FieldName.from(columnHeading).inNormalizedForm();

            if (assignPropertyValue(newObject, property, value)) {
                validPropertyFound = true;
            }
        }
        if (!validPropertyFound) {
            throw new FailedToInitializeTestData("No properties or public fields matching the data columns were found "
                                                 + "or could be assigned for the class " + clazz.getName()
                                                 + "using test data: " + rowData);
        }
    }

    protected  T createNewInstanceOf(final Class clazz, final Object... constructorArgs) {
        try {
            return InstanceBuilder.newInstanceOf(clazz, constructorArgs);
        } catch (Exception e) {
            LOGGER.error("Could not create test data bean", e);
            throw new FailedToInitializeTestData("Could not create test data beans", e);
        }
    }

    protected  boolean assignPropertyValue(final T newObject, final String property, final String value) {
        boolean valueWasAssigned = true;
        try {
            InstanceBuilder.inObject(newObject).setPropertyValue(property, value);
        } catch (FailedToInitializeTestData e) {
            valueWasAssigned = false;
        }
        return valueWasAssigned;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy