Skip to content

Commit bea01e4

Browse files
add tests for CacheBasedSessionHandler (#55487)
1 parent 3ae99ee commit bea01e4

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\Session;
4+
5+
use Illuminate\Contracts\Cache\Repository as CacheContract;
6+
use Illuminate\Session\CacheBasedSessionHandler;
7+
use Mockery;
8+
use PHPUnit\Framework\TestCase;
9+
10+
class CacheBasedSessionHandlerTest extends TestCase
11+
{
12+
protected $cacheMock;
13+
14+
protected $sessionHandler;
15+
16+
protected function setUp(): void
17+
{
18+
parent::setUp();
19+
$this->cacheMock = Mockery::mock(CacheContract::class);
20+
$this->sessionHandler = new CacheBasedSessionHandler(cache: $this->cacheMock, minutes: 10);
21+
}
22+
23+
protected function tearDown(): void
24+
{
25+
Mockery::close();
26+
parent::tearDown();
27+
}
28+
29+
public function test_open()
30+
{
31+
$result = $this->sessionHandler->open('path', 'session_name');
32+
$this->assertTrue($result);
33+
}
34+
35+
public function test_close()
36+
{
37+
$result = $this->sessionHandler->close();
38+
$this->assertTrue($result);
39+
}
40+
41+
public function test_read_returns_data_from_cache()
42+
{
43+
$this->cacheMock->shouldReceive('get')->once()->with('session_id', '')->andReturn('session_data');
44+
45+
$data = $this->sessionHandler->read(sessionId: 'session_id');
46+
$this->assertEquals('session_data', $data);
47+
}
48+
49+
public function test_read_returns_empty_string_if_no_data()
50+
{
51+
$this->cacheMock->shouldReceive('get')->once()->with('some_id', '')->andReturn('');
52+
53+
$data = $this->sessionHandler->read(sessionId: 'some_id');
54+
$this->assertEquals('', $data);
55+
}
56+
57+
public function test_write_stores_data_in_cache()
58+
{
59+
$this->cacheMock->shouldReceive('put')->once()->with('session_id', 'session_data', 600) // 10 minutes in seconds
60+
->andReturn(true);
61+
62+
$result = $this->sessionHandler->write(sessionId: 'session_id', data: 'session_data');
63+
64+
$this->assertTrue($result);
65+
}
66+
67+
public function test_destroy_removes_data_from_cache()
68+
{
69+
$this->cacheMock->shouldReceive('forget')->once()->with('session_id')->andReturn(true);
70+
71+
$result = $this->sessionHandler->destroy(sessionId: 'session_id');
72+
73+
$this->assertTrue($result);
74+
}
75+
76+
public function test_gc_returns_zero()
77+
{
78+
$result = $this->sessionHandler->gc(lifetime: 120);
79+
80+
$this->assertEquals(0, $result);
81+
}
82+
83+
public function test_get_cache_returns_cache_instance()
84+
{
85+
$cacheInstance = $this->sessionHandler->getCache();
86+
87+
$this->assertSame($this->cacheMock, $cacheInstance);
88+
}
89+
}

0 commit comments

Comments
 (0)