6 class HashBagOStuffTest
extends PHPUnit_Framework_TestCase
{
8 public function testDelete() {
9 $cache = new HashBagOStuff();
10 for ( $i = 0; $i < 10; $i++
) {
11 $cache->set( "key$i", 1 );
12 $this->assertEquals( 1, $cache->get( "key$i" ) );
13 $cache->delete( "key$i" );
14 $this->assertEquals( false, $cache->get( "key$i" ) );
18 public function testClear() {
19 $cache = new HashBagOStuff();
20 for ( $i = 0; $i < 10; $i++
) {
21 $cache->set( "key$i", 1 );
22 $this->assertEquals( 1, $cache->get( "key$i" ) );
25 for ( $i = 0; $i < 10; $i++
) {
26 $this->assertEquals( false, $cache->get( "key$i" ) );
30 public function testExpire() {
31 $cache = new HashBagOStuff();
32 $cacheInternal = TestingAccessWrapper
::newFromObject( $cache );
33 $cache->set( 'foo', 1 );
34 $cache->set( 'bar', 1, 10 );
35 $cache->set( 'baz', 1, -10 );
37 $this->assertEquals( 0, $cacheInternal->bag
['foo'][$cache::KEY_EXP
], 'Indefinite' );
38 // 2 seconds tolerance
39 $this->assertEquals( time() +
10, $cacheInternal->bag
['bar'][$cache::KEY_EXP
], 'Future', 2 );
40 $this->assertEquals( time() - 10, $cacheInternal->bag
['baz'][$cache::KEY_EXP
], 'Past', 2 );
42 $this->assertEquals( 1, $cache->get( 'bar' ), 'Key not expired' );
43 $this->assertEquals( false, $cache->get( 'baz' ), 'Key expired' );
47 * Ensure maxKeys eviction prefers keeping new keys.
49 public function testEvictionAdd() {
50 $cache = new HashBagOStuff( array( 'maxKeys' => 10 ) );
51 for ( $i = 0; $i < 10; $i++
) {
52 $cache->set( "key$i", 1 );
53 $this->assertEquals( 1, $cache->get( "key$i" ) );
55 for ( $i = 10; $i < 20; $i++
) {
56 $cache->set( "key$i", 1 );
57 $this->assertEquals( 1, $cache->get( "key$i" ) );
58 $this->assertEquals( false, $cache->get( "key" . $i - 10 ) );
63 * Ensure maxKeys eviction prefers recently set keys
64 * even if the keys pre-exist.
66 public function testEvictionSet() {
67 $cache = new HashBagOStuff( array( 'maxKeys' => 3 ) );
69 foreach ( array( 'foo', 'bar', 'baz' ) as $key ) {
70 $cache->set( $key, 1 );
74 $cache->set( 'foo', 1 );
76 // Add a 4th key (beyond the allowed maximum)
77 $cache->set( 'quux', 1 );
79 // Foo's life should have been extended over Bar
80 foreach ( array( 'foo', 'baz', 'quux' ) as $key ) {
81 $this->assertEquals( 1, $cache->get( $key ), "Kept $key" );
83 $this->assertEquals( false, $cache->get( 'bar' ), 'Evicted bar' );
87 * Ensure maxKeys eviction prefers recently retrieved keys (LRU).
89 public function testEvictionGet() {
90 $cache = new HashBagOStuff( array( 'maxKeys' => 3 ) );
92 foreach ( array( 'foo', 'bar', 'baz' ) as $key ) {
93 $cache->set( $key, 1 );
97 $cache->get( 'foo', 1 );
99 // Add a 4th key (beyond the allowed maximum)
100 $cache->set( 'quux', 1 );
102 // Foo's life should have been extended over Bar
103 foreach ( array( 'foo', 'baz', 'quux' ) as $key ) {
104 $this->assertEquals( 1, $cache->get( $key ), "Kept $key" );
106 $this->assertEquals( false, $cache->get( 'bar' ), 'Evicted bar' );