net.sf.ginp.TestGinpModel.java Source code

Java tutorial

Introduction

Here is the source code for net.sf.ginp.TestGinpModel.java

Source

/*
 *  ginp - Java Web Application for Viewing Photo Collections
 *  Copyright (C) 2004  Douglas John Culnane <doug@culnane.net>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package net.sf.ginp;

import junit.framework.TestCase;

import net.sf.ginp.commands.SetLanguageCode;
import net.sf.ginp.config.Configuration;
import net.sf.ginp.config.ModelUtil;
import net.sf.ginp.setup.SetupException;
import net.sf.ginp.util.StringTool;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Vector;

/**
 *  Test Case Class for use with junit.
 *
 *@author     Doug Culnane
 *@version    $Revision$
 */
public class TestGinpModel extends TestCase {
    private GinpModel model;
    private Log log = LogFactory.getLog(TestGinpModel.class);
    private static boolean firstTime = true;
    private static String TEST_DIRECTORY = System.getProperty("java.io.tmpdir") + File.separator + "TestGinpModel";
    private static String CONFIG_FILE_LOCATION = TEST_DIRECTORY + File.separator + "ginp.xml";
    private static String PICTURE_FILE_NAME = "picture.jpeg";
    private static String PICTURE_FILE_LOCATION = TEST_DIRECTORY + File.separator + PICTURE_FILE_NAME;

    /**
     *  A unit test for JUnit
     */
    public void test_Collection() {
        PicCollection collection = model.getCollection(0);
        assertEquals("Test PicCollection (id=0)", collection.getName());
    }

    /**
     *  A unit test for JUnit
     */
    public void test_Collection_sortPictures() {
        String[] ans1 = { "a.jpeg", "b.jpg", "c", "d.jpg" };
        String[] tst1 = { "a.jpeg", "b.jpg", "c", "d.jpg" };

        ModelUtil.getFolderManager().sortPictures(ans1);

        for (int i = 0; i < ans1.length; i++) {
            assertEquals(ans1[i], tst1[i]);
        }

        tst1[0] = "c";
        tst1[2] = "a.jpeg";
        ModelUtil.getFolderManager().sortPictures(tst1);

        for (int i = 0; i < ans1.length; i++) {
            assertEquals(ans1[i], tst1[i]);
        }

        tst1[0] = "/path to/c";
        tst1[2] = "/path to/a.jpeg";
        ModelUtil.getFolderManager().sortPictures(tst1);
        assertEquals("/path to/a.jpeg", tst1[0]);
        assertEquals("b.jpg", tst1[1]);
        assertEquals("/path to/c", tst1[2]);
        assertEquals("d.jpg", tst1[3]);
    }

    /**
     *  A unit test for JUnit
     */
    public void test_Commands_Logon() {
        Vector params;

        params = new Vector();
        params.add(new CommandParameter("u", "joe"));
        params.add(new CommandParameter("p", "C9@mPlX*"));
        model.doCommand("logon", params);
        assertTrue(model.getCollection(0) != null);
        assertTrue(model.getCollection(1) != null);
        assertEquals("Test PicCollection (id=0)", model.getCollection(0).getName());
        assertEquals("Joe's Photos", model.getCollection(1).getName());
        assertEquals("Joe's Photos 2", model.getCollection(2).getName());

        params = new Vector();
        params.add(new CommandParameter("u", "joe"));
        params.add(new CommandParameter("p", "badpass"));
        model.doCommand("logon", params);
        assertTrue(model.getCollection(0) != null);
        assertEquals("logon.jsp?username=joe", model.getCurrentPage());
        assertFalse(model.getUserName().equals("joe"));
        assertEquals(0, model.getCurrCollectionId());
        assertEquals("Test PicCollection (id=0)", model.getCollection(0).getName());

        params = new Vector();
        params.add(new CommandParameter("u", "guest"));
        params.add(new CommandParameter("p", "guestpass"));
        model.doCommand("logon", params);
        assertEquals("collections.jsp", model.getCurrentPage());
        assertTrue(model.getCollection(0) != null);
        assertTrue(model.getCollection(1) != null);
        assertEquals("Test PicCollection (id=0)", model.getCollection(0).getName());
        assertEquals("Test PicCollection (id=1)", model.getCollection(1).getName());
    }

    /**
     *  SelectCollection with valid parameter values
     */
    public void test_Commands_SelectCollection() {
        Vector params;
        model = ModelUtil.getModel("test_Command_SelectCollection");

        params = new Vector();
        params.add(new CommandParameter("id", "0"));
        model.doCommand("selectcollection", params);
        assertEquals(0, model.getCurrCollectionId());

        params = new Vector();
        params.add(new CommandParameter("id", "1"));
        model.doCommand("selectcollection", params);
        assertEquals(0, model.getCurrCollectionId());

        params = new Vector();
        params.add(new CommandParameter("u", "joe"));
        params.add(new CommandParameter("p", "C9@mPlX*"));
        model.doCommand("logon", params);
        assertTrue(model.getCollection(0) != null);
        assertTrue(model.getCollection(1) != null);
        params = new Vector();
        params.add(new CommandParameter("id", "1"));
        model.doCommand("selectcollection", params);
        assertEquals(1, model.getCurrCollectionId());

        params = new Vector();
        params.add(new CommandParameter("id", "0"));
        model.doCommand("selectcollection", params);
        assertEquals(0, model.getCurrCollectionId());

        params = new Vector();
        params.add(new CommandParameter("id", "3"));
        model.doCommand("selectcollection", params);
        assertEquals(0, model.getCurrCollectionId());
    }

    /**
     *  SelectCollection with invalid parameter values
     */
    public void test_Commands_SelectCollectionInvalid() {
        Vector params;
        model = ModelUtil.getModel("test_Command_SelectCollection");

        params = new Vector();
        params.add(new CommandParameter("id", "fail"));
        // needs to be error to print in maven test log
        log.error("Please ignore next error message, it is expected...");
        model.doCommand("selectcollection", params);
        assertEquals(0, model.getCurrCollectionId());
    }

    /**
     *  Test of ResourceBundle translation.
     */
    public void test_GinpModel_translate() {
        model.setLocale(new Locale("en"));
        assertEquals("Foo Bar", model.translate("testMessage"));

        model.setLocale(new Locale("de"));
        assertEquals("Foo Bar de", model.translate("testMessage"));
    }

    public void test_command_SetLanguageCode() {
        SetLanguageCode comm = new SetLanguageCode();
        Vector para = new Vector();

        para.add(new CommandParameter("code", "de_AT"));

        comm.action(model, para);
        assertEquals("Foo Bar de_AT", model.translate("testMessage"));

        para.clear();
        para.add(new CommandParameter("code", "de_FR"));
        comm.action(model, para);
        assertEquals("Foo Bar de", model.translate("testMessage"));
    }

    /**
     *  A unit test for JUnit
     */
    public void test_Model() {
        model = ModelUtil.getModel("new");

        assertEquals(model.getPageHeight(), 500);
        assertEquals(0, model.getCurrCollectionId());
        //assertEquals("collection.jsp", model.getCurrentPage());
        model.setPageHeight(123);
        assertEquals(model.getPageHeight(), 123);
        model.setPageWidth(123);
        assertEquals(model.getPageWidth(), 123);
        assertTrue(model.getCollection() != null);
    }

    /**
     *  A unit test for JUnit
     */
    public void test_ModelManager() {
        assertEquals(model, ModelUtil.getModel("test123"));
        assertNotSame(model, ModelUtil.getModel("test321"));
    }

    /**
     *  A unit test for JUnit
     */
    public void test_Model_pageDimensions() {
        assertEquals(200, Configuration.getThumbSize());
        assertEquals(600, model.getPageWidth());
    }

    /**
     *  processing variation for a good path and picture file
     */
    public void test_Picture() {
        // path must have a trailing separator
        Picture pic = new Picture(TEST_DIRECTORY + File.separator, PICTURE_FILE_NAME);
        assertEquals(PICTURE_FILE_NAME, pic.getFileName());
    }

    /**
     *  processing variation for a good picture file with
     *  path elements in both arguments
     */
    public void test_PictureFullName() {
        // filename with path ignores path argument (must use "/")
        final String PART1 = System.getProperty("java.io.tmpdir") + "/";
        final String PART2 = "TestGinpModel";
        final String BIG_NAME = PART2 + "/" + PICTURE_FILE_NAME;

        Picture pic = new Picture(PART1, BIG_NAME);

        assertEquals(PICTURE_FILE_NAME, pic.getFileName());
    }

    /**
     *  Picture data and time manipulation
     */
    public void test_Picture_setDateTime() {
        Picture pic = new Picture(TEST_DIRECTORY + File.separator, PICTURE_FILE_NAME);

        assertFalse(pic.setDateTime(": : : :"));
        assertFalse(pic.setDateTime(""));
        assertFalse(pic.setDateTime("03:08:25 11:35:09"));
        assertTrue(pic.setDateTime("2003:08:25 11:35:09"));
        assertEquals("2003.08.25", pic.getDate("", new Locale("en")));
        assertEquals("11:35:09", pic.getTime());
        assertTrue(pic.setDateTime("2004:10:20 13:01:59"));
        assertEquals("Wed 20.10.2004", pic.getDate("EEE dd.MM.yyyy", new Locale("en")));
        assertEquals("Mi 20.10.2004", pic.getDate("EEE dd.MM.yyyy", new Locale("de")));
    }

    /**
     *  Picture absolute location path tests
     */
    public void test_Picture_setAbsLocation() {
        Picture pic = new Picture(TEST_DIRECTORY + File.separator, PICTURE_FILE_NAME);

        assertEquals(PICTURE_FILE_LOCATION, pic.getAbsLocation());
        assertEquals(PICTURE_FILE_NAME, pic.getFileName());

        // doesn't actually rename the file...
        final String NEW_NAME = "newfilename.jpeg";
        final String NEW_PATH = "/newpath/to/picture/";
        final String NEW_FILENAME = NEW_PATH + NEW_NAME;
        pic.setAbsLocation(NEW_FILENAME);
        assertEquals(NEW_FILENAME, pic.getAbsLocation());
        assertEquals(NEW_NAME, pic.getFileName());
    }

    /**
     *  A unit test for JUnit
     */
    public void test_StringTool_getXMLTagContent() {
        assertEquals("content", StringTool.getXMLTagContent("tag", "<tag>content</tag>"));
        assertEquals(" content ", StringTool.getXMLTagContent("tag", "<tag> content </tag>"));
        assertEquals("content", StringTool.getXMLTagContent("tag", "bla<tag>content</tag>"));
        assertEquals("content", StringTool.getXMLTagContent("tag", "<tag>content</tag>bla"));
        //  assertEquals("content", StringTool.getXMLTagContent("tag", "<tag>content</tag><tag></tag>"));
        assertEquals(null, StringTool.getXMLTagContent("tag", "notag"));
    }

    /**
     *  A unit test for JUnit
     */
    public void test_StringTool_replace() {
        assertEquals("A+C", StringTool.replace("ABC", "B", "+"));
        assertEquals("ABBBBBBBBBBBC", StringTool.replace("ABC", "B", "BBBBBBBBBBB"));

        assertEquals("Abc", StringTool.replace("abc", "a", "A"));
        assertEquals("aBc", StringTool.replace("abc", "b", "B"));
        assertEquals("abC", StringTool.replace("abc", "c", "C"));
        assertEquals("abc", StringTool.replace("abc", "b", "b"));
        assertEquals("ABc", StringTool.replace("abc", "ab", "AB"));
        assertEquals("ABC", StringTool.replace("abc", "abc", "ABC"));
        assertEquals("abc", StringTool.replace("abc", "ABC", "ABC"));
        assertEquals("ABCABCABC", StringTool.replace("abcabcabc", "abc", "ABC"));
        assertEquals(" test, test,", StringTool.replace("test,test,", "test", " test"));
        assertEquals("test, test", StringTool.replace("test", "test", "test, test"));
    }

    /**
     *  A unit test for JUnit
     */
    public void test_StringTool_splitToArray() {
        String[] args1 = StringTool.splitToArray("2002:12:22 14:47:25", " ");
        assertEquals("2002:12:22", args1[0]);
        assertEquals("14:47:25", args1[1]);

        String[] args2 = StringTool.splitToArray(args1[0], ":");
        assertEquals("2002", args2[0]);
        assertEquals("12", args2[1]);
        assertEquals("22", args2[2]);

        String[] args3 = StringTool.splitToArray(args1[1], ":");
        assertEquals("14", args3[0]);
        assertEquals("47", args3[1]);
        assertEquals("25", args3[2]);

        assertEquals("hello", StringTool.splitToArray("hello", "|")[0]);
        assertEquals("hello", StringTool.splitToArray("hello|", "|")[0]);
        assertEquals("", StringTool.splitToArray("hello|", "|")[1]);
        assertEquals(" ", StringTool.splitToArray("hello| ", "|")[1]);
        assertEquals("hello ", StringTool.splitToArray("hello | ", "|")[0]);
        assertEquals(" world ", StringTool.splitToArray("hello | world |", "|")[1]);
        assertEquals("world", StringTool.splitToArray("hello |world|", "|")[1]);
        assertEquals("", StringTool.splitToArray("hello |world|", "|")[2]);
        assertEquals(" ", StringTool.splitToArray("hello |world| ", "|")[2]);
        assertEquals("hello", StringTool.splitToArray("hello | world | ", " | ")[0]);
        assertEquals("world", StringTool.splitToArray("hello | world | ", " | ")[1]);
        assertEquals("", StringTool.splitToArray("hello | world | ", " | ")[2]);
    }

    /**
     *  The JUnit setup method
     *
     *@throws  IOException
     *@throws  SetupException
     */
    protected void setUp() throws SetupException, IOException {
        // some setup is only needed once for all tests
        if (firstTime) {
            firstTime = false;

            // ensure the directory path exists for all test files
            setupTestDirectory();

            // now create a new config file for all tests
            setupTestConfig();

            // now copy a jpeg file for all tests
            setupTestJpeg();
        }

        Configuration.setConfigfilelocation(CONFIG_FILE_LOCATION);

        model = ModelUtil.getModel("anon");

        Vector params;

        model = ModelUtil.getModel("guest");
        params = new Vector();
        params.add(new CommandParameter("u", "guest"));
        params.add(new CommandParameter("p", "guestpass"));
        model.doCommand("logon", params);

        model = ModelUtil.getModel("joe");
        params = new Vector();
        params.add(new CommandParameter("u", "joe"));
        params.add(new CommandParameter("p", "C9@mPlX*"));
        model.doCommand("logon", params);

        model = ModelUtil.getModel("test123");
    }

    /**
     *  JUnit setup helper method
     *
     *@throws  IOException
     */
    private void setupTestDirectory() throws IOException {
        // ensure the directory path exists for all test files
        File testDir = new File(TEST_DIRECTORY);

        if (!testDir.exists()) {
            if (!testDir.mkdirs()) {
                log.warn("can not make test dir at: " + testDir.getAbsolutePath());
            }
        }
    }

    /**
     *  JUnit setup helper method
     *
     *@throws  IOException
     *@throws  SetupException
     */
    protected void setupTestConfig() throws IOException {
        // now create a new config file for all tests
        FileWriter fw = new FileWriter(CONFIG_FILE_LOCATION);
        fw.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<!DOCTYPE ginp [\n"
                + "    <!ELEMENT ginp ( collection*, user* ) >\n"
                + "    <!ELEMENT collection ( name, root, users, admins ) >\n" + "    <!ELEMENT user (#PCDATA)>\n"
                + "    <!ELEMENT name (#PCDATA)>\n" + "    <!ELEMENT root (#PCDATA)>\n"
                + "    <!ELEMENT users (username*)>\n" + "    <!ELEMENT username (#PCDATA)>\n"
                + "    <!ELEMENT admins (username*)>\n" + "    <!ATTLIST ginp forcelocale CDATA \"\">\n"
                + "    <!ATTLIST ginp thumbsize CDATA \"200\">\n"
                + "    <!ATTLIST ginp filmstripthumbsize CDATA \"100\">\n"
                + "    <!ATTLIST ginp picturepagename CDATA \"picture.jsp\">\n"
                + "    <!ATTLIST ginp collectionpagename CDATA \"collection.jsp\">\n"
                + "    <!ATTLIST user username CDATA #REQUIRED>\n"
                + "    <!ATTLIST user userpass CDATA #REQUIRED>\n" + "    <!ATTLIST user fullname CDATA \"\">\n"
                + "] >\n" + "<ginp>\n" + "    <collection>\n" + "      <name>Test PicCollection (id=0)</name>\n"
                + "      <root>/data/Photos/Demo</root>\n" + "        <users></users>\n"
                + "        <admins><username>admin</username></admins>\n" + "   </collection>\n"
                + "    <collection>\n" + "      <name>Test PicCollection (id=1)</name>\n"
                + "      <root>/data/Photos/Guest</root>\n"
                + "        <users><username>guest</username><username>TestUser</username></users>\n"
                + "        <admins><username>admin</username></admins>\n" + "   </collection>\n"
                + "    <collection>\n" + "      <name>Joe's Photos</name>\n" + "      <root>/data/Photos</root>\n"
                + "        <users><username>joe</username></users>\n"
                + "        <admins><username>joe</username><username>admin</username></admins>\n"
                + "   </collection>\n" + "    <collection>\n" + "      <name>Joe's Photos 2</name>\n"
                + "      <root>/data/Photos2</root>\n"
                + "        <users><username>joe</username><username>TestUser</username></users>\n"
                + "        <admins><username>admin</username><username>joe</username></admins>\n"
                + "   </collection>\n"
                + "   <user username=\"admin\" userpass=\"adminpass\" fullname=\"Administrator\" />\n"
                + "   <user username=\"guest\" userpass=\"guestpass\" fullname=\"Guest User\" />\n"
                + "   <user userpass=\"C9@mPlX*\" fullname=\"Joe Bloggs\" username=\"joe\"/>\n" + "</ginp>\n");
        fw.flush();
        fw.close();
    }

    /**
    *  JUnit setup helper method
    *
    *@throws  IOException
    *@throws  SetupException
    */
    protected void setupTestJpeg() {
        // grab the test jpeg from the testing classpath
        InputStream picture = this.getClass().getResourceAsStream(File.separator + PICTURE_FILE_NAME);
        FileOutputStream outPic = null;
        int size = 0;

        try {
            size = picture.available();

            if (size > 0) {
                byte[] buffer = new byte[size];
                int i = picture.read(buffer);

                outPic = new FileOutputStream(PICTURE_FILE_LOCATION);
                outPic.write(buffer);
                outPic.flush();
            }
        } catch (IOException ioe) {
            fail("cannot create test jpeg file:" + ioe);
        } finally {
            try {
                if (picture != null) {
                    picture.close();
                }

                if (outPic != null) {
                    outPic.close();
                }
            } catch (IOException ioe) {
                fail("error closing test jpeg file:" + ioe);
            }
        }
    }

    /**
       * do nothing at the end of a test case
       * @see junit.framework.TestCase#tearDown()
       */
    protected void tearDown() {
    }

    /**
     *  Description of the Method
     *
     *@param  args  Description of the Parameter
     */
    public static void main(String[] args) {
        junit.textui.TestRunner.run(TestGinpModel.class);

        File fl = new File(CONFIG_FILE_LOCATION);
        fl.delete();
    }
}