LRUCacheTest.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Elgg\Cache;
  3. use PHPUnit_Framework_TestCase as TestCase;
  4. class LRUCacheTest extends TestCase {
  5. public function testOldestItemsGetDroppedWhenUnused() {
  6. $pool = new LRUCache(4);
  7. // foo1 gets dropped
  8. $pool->set('foo1', 10);
  9. $pool->set('foo2', 20);
  10. $pool['foo3'] = 30;
  11. $pool['foo4'] = 40;
  12. $pool->set('foo5', 50);
  13. $this->assertEquals(null, $pool->get('foo1'));
  14. $this->assertFalse(isset($pool['foo1']));
  15. $this->assertEquals(20, $pool->get('foo2'));
  16. $this->assertEquals(30, $pool->get('foo3'));
  17. $this->assertEquals(40, $pool['foo4']);
  18. $this->assertEquals(50, $pool['foo5']);
  19. $this->assertEquals(4, $pool->size());
  20. // remove item using unset
  21. unset($pool['foo4']);
  22. $this->assertFalse(isset($pool['foo4']));
  23. $this->assertEquals(null, $pool['foo4']);
  24. $this->assertEquals(3, $pool->size());
  25. // remove item using method
  26. $this->assertEquals(20, $pool->remove('foo2'));
  27. $this->assertEquals(2, $pool->size());
  28. $this->assertEquals(null, $pool->remove('foo2'));
  29. // clear the cache
  30. $pool->clear();
  31. $this->assertEquals(null, $pool['foo2']);
  32. $this->assertEquals(0, $pool->size());
  33. }
  34. public function testLeastUsedItemGetsDropped() {
  35. $pool = new LRUCache(2);
  36. $pool->set('foo1', 10);
  37. $pool->set('foo2', 25);
  38. $this->assertEquals(25, $pool->get('foo2'));
  39. $pool->set('foo2', 20);
  40. $this->assertEquals(20, $pool->get('foo2'));
  41. $this->assertEquals(10, $pool->get('foo1'));
  42. // foo2 was least recently read
  43. $pool->set('foo3', 30);
  44. $this->assertEquals(null, $pool->get('foo2'));
  45. $this->assertFalse(isset($pool['foo2']));
  46. $this->assertEquals(10, $pool->get('foo1'));
  47. $this->assertEquals(30, $pool->get('foo3'));
  48. $this->assertEquals(2, $pool->size());
  49. }
  50. public function testThrowExceptionOnNegativeSize() {
  51. $this->setExpectedException('\InvalidArgumentException');
  52. $pool = new LRUCache(-2);
  53. }
  54. public function testThrowExceptionOnNonIntSize() {
  55. $this->setExpectedException('\InvalidArgumentException');
  56. $pool = new LRUCache("abc");
  57. }
  58. }