1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.impl.client.cache.memcached;
28
29 import static org.junit.Assert.assertEquals;
30 import static org.junit.Assert.assertNotNull;
31 import static org.junit.Assert.assertNull;
32 import static org.junit.Assert.assertTrue;
33
34 import java.io.ByteArrayOutputStream;
35 import java.io.IOException;
36
37 import org.apache.http.client.cache.HttpCacheEntry;
38 import org.apache.http.impl.client.cache.DefaultHttpCacheEntrySerializer;
39 import org.apache.http.impl.client.cache.HttpTestUtils;
40 import org.junit.Before;
41 import org.junit.Test;
42
43
44 public class TestMemcachedCacheEntryImpl {
45
46 private MemcachedCacheEntryImpl impl;
47 private HttpCacheEntry entry;
48
49 @Before
50 public void setUp() {
51 entry = HttpTestUtils.makeCacheEntry();
52 impl = new MemcachedCacheEntryImpl("foo", entry);
53 }
54
55 @Test
56 public void canBeCreatedEmpty() {
57 impl = new MemcachedCacheEntryImpl();
58 assertNull(impl.getStorageKey());
59 assertNull(impl.getHttpCacheEntry());
60 }
61
62 @Test
63 public void canBeSerialized() {
64 final byte[] bytes = impl.toByteArray();
65 assertNotNull(bytes);
66 assertTrue(bytes.length > 0);
67 }
68
69 @Test
70 public void knowsItsCacheKey() {
71 assertEquals("foo", impl.getStorageKey());
72 }
73
74 @Test
75 public void knowsItsCacheEntry() {
76 assertEquals(entry, impl.getHttpCacheEntry());
77 }
78
79 @Test
80 public void canBeReconstitutedFromByteArray() throws Exception {
81 final String key = impl.getStorageKey();
82 final HttpCacheEntry entry1 = impl.getHttpCacheEntry();
83 final byte[] bytes = impl.toByteArray();
84 impl = new MemcachedCacheEntryImpl();
85 impl.set(bytes);
86
87 assertEquals(key, impl.getStorageKey());
88 assertEquivalent(entry1, impl.getHttpCacheEntry());
89 }
90
91 @Test(expected=MemcachedSerializationException.class)
92 public void cannotReconstituteFromGarbage() {
93 impl = new MemcachedCacheEntryImpl();
94 final byte[] bytes = HttpTestUtils.getRandomBytes(128);
95 impl.set(bytes);
96 }
97
98 private void assertEquivalent(final HttpCacheEntry entry,
99 final HttpCacheEntry resultEntry) throws IOException {
100
101
102
103
104
105
106
107
108 final DefaultHttpCacheEntrySerializer ser = new DefaultHttpCacheEntrySerializer();
109 final ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
110 ser.writeTo(entry, bos1);
111 final byte[] bytes1 = bos1.toByteArray();
112 final ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
113 ser.writeTo(resultEntry, bos2);
114 final byte[] bytes2 = bos2.toByteArray();
115 assertEquals(bytes1.length, bytes2.length);
116 for(int i = 0; i < bytes1.length; i++) {
117 assertEquals(bytes1[i], bytes2[i]);
118 }
119 }
120 }