Umesh Krishnaswamy | 345ee99 | 2012-12-13 20:29:48 -0800 | [diff] [blame] | 1 | package net.floodlightcontroller.util; |
| 2 | |
| 3 | import static org.junit.Assert.*; |
| 4 | |
| 5 | import org.junit.Before; |
| 6 | import org.junit.Test; |
| 7 | |
| 8 | public class TimedCacheTest { |
| 9 | public static class CacheEntry { |
| 10 | public int key; |
| 11 | |
| 12 | public CacheEntry(int key) { |
| 13 | this.key = key; |
| 14 | } |
| 15 | |
| 16 | @Override |
| 17 | public int hashCode() { |
| 18 | final int prime = 31; |
| 19 | int result = 1; |
| 20 | result = prime * result + key; |
| 21 | return result; |
| 22 | } |
| 23 | |
| 24 | @Override |
| 25 | public boolean equals(Object obj) { |
| 26 | if (this == obj) |
| 27 | return true; |
| 28 | if (obj == null) |
| 29 | return false; |
| 30 | if (getClass() != obj.getClass()) |
| 31 | return false; |
| 32 | CacheEntry other = (CacheEntry) obj; |
| 33 | if (key != other.key) |
| 34 | return false; |
| 35 | return true; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | protected TimedCache<CacheEntry> cache; |
| 40 | |
| 41 | @Before |
| 42 | public void setUp() { |
| 43 | // |
| 44 | } |
| 45 | |
| 46 | |
| 47 | @Test |
| 48 | public void testCaching() throws InterruptedException { |
| 49 | int timeout = 50; |
| 50 | int timeToSleep = 60; |
| 51 | cache = new TimedCache<TimedCacheTest.CacheEntry>(100, timeout); |
| 52 | |
| 53 | CacheEntry e1a = new CacheEntry(1); |
| 54 | CacheEntry e1b = new CacheEntry(1); |
| 55 | CacheEntry e1c = new CacheEntry(1); |
| 56 | CacheEntry e2 = new CacheEntry(2); |
| 57 | |
| 58 | assertEquals(false, cache.update(e1a)); |
| 59 | assertEquals(true, cache.update(e1a)); |
| 60 | assertEquals(true, cache.update(e1b)); |
| 61 | assertEquals(true, cache.update(e1c)); |
| 62 | assertEquals(false, cache.update(e2)); |
| 63 | assertEquals(true, cache.update(e2)); |
| 64 | |
| 65 | Thread.sleep(timeToSleep); |
| 66 | assertEquals(false, cache.update(e1a)); |
| 67 | assertEquals(false, cache.update(e2)); |
| 68 | } |
| 69 | |
| 70 | @Test |
| 71 | public void testCapacity() throws InterruptedException { |
| 72 | int timeout = 5000; |
| 73 | cache = new TimedCache<TimedCacheTest.CacheEntry>(2, timeout); |
| 74 | |
| 75 | // Testing the capacity is tricky since the capacity can be |
| 76 | // exceeded for short amounts of time, so we try to flood the cache |
| 77 | // to make sure the first entry is expired |
| 78 | CacheEntry e1 = new CacheEntry(1); |
| 79 | for (int i=0; i < 100; i++) { |
| 80 | CacheEntry e = new CacheEntry(i); |
| 81 | cache.update(e); |
| 82 | } |
| 83 | |
| 84 | // entry 1 should have been expired due to capacity limits |
| 85 | assertEquals(false, cache.update(e1)); |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | } |