<commit_before>/*********************************************************************************
 * Copyright 2015-present trivago GmbH
 * 
 * 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 com.trivago.triava.tcache;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Collection;
import java.util.Random;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import com.trivago.triava.tcache.core.Builder;
import com.trivago.triava.tcache.eviction.Cache;
import com.trivago.triava.tcache.eviction.Cache.AccessTimeObjectHolder;
import com.trivago.triava.tcache.statistics.TCacheStatistics;

/**
 * Tests for tCache operations, and behavior like eviction
 * @author cesken
 *
 */
public class CacheTest
{
	private static final long maxIdleTime = 100L;
	private static final long maxCacheTime = 1000L;
	private static Cache<String, Integer> cache = createCache("CacheTest", maxIdleTime, maxCacheTime, 10);

	boolean runAcceptanceTests = false;

	
	@AfterClass
	public static void tearDown()
	{
		// Not closing, as there is another unit test that also uses the TCacheFactory.standardFactory() 
		//TCacheFactory.standardFactory().close();
	}
	
	@Before
	public void setUpEach()
	{
		cache = TCacheFactory.standardFactory().<String,Integer>builder().setExpectedMapSize(10).setMaxCacheTime(maxCacheTime).setMaxIdleTime(maxIdleTime) .build();
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
	}
	
	@Test
	public void testCacheConstructor()
	{
		try
		{
			//Test constructor with all parameters and idle time
			Cache<String, Integer> tmpCache = createCache("CacheTest-1", maxIdleTime, maxCacheTime, 10);

			assertEquals("Cache idle time not set correctly", maxIdleTime, tmpCache.getDefaultMaxIdleTime());
		}
		catch (Exception e)
		{
			fail(e.getMessage());
		}
	}

	private static Cache<String, Integer> createCache(String id, long idleTime, long cacheTime, int size)
	{
		Builder<String, Integer> cacheB = TCacheFactory.standardFactory().builder();
		cacheB.setId(id);
		cacheB	.setMaxIdleTime(idleTime)
                .setMaxCacheTime(cacheTime)
                .setExpectedMapSize(size);

		return cacheB.build();
	}

	@Test
	public void testCacheConstructorDefaultIdle()
	{
		try
		{	
			//Test constructor with all parameters and idle time
			Cache<String, Integer> tmpCache = createCache("CacheTest-2", 0, maxCacheTime, 10);

			assertEquals("Cache object should have idle time of 1800", 1800, tmpCache.getDefaultMaxIdleTime());
		}
		catch (Exception e)
		{
			fail(e.getMessage());
		}
	}
	
	@Test
	public void expireCacheEntry()
	{
		Cache<String, Integer> cache1 = createCache("CacheTest-autoCleanCacheEntry", 1, 1, 10);

		assertTrue("Cache is not empty at start of test",  cache1.size() == 0);
		
		
		String key = "key-a";
		Integer value = 1;
		
		cache1.put(key, value);
		assertEquals("Retrieved value do not match.", value, cache1.get(key));
		try 
		{
			Thread.sleep(1400);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		assertTrue("Cache is not empty after sleep",  cache1.size() == 0);
	}
	
	@Test
	public void putIfAbsent()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-b";
		Integer value = 1;
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		assertEquals("Retrived value do not match.", value, cache.get(key));
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		assertEquals("Retrived value do not match.", value, cache.get(key));
	}
	
	@Test
	public void removeEntry()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-c";
		Integer value = 1;
		
		// Add key-value
		cache.put(key, value, 5L, 5L);
		
		assertTrue("Cache is not empty at start of test", cache.size() == 1);
		assertEquals("Retrived value do not match.", value, cache.get(key));
		
		// Remove existing key-value
		Integer removedValue = (Integer) cache.remove(key);
		
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		assertEquals("Removed value do not match.", value, removedValue);
		
		// Remove non existing key-value
		Integer nullValue = (Integer) cache.remove("_non_existent_key_");
		
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		assertNull("Found value when removing a non existent key.", nullValue);
	}
	
	@Test
	public void testDefaultAccessTimeOjectHolder()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-a";
		Integer value = 1;
//		long lastAccess = 0L;
		long inputDate = 0L;
		
		inputDate = System.currentTimeMillis();
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		
		Collection<AccessTimeObjectHolder<Integer>> list = cache.getAccessTimeHolderObjects();
		
		assertTrue("List should contain exactly one holder", !list.isEmpty() && list.size() == 1);
		
		AccessTimeObjectHolder<Integer> holder = list.iterator().next(); // Get  first (and only) element
		
		holder.setMaxIdleTime(2);
		
		assertEquals("Value does not match", 2, holder.getMaxIdleTime());
		assertEquals("Value does not match", value, holder.peek());
		assertEquals("Value does not match", 1, holder.getUseCount());
		
		holder.get();
//		lastAccess = System.currentTimeMillis();
		
//		assertEquals((System.currentTimeMillis() - lastAccess) / 1000.0, holder.getIdleTime(), 0.5);
		assertEquals(inputDate, holder.getInputDate(), 0);
		
	}
	
	@Test
	public void testGetAccessTimeHolderObjects()<commit_msg>SRT-28657 Code cleanup<commit_after>/*********************************************************************************
 * Copyright 2015-present trivago GmbH
 * 
 * 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 com.trivago.triava.tcache;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Collection;
import java.util.Random;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import com.trivago.triava.tcache.core.Builder;
import com.trivago.triava.tcache.eviction.Cache;
import com.trivago.triava.tcache.eviction.Cache.AccessTimeObjectHolder;
import com.trivago.triava.tcache.statistics.TCacheStatistics;

/**
 * Tests for tCache operations, and behavior like eviction
 * @author cesken
 *
 */
public class CacheTest
{
	private static final long maxIdleTime = 100L;
	private static final long maxCacheTime = 1000L;
	private static Cache<String, Integer> cache = createCache("CacheTest", maxIdleTime, maxCacheTime, 10);

	boolean runAcceptanceTests = false;

	
	@AfterClass
	public static void tearDown()
	{
		// Not closing, as there is another unit test that also uses the TCacheFactory.standardFactory() 
		//TCacheFactory.standardFactory().close();
	}
	
	@Before
	public void setUpEach()
	{
		cache = TCacheFactory.standardFactory().<String,Integer>builder().setExpectedMapSize(10).setMaxCacheTime(maxCacheTime).setMaxIdleTime(maxIdleTime) .build();
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
	}
	
	@Test
	public void testCacheConstructor()
	{
		try
		{
			//Test constructor with all parameters and idle time
			Cache<String, Integer> tmpCache = createCache("CacheTest-1", maxIdleTime, maxCacheTime, 10);

			assertEquals("Cache idle time not set correctly", maxIdleTime, tmpCache.getDefaultMaxIdleTime());
		}
		catch (Exception e)
		{
			fail(e.getMessage());
		}
	}

	private static Cache<String, Integer> createCache(String id, long idleTime, long cacheTime, int size)
	{
		Builder<String, Integer> cacheB = TCacheFactory.standardFactory().builder();
		cacheB.setId(id);
		cacheB	.setMaxIdleTime(idleTime)
                .setMaxCacheTime(cacheTime)
                .setExpectedMapSize(size);

		return cacheB.build();
	}

	@Test
	public void testCacheConstructorDefaultIdle()
	{
		try
		{	
			//Test constructor with all parameters and idle time
			Cache<String, Integer> tmpCache = createCache("CacheTest-2", 0, maxCacheTime, 10);

			assertEquals("Cache object should have idle time of 1800", 1800, tmpCache.getDefaultMaxIdleTime());
		}
		catch (Exception e)
		{
			fail(e.getMessage());
		}
	}
	
	@Test
	public void expireCacheEntry()
	{
		Cache<String, Integer> cache1 = createCache("CacheTest-autoCleanCacheEntry", 1, 1, 10);

		assertTrue("Cache is not empty at start of test",  cache1.size() == 0);
		
		
		String key = "key-a";
		Integer value = 1;
		
		cache1.put(key, value);
		assertEquals("Retrieved value do not match.", value, cache1.get(key));
		try 
		{
			Thread.sleep(1400);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		assertTrue("Cache is not empty after sleep",  cache1.size() == 0);
	}
	
	@Test
	public void putIfAbsent()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-b";
		Integer value = 1;
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		assertEquals("Retrived value do not match.", value, cache.get(key));
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		assertEquals("Retrived value do not match.", value, cache.get(key));
	}
	
	@Test
	public void removeEntry()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-c";
		Integer value = 1;
		
		// Add key-value
		cache.put(key, value, 5L, 5L);
		
		assertTrue("Cache is not empty at start of test", cache.size() == 1);
		assertEquals("Retrived value do not match.", value, cache.get(key));
		
		// Remove existing key-value
		Integer removedValue = (Integer) cache.remove(key);
		
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		assertEquals("Removed value do not match.", value, removedValue);
		
		// Remove non existing key-value
		Integer nullValue = (Integer) cache.remove("_non_existent_key_");
		
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		assertNull("Found value when removing a non existent key.", nullValue);
	}
	
	@Test
	public void testDefaultAccessTimeOjectHolder()
	{
		assertTrue("Cache is not empty at start of test",  cache.size() == 0);
		
		String key = "key-a";
		Integer value = 1;
		long inputDate = System.currentTimeMillis();
		
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		cache.putIfAbsent(key, value, maxIdleTime, maxCacheTime);
		
		Collection<AccessTimeObjectHolder<Integer>> list = cache.getAccessTimeHolderObjects();
		
		assertTrue("List should contain exactly one holder", !list.isEmpty() && list.size() == 1);
		
		AccessTimeObjectHolder<Integer> holder = list.iterator().next(); // Get  first (and only) element
		
		holder.setMaxIdleTime(2);
		
		assertEquals("Value does not match", 2, holder.getMaxIdleTime());
		assertEquals("Value does not match", value, holder.peek());
		assertEquals("Value does not match", 1, holder.getUseCount());
		
		holder.get();
//		lastAccess = System.currentTimeMillis();
		
//		assertEquals((System.currentTimeMillis() - lastAccess) / 1000.0, holder.getIdleTime(), 0.5);
		assertEquals(inputDate, holder.getInputDate(), 0);
		
	}
	
	@Test
	public void testGetAccessTimeHolderObjects()
{'fraction_non_alphanumeric': 0.14090189873417722, 'fraction_numerical': 0.0122626582278481, 'mean_word_length': 4.271476230191826, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2764382', 'n_tokens_mistral': 4197, 'n_tokens_neox': 3711, 'n_words': 1106}