/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.loader;

import junit.textui.TestRunner;
import org.jboss.cache.TreeCache;

/**
 * A simple non-failing unit test to measure how many times each method on a cache loader is called.
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
 */
public class CacheLoaderMethodCallCounterTest extends AbstractCacheLoaderTestBase
{
    private TreeCache cache;
    private DummyCacheLoader dummyLoader;

    public static void main(String[] args)
    {
        TestRunner.run(CacheLoaderMethodCallCounterTest.class);
    }

    protected void setUp() throws Exception
    {
        if (cache != null) tearDown();
        cache = new TreeCache();
        cache.setCacheLoaderConfiguration(getSingleCacheLoaderConfig("", DummyCacheLoader.class.getName(), "", false, false, false));
        cache.startService();
        dummyLoader = (DummyCacheLoader) cache.getCacheLoader();
    }

    protected void tearDown()
    {
        if (cache != null)
        cache.stopService();
        cache.destroyService();
        cache = null;
    }


    public void testPut() throws Exception
    {
        cache.put("/node", "key", "value");
        printReport( "putKeyValue", dummyLoader );
    }

    public void testGet() throws Exception
    {
        cache.get("/node", "key");
        printReport( "getKey", dummyLoader );
    }

    public void testRemove() throws Exception
    {
        cache.remove("/node", "key");
        printReport( "removeKey", dummyLoader );
    }

    private void printReport(String test, DummyCacheLoader d)
    {
        System.out.println("------------------------------");
        System.out.println(" Test name: " + test);
        System.out.println("  cache loader stats:");
        System.out.println("   put count: " + d.getPutCount());
        System.out.println("   get count: " + d.getGetCount());
        System.out.println("   exists count: " + d.getExistsCount());
        System.out.println("   remove count: " + d.getRemoveCount());
        System.out.println("   getChildrenNames count: " + d.getGetChildrenNamesCount());
        System.out.println("------------------------------");
    }

    public void testLoopedGets() throws Exception
    {
        // put an object in cache
        cache.put("/test", "key", "value");

        // we should see this put in the cl
        assertEquals(1, dummyLoader.getPutCount());
        // the cloader interceptor does a get as well when doing the put ... ?
        assertEquals(0, dummyLoader.getGetCount());

        for (int i=0;i<2000; i++)
        {
            cache.get("/test");
        }

        assertEquals(1, dummyLoader.getPutCount());
        assertEquals(1, dummyLoader.getGetCount());
        assertEquals(0, dummyLoader.getRemoveCount());
        assertEquals(0, dummyLoader.getExistsCount());
    }
}
