/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.ee;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import junit.framework.TestCase;

import woolpack.ee.mock.MockServletContext;

public class ServletContextMapTest extends TestCase {
	private final Map<String, Object> actualMap = new HashMap<String, Object>();

	private final Map<String, Object> map = new ServletContextMap(
			new MockServletContext() {
				public Object getAttribute(final String arg0) {
					return actualMap.get(arg0);
				}

				public Enumeration getAttributeNames() {

					return new Enumeration() {
						private final Iterator it = actualMap.keySet()
								.iterator();

						public boolean hasMoreElements() {
							return it.hasNext();
						}

						public Object nextElement() {
							return it.next();
						}

					};
				}

				public void setAttribute(final String arg0, final Object arg1) {
					actualMap.put(arg0, arg1);
				}

				public void removeAttribute(final String arg0) {
					actualMap.remove(arg0);
				}
			});

	public void testNormal0() {
		map.put("1", "value1");
		assertEquals("value1", map.get("1"));
		map.put("2", "value2");
		assertEquals("value2", map.get("2"));
		map.put("1", "Value1");
		assertEquals("Value1", map.get("1"));
		map.remove("1");
		assertNull(map.get("1"));
		map.remove("2");
		assertNull(map.get("2"));
	}

	public void testNormal1() {
		actualMap.put("key0", "value0");
		actualMap.put("key1", "value1");

		for (final Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
			final String key = it.next();
			if (key.equals("key0")) {
				assertEquals("value0", map.get(key));
			} else if (key.equals("key1")) {
				assertEquals("value1", map.get(key));
			} else {
				fail();
			}
		}
	}

	public void testKeySet() {
		map.put("1", "value1");
		final Set<String> set = map.keySet();
		assertEquals(1, set.size());

		for (final Iterator<String> it = set.iterator(); it.hasNext();) {
			final String key = it.next();
			assertEquals("value1", map.get(key));
			it.remove();
		}
		assertEquals(0, set.size());
	}
}
