package com.wizzardo.tools;

import com.wizzardo.tools.cache.Cache;
import com.wizzardo.tools.cache.Computable;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author: moxa
 * Date: 9/27/13
 */
public class CacheTest {

    @Test
    public void simpleCache() {
        Cache<Integer, Integer> cache = new Cache<Integer, Integer>(1, new Computable<Integer, Integer>() {

            @Override
            public Integer compute(Integer s) {
                return new Integer(s * s);
            }
        });

        Assert.assertEquals(Integer.valueOf(4), cache.get(2));

        Integer cached = cache.get(16);
        Assert.assertTrue(cached == cache.get(16));

        try {
            Thread.sleep(1501);
        } catch (InterruptedException ignored) {
        }

        Assert.assertTrue(cached != cache.get(16));
    }

    @Test
    public void exceptions() {
        Cache<Integer, Integer> cache = new Cache<Integer, Integer>(0, new Computable<Integer, Integer>() {

            @Override
            public Integer compute(Integer s) {
                throw new RuntimeException();
            }
        });

        try {
            cache.get(1);
        } catch (Exception e) {
        }

        try {
            cache.get(1);
        } catch (Exception e) {
        }

    }

    @Test
    public void testTTL() throws InterruptedException {
        Cache<String, String> cache = new Cache<String, String>(1, new Computable<String, String>() {
            @Override
            public String compute(String s) {
                return s.toUpperCase();
            }
        });

        cache.get("foo", true);
        Thread.sleep(500);
        cache.get("bar");

        Thread.sleep(490);
        Assert.assertEquals(2, cache.size());

        Thread.sleep(500);
        Assert.assertEquals(1, cache.size());

        Thread.sleep(20);
        Assert.assertEquals(0, cache.size());
    }
}

@@ -1160,32 +1160,58 @@
   cache.get(1);%0A
+            assert false;%0A
         %7D catch 
@@ -1218,32 +1218,32 @@
 (Exception e) %7B%0A
-
         %7D%0A%0A     
@@ -1269,32 +1269,58 @@
   cache.get(1);%0A
+            assert false;%0A
         %7D catch 
@@ -1912,24 +1912,24 @@
 .sleep(20);%0A
-
         Asse
@@ -1967,11 +1967,552 @@
 );%0A    %7D
+%0A%0A    @Test%0A    public void testCustomTTL() throws InterruptedException %7B%0A        Cache%3CString, String%3E cache = new Cache%3CString, String%3E(1, new Computable%3CString, String%3E() %7B%0A            @Override%0A            public String compute(String s) %7B%0A                return s.toUpperCase();%0A            %7D%0A        %7D);%0A%0A        cache.get(%22foo%22);%0A%0A        String bar = %22BAR%22;%0A        cache.put(%22bar%22, bar, 500);%0A%0A        Assert.assertTrue(bar == cache.get(%22bar%22));%0A%0A        Thread.sleep(550);%0A%0A        Assert.assertTrue(bar != cache.get(%22bar%22));%0A    %7D
 %0A%7D%0A

add ttl test