tk.elevenk.restfulrobot.testsuite.TestSuiteReader.java Source code

Java tutorial

Introduction

Here is the source code for tk.elevenk.restfulrobot.testsuite.TestSuiteReader.java

Source

/* This source code file is part of RESTfulRobot
Copyright (C) 2014 John Krause (Eleven-K Software)
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program 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 Affero General Public License for more details.
    
You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package tk.elevenk.restfulrobot.testsuite;

import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Set;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import tk.elevenk.restfulrobot.RestfulRobot;
import tk.elevenk.restfulrobot.testcase.TestCase;

public class TestSuiteReader {

    // ******************************************************************************************
    // INSTANCE VARIABLES
    // *******************************************************************************************/

    private static final String JSON_PARSE_ERROR = "Error reading test suite file. Check Syntax in file and that the file exists.";
    private static final String TEST_CASES_KEY = "testCases";
    private static final String BASE_URL_KEY = "baseURL";

    private String testSuiteFileName;
    private ArrayList<TestSuite> testSuites;
    private Logger logger = LogManager.getLogger(TestSuiteReader.class.getName());

    // ******************************************************************************************
    // CONSTRUCTOR
    // *******************************************************************************************/

    /**
     * Reads the given test suite file and creates an array of test suites
     * 
     * @param file
     */
    public TestSuiteReader() {

        testSuites = new ArrayList<TestSuite>();

    }

    /******************************************************************************************
     * METHODS
     *******************************************************************************************/

    /**
     * Reads the given file and populates the suite list
     * 
     * @param file
     */
    public void read(String file) {
        // set filename from parameter
        testSuiteFileName = file;

        try {

            // retrieve list of directories to look for suites in
            String path = new File(RestfulRobot.FILES_PATH).getAbsolutePath();
            File temp = new File(path);
            String[] directories = temp.list(new FilenameFilter() {
                @Override
                public boolean accept(File current, String name) {
                    return new File(current, name).isDirectory();
                }
            });

            // create JSON object to hold the whole suite
            JSONObject jsonSuiteFile = null;

            // attempt to parse file from root files directory first
            logger.info("Searching for test suite file...");
            try {
                jsonSuiteFile = (JSONObject) JSONValue
                        .parse(new FileReader(RestfulRobot.FILES_PATH + testSuiteFileName));
            } catch (Exception e) {
                logger.trace(e.getMessage());
            }

            // attempt to parse file from each sub-directory until it is found
            if (directories != null) {
                for (int i = 0; i < directories.length && jsonSuiteFile == null; i++) {
                    try {
                        jsonSuiteFile = (JSONObject) JSONValue.parse(
                                new FileReader(RestfulRobot.FILES_PATH + directories[i] + "/" + testSuiteFileName));
                    } catch (Exception e) {
                        logger.trace(e.getMessage());
                    }
                }
            }

            // log error if the file was not found
            if (jsonSuiteFile == null) {
                logger.error(JSON_PARSE_ERROR);
                System.out.println(JSON_PARSE_ERROR);
            }

            else {
                logger.info("Test suite file found. Processing...");

                // retrieve the set of keys from the JSON object which are each
                // test suites
                @SuppressWarnings("unchecked")
                Set<String> keys = jsonSuiteFile.keySet();

                /*
                 * Test suite files are formatted to contain json objects for
                 * each test suite in the file. Each test suite object has the
                 * details of the suite such as cases and base URL.
                 */
                for (String suiteName : keys) {

                    // get the suite object to parse test cases from
                    JSONObject suite = (JSONObject) jsonSuiteFile.get(suiteName);

                    ArrayList<TestCase> testCasesArray = new ArrayList<TestCase>();

                    // find the test cases array in the test suite and
                    // add each test case script name to a list
                    JSONArray testCases = (JSONArray) suite.get(TEST_CASES_KEY);
                    for (int i = 0; i < testCases.size(); i++) {
                        testCasesArray.add(new TestCase((String) testCases.get(i)));
                    }

                    // get the base url from the suite
                    String baseURL = (String) suite.get(BASE_URL_KEY);

                    // create a test suite with the given test cases and add to
                    // list of test suites
                    TestSuite testSuite = new TestSuite(suiteName, baseURL, testCasesArray);
                    testSuites.add(testSuite);
                }
            }
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
    }

    // *****************************************************************************
    // GETTERS/SETTERS
    // *****************************************************************************

    public String getFileName() {
        return testSuiteFileName;
    }

    public ArrayList<TestSuite> getTestSuites() {
        return testSuites;
    }
}