1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.util;
17  
18  import java.util.HashSet;
19  import java.util.Set;
20  
21  import junit.framework.TestCase;
22  
23  import org.seasar.cubby.CubbyConstants;
24  import org.seasar.framework.mock.servlet.MockHttpSession;
25  import org.seasar.framework.mock.servlet.MockHttpSessionImpl;
26  import org.seasar.framework.mock.servlet.MockServletContextImpl;
27  import org.seasar.framework.util.LruHashMap;
28  
29  public class TokenHelperTest extends TestCase {
30  
31  	public void testGenerateGUID() throws Exception {
32  		final int count = 50000;
33  		Set<String> generatedGuids = new HashSet<String>();
34  		for (int i = 0; i < count; i++) {
35  			String guid = TokenHelper.generateGUID();
36  //			assertEquals("GUIDは32文字[" + guid + "]", 32, guid.length());
37  			assertNotNull(guid);
38  			assertTrue(guid.length() > 0);
39  			assertFalse("GUIDが重複した:" + guid, generatedGuids.contains(guid));
40  			generatedGuids.add(guid);
41  		}
42  		assertEquals(count, generatedGuids.size());
43  	}
44  
45  	public void testSetToken() throws Exception {
46  		String token = "tokenstring";
47  		MockHttpSession session = new MockHttpSessionImpl(new MockServletContextImpl("/cubby"));
48  		LruHashMap tokenMap = new LruHashMap(32);
49  		session.setAttribute(CubbyConstants.ATTR_TOKEN, tokenMap);
50  		TokenHelper.setToken(session, token);
51  
52  		assertTrue("トークン文字列がトークン用のMapのキーとして追加", tokenMap
53  				.containsKey("tokenstring"));
54  	}
55  
56  	public void testValidateToken() throws Exception {
57  		String token = "tokenstring";
58  		MockHttpSession session = new MockHttpSessionImpl(new MockServletContextImpl("/cubby"));
59  		LruHashMap tokenMap = new LruHashMap(32);
60  		session.setAttribute(CubbyConstants.ATTR_TOKEN, tokenMap);
61  		TokenHelper.setToken(session, token);
62  
63  		assertFalse("セッション中に存在しないトークン文字列", TokenHelper.validateToken(
64  				session, "dummytoken"));
65  		assertTrue("セッション中に存在するトークン文字列", TokenHelper.validateToken(
66  				session, "tokenstring"));
67  		assertFalse("1度validateTokenした後は指定したトークン文字列は除去されている", TokenHelper.validateToken(
68  				session, "tokenstring"));
69  	}
70  }