package net.rubyeye.xmemcached.test.unittest.impl;

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;
import net.rubyeye.xmemcached.HashAlgorithm;
import net.rubyeye.xmemcached.MemcachedSessionLocator;
import net.rubyeye.xmemcached.impl.ArrayMemcachedSessionLocator;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.test.unittest.MockSession;

import com.google.code.yanf4j.core.Session;

public class SessionLocatorTest extends TestCase {
	MemcachedSessionLocator sessionLocator;

	public void testArraySessionLocator() {
		sessionLocator = new ArrayMemcachedSessionLocator();

		List<Session> sessions = new ArrayList<Session>();
		for (int i = 8080; i < 8100; i++) {
			sessions.add(new MockSession(i));
		}
		sessionLocator.updateSessions(sessions);
		for (int i = 1; i <= 10; i++) {
			String key = String.valueOf(i);
			int mod = key.hashCode() % sessions.size();
			assertSame(sessions.get(mod), sessionLocator.getSessionByKey(key));
		}

		String key = "test";
		int oldIndex = key.hashCode() % sessions.size();
		Session oldSession = sessions.get(oldIndex);

		assertSame(oldSession, sessionLocator.getSessionByKey(key));
		// close old session
		oldSession.close();
		assertNotSame(oldSession, sessionLocator.getSessionByKey(key));
		// use next
		assertSame(sessions.get(oldIndex + 1), sessionLocator
				.getSessionByKey(key));
		sessions = new ArrayList<Session>();
		sessionLocator.updateSessions(sessions);
		assertNull(sessionLocator.getSessionByKey(key));
	}

	public void testKetamaMemcachedSessionLocator() {
		sessionLocator = new KetamaMemcachedSessionLocator(
				HashAlgorithm.NATIVE_HASH);
		List<Session> sessions = new ArrayList<Session>();
		for (int i = 8080; i < 8100; i++) {
			sessions.add(new MockSession(i));
		}
		sessionLocator.updateSessions(sessions);
		for (int i = 1; i <= 10; i++) {
			String key = String.valueOf(i);

			assertSame(((KetamaMemcachedSessionLocator) sessionLocator)
					.getSessionByHash(key.hashCode()), sessionLocator
					.getSessionByKey(key));
		}

	}

}

@@ -1992,16 +1992,75 @@
 (i);%0D%0A%0D%0A
+%09%09%09Session session = sessionLocator.getSessionByKey(key);%0D%0A
 %09%09%09asser
@@ -2166,22 +2166,102 @@
 sion
+);%0D%0A%09%09%09assertSame(sessionLocator.getSessionByKey(key), session);%0D%0A%09%09%09assertSame(session
 Locator
-%0D%0A%09%09%09%09%09
 .get
@@ -2269,32 +2269,41 @@
 essionByKey(key)
+, session
 );%0D%0A%09%09%7D%0D%0A%0D%0A%09%7D%0D%0A%0D

Add more assert to make sure sessionLocator return same session.