summaryrefslogtreecommitdiffstats
path: root/tests/Auth/SessionsTest.php
blob: 12ba621c3f126c0a54f6f1e5db4aeb71297d287b (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php

namespace Jasny\Auth;

use Jasny\Auth;
use PHPUnit_Framework_TestCase as TestCase;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use Jasny\TestHelper;

/**
 * @covers Jasny\Auth\Sessions
 */
class SessionsAuth extends TestCase
{
    use TestHelper;
    
    /**
     * @var Auth\Sessions|MockObject 
     */
    protected $auth;
    
    /**
     * @var string
     */
    protected $sessionModule;

    protected function mockSessionHandling()
    {
        // Mock sessions
        session_cache_limiter('');
        ini_set('session.use_cookies', 0);
        ini_set('session.use_only_cookies', 0);
        
        $this->sessionModule = session_module_name();

        $void = function () { return true; };
        $read = function () { return "a:0:{}"; };
        session_set_save_handler($void, $void, $read, $void, $void, $void);
        
        session_start();
    }
    
    protected function restoreSessionHandling()
    {
        session_abort();
        session_module_name($this->sessionModule);
    }
    
    
    public function setUp()
    {
        $this->auth = $this->getMockForTrait(Auth\Sessions::class);
        $this->mockSessionHandling();
    }
    
    public function tearDown()
    {
        $this->restoreSessionHandling();
    }
    
    
    public function testGetCurrentUserIdWithUser()
    {
        $_SESSION['auth_uid'] = 123;
        
        $id = $this->callPrivateMethod($this->auth, 'getCurrentUserId');
        $this->assertEquals(123, $id);
    }
    
    public function testGetCurrentUserIdWithoutUser()
    {
        $id = $this->callPrivateMethod($this->auth, 'getCurrentUserId');
        $this->assertNull($id);
    }
    
    
    public function testPersistCurrentUserWithUser()
    {
        $_SESSION['foo'] = 'bar';
        
        $user = $this->createMock(Auth\User::class);
        $user->method('getId')->willReturn(123);
        
        $this->auth->expects($this->once())->method('user')->willReturn($user);
        
        $this->callPrivateMethod($this->auth, 'persistCurrentUser');
        
        $this->assertEquals(['foo' => 'bar', 'auth_uid' => 123], $_SESSION);
    }
    
    public function testPersistCurrentUserWithoutUser()
    {
        $_SESSION['auth_uid'] = 123;
        $_SESSION['foo'] = 'bar';
        
        $this->auth->expects($this->once())->method('user')->willReturn(null);
        
        $this->callPrivateMethod($this->auth, 'persistCurrentUser');
        
        $this->assertEquals(['foo' => 'bar'], $_SESSION);
    }
}