transparent.market.alife.jetty.JettyTestCase.java Source code

Java tutorial

Introduction

Here is the source code for transparent.market.alife.jetty.JettyTestCase.java

Source

/*
 *      Copyright (C) 2015 Transparent Market
 *
 *   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 transparent.market.alife.jetty;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import transparent.market.alife.ApplicationContext;
import transparent.market.alife.MidasApplication;
import transparent.market.alife.dom.Page;
import transparent.market.alife.jetty.JettyInstance;
import transparent.market.alife.junit.MidasTestCase;
import transparent.market.util.Size;
import transparent.market.util.StringUtil;

/**
 * @author Martin Kersten <Martin.Kersten.mk@gmail.com>
 */
public class JettyTestCase extends MidasTestCase {

    protected static JettyInstance jettyInstance = null;
    protected static HtmlUnitDriver htmlUnitDriver = null;
    protected static FirefoxDriver firefoxDriver = null;

    @Before
    public void ensureJettyInstanceExists() {
        if (jettyInstance == null)
            jettyInstance = JettyInstance.setupForDevelopment();
    }

    @After
    public void shutdownJettyOnLastTestMethodOfLastTestCase() {
        if (isLastTestMethodOfLastTestCase(JettyTestCase.class)) {
            quitWebDrivers();
            jettyInstance.shutDown();
            jettyInstance = null;
        }
    }

    protected void quitWebDrivers() {
        quitHtmlUnitDriver();
        quitFirefoxDriver();
    }

    protected void quitFirefoxDriver() {
        quitWebDriver(firefoxDriver);
        firefoxDriver = null;
    }

    protected void quitWebDriver(WebDriver driver) {
        if (driver != null)
            driver.quit();
    }

    protected void quitHtmlUnitDriver() {
        quitWebDriver(htmlUnitDriver);
        htmlUnitDriver = null;
    }

    public HtmlUnitDriver getHtmlUnitDriver() {
        if (htmlUnitDriver == null)
            htmlUnitDriver = new HtmlUnitDriver();
        return htmlUnitDriver;
    }

    public FirefoxDriver getFirefoxDriver() {
        if (firefoxDriver == null)
            firefoxDriver = new FirefoxDriver();
        return firefoxDriver;
    }

    /** Returns the content of the page fetched by accessing the localhost server with 
     *  the current server port by URL. */
    protected static String getPage(String uri) {
        return getTextResource(uri);
    }

    /** Returns the text resource from the given uri. */
    protected static String getTextResource(String uri) {
        try {
            URL url = new URL(
                    "http://localhost:" + jettyInstance.getServerPort() + (uri.startsWith("/") ? "" : "/") + uri);
            try (InputStreamReader reader = new InputStreamReader(url.openStream())) {
                return StringUtil.readContentFromReader(reader);
            }
        } catch (IOException e) {
            throw new AssertionError("Problem while reading page content for " + uri, e);
        }
    }

    /** Returns the binary resource from the given uri. */
    protected static byte[] getBinaryResource(String uri) {
        try {
            URL url = new URL(
                    "http://localhost:" + jettyInstance.getServerPort() + (uri.startsWith("/") ? "" : "/") + uri);
            try (BufferedInputStream in = new BufferedInputStream(url.openStream());
                    ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buf = new byte[Size.FOUR_KILOBYTE];
                int bytesRead;
                while ((bytesRead = in.read(buf)) != -1) {
                    out.write(buf, 0, bytesRead);
                }
                return out.toByteArray();
            }
        } catch (IOException e) {
            throw new AssertionError("Problem while reading page content for " + uri, e);
        }
    }

    public static void assertTextFile(File expected, String actualContent) {
        String expectedContent = readTextFile(expected);
        Assert.assertEquals(expectedContent, actualContent);
    }

    public static String readTextFile(File expected) {
        try (FileReader in = new FileReader(expected)) {
            return StringUtil.readContentFromReader(in);
        } catch (IOException e) {
            throw new AssertionError("Problem while reading file '" + expected.getAbsolutePath() + "'");
        }
    }

    /** Asserts that the content of the page for the given URI is as expected. */
    protected static void assertPageContent(String expectedContent, String uri) {
        String actualContent = getPage(uri);
        Assert.assertEquals(expectedContent, actualContent);
    }

    /** Asserts that the content of a message page for the given URI is as expected. */
    protected static void assertMessagePageContent(String expectedMessage, String uri) {
        assertPageContent("<!DOCTYPE html>" + getExpectedMessagePageContent(expectedMessage), uri);
    }

    public abstract static class TestApplication extends MidasApplication {
        @Override
        public File getRootDirectory() {
            return getTestDirectory();
        }
    }

    protected void setupSinglePageTestApplication(Class<? extends Page> page) {
        setup(new SinglePageTestApplication(page));
    }

    protected void setup(MidasApplication application) {
        jettyInstance.start(application);
    }

    protected MidasApplication getApplication() {
        return jettyInstance.getApplication();
    }

    protected ApplicationContext getApplicationContext() {
        return getApplication().getApplicationContext();
    }

    protected void stop() {
        jettyInstance.stop();
    }

    public static class SinglePageTestApplication extends TestApplication {

        private final Class<? extends Page> pageClass;

        public SinglePageTestApplication(Class<? extends Page> pageClass) {
            this.pageClass = pageClass;
        }

        @Override
        public void init() {
            super.init();
            getDispatcher().setDefaultPage(pageClass);
        }
    }
}