3 namespace MediaWiki\Session
;
5 use Psr\Log\LoggerInterface
;
6 use Wikimedia\TestingAccessWrapper
;
9 * Utility functions for Session unit tests
14 * Override the singleton for unit testing
15 * @param SessionManager|null $manager
16 * @return \\Wikimedia\ScopedCallback|null
18 public static function setSessionManagerSingleton( SessionManager
$manager = null ) {
19 session_write_close();
21 $rInstance = new \
ReflectionProperty(
22 SessionManager
::class, 'instance'
24 $rInstance->setAccessible( true );
25 $rGlobalSession = new \
ReflectionProperty(
26 SessionManager
::class, 'globalSession'
28 $rGlobalSession->setAccessible( true );
29 $rGlobalSessionRequest = new \
ReflectionProperty(
30 SessionManager
::class, 'globalSessionRequest'
32 $rGlobalSessionRequest->setAccessible( true );
34 $oldInstance = $rInstance->getValue();
37 [ $rInstance, $oldInstance ],
38 [ $rGlobalSession, $rGlobalSession->getValue() ],
39 [ $rGlobalSessionRequest, $rGlobalSessionRequest->getValue() ],
42 $rInstance->setValue( $manager );
43 $rGlobalSession->setValue( null );
44 $rGlobalSessionRequest->setValue( null );
45 if ( $manager && PHPSessionHandler
::isInstalled() ) {
46 PHPSessionHandler
::install( $manager );
49 return new \Wikimedia\
ScopedCallback( function () use ( &$reset, $oldInstance ) {
50 foreach ( $reset as &$arr ) {
51 $arr[0]->setValue( $arr[1] );
53 if ( $oldInstance && PHPSessionHandler
::isInstalled() ) {
54 PHPSessionHandler
::install( $oldInstance );
60 * If you need a SessionBackend for testing but don't want to create a real
62 * @return SessionBackend Unconfigured! Use reflection to set any private
65 public static function getDummySessionBackend() {
66 $rc = new \
ReflectionClass( SessionBackend
::class );
67 if ( !method_exists( $rc, 'newInstanceWithoutConstructor' ) ) {
68 \PHPUnit_Framework_Assert
::markTestSkipped(
69 'ReflectionClass::newInstanceWithoutConstructor isn\'t available'
73 $ret = $rc->newInstanceWithoutConstructor();
74 TestingAccessWrapper
::newFromObject( $ret )->logger
= new \TestLogger
;
79 * If you need a Session for testing but don't want to create a backend to
80 * construct one, use this.
81 * @param object $backend Object to serve as the SessionBackend
82 * @param int $index Index
83 * @param LoggerInterface $logger
86 public static function getDummySession( $backend = null, $index = -1, $logger = null ) {
87 $rc = new \
ReflectionClass( Session
::class );
88 if ( !method_exists( $rc, 'newInstanceWithoutConstructor' ) ) {
89 \PHPUnit_Framework_Assert
::markTestSkipped(
90 'ReflectionClass::newInstanceWithoutConstructor isn\'t available'
94 if ( $backend === null ) {
95 $backend = new DummySessionBackend
;
98 $session = $rc->newInstanceWithoutConstructor();
99 $priv = TestingAccessWrapper
::newFromObject( $session );
100 $priv->backend
= $backend;
101 $priv->index
= $index;
102 $priv->logger
= $logger ?
: new \TestLogger
;