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
28 package org.apache.hc.client5.http.impl.cookie;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.ByteArrayOutputStream;
32 import java.io.ObjectInputStream;
33 import java.io.ObjectOutputStream;
34 import java.util.Calendar;
35 import java.util.List;
36
37 import org.apache.hc.client5.http.cookie.BasicCookieStore;
38 import org.apache.hc.client5.http.cookie.Cookie;
39 import org.junit.Assert;
40 import org.junit.Test;
41
42
43
44
45 public class TestBasicCookieStore {
46
47 @Test
48 public void testBasics() throws Exception {
49 final BasicCookieStore store = new BasicCookieStore();
50 store.addCookie(new BasicClientCookie("name1", "value1"));
51 store.addCookies(new BasicClientCookie[] {new BasicClientCookie("name2", "value2")});
52 List<Cookie> list = store.getCookies();
53 Assert.assertNotNull(list);
54 Assert.assertEquals(2, list.size());
55 Assert.assertEquals("name1", list.get(0).getName());
56 Assert.assertEquals("name2", list.get(1).getName());
57 store.clear();
58 list = store.getCookies();
59 Assert.assertNotNull(list);
60 Assert.assertEquals(0, list.size());
61 }
62
63 @Test
64 public void testExpiredCookie() throws Exception {
65 final BasicCookieStore store = new BasicCookieStore();
66 final BasicClientCookie cookie = new BasicClientCookie("name1", "value1");
67
68 final Calendar c = Calendar.getInstance();
69 c.add(Calendar.DAY_OF_YEAR, -10);
70 cookie.setExpiryDate(c.getTime());
71 store.addCookie(cookie);
72 final List<Cookie> list = store.getCookies();
73 Assert.assertNotNull(list);
74 Assert.assertEquals(0, list.size());
75 }
76
77 @Test
78 public void testSerialization() throws Exception {
79 final BasicCookieStore orig = new BasicCookieStore();
80 orig.addCookie(new BasicClientCookie("name1", "value1"));
81 orig.addCookie(new BasicClientCookie("name2", "value2"));
82 final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
83 final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer);
84 outStream.writeObject(orig);
85 outStream.close();
86 final byte[] raw = outbuffer.toByteArray();
87 final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw);
88 final ObjectInputStream inStream = new ObjectInputStream(inBuffer);
89 final BasicCookieStore clone = (BasicCookieStore) inStream.readObject();
90 final List<Cookie> expected = orig.getCookies();
91 final List<Cookie> clones = clone.getCookies();
92 Assert.assertNotNull(expected);
93 Assert.assertNotNull(clones);
94 Assert.assertEquals(expected.size(), clones.size());
95 for (int i = 0; i < expected.size(); i++) {
96 Assert.assertEquals(expected.get(i).getName(), clones.get(i).getName());
97 Assert.assertEquals(expected.get(i).getValue(), clones.get(i).getValue());
98 }
99 }
100
101 }