3 namespace MediaWiki\Tests\Session
;
5 use MediaWiki\Session\PHPSessionHandler
;
6 use MediaWiki\Session\Session
;
7 use MediaWiki\Session\SessionBackend
;
8 use MediaWiki\Session\SessionManager
;
9 use PHPUnit\Framework\Assert
;
10 use Psr\Log\LoggerInterface
;
13 use Wikimedia\ScopedCallback
;
14 use Wikimedia\TestingAccessWrapper
;
17 * Utility functions for Session unit tests
22 * Override the singleton for unit testing
23 * @param SessionManager|null $manager
24 * @return ScopedCallback|null
26 public static function setSessionManagerSingleton( ?SessionManager
$manager = null ) {
27 session_write_close();
29 $staticAccess = TestingAccessWrapper
::newFromClass( SessionManager
::class );
31 $oldInstance = $staticAccess->instance
;
34 [ 'instance', $oldInstance ],
35 [ 'globalSession', $staticAccess->globalSession
],
36 [ 'globalSessionRequest', $staticAccess->globalSessionRequest
],
39 $staticAccess->instance
= $manager;
40 $staticAccess->globalSession
= null;
41 $staticAccess->globalSessionRequest
= null;
42 if ( $manager && PHPSessionHandler
::isInstalled() ) {
43 PHPSessionHandler
::install( $manager );
46 return new ScopedCallback( static function () use ( $reset, $staticAccess, $oldInstance ) {
47 foreach ( $reset as [ $property, $oldValue ] ) {
48 $staticAccess->$property = $oldValue;
50 if ( $oldInstance && PHPSessionHandler
::isInstalled() ) {
51 PHPSessionHandler
::install( $oldInstance );
57 * If you need a SessionBackend for testing but don't want to create a real
59 * @return SessionBackend Unconfigured! Use reflection to set any private
62 public static function getDummySessionBackend() {
63 $rc = new ReflectionClass( SessionBackend
::class );
64 if ( !method_exists( $rc, 'newInstanceWithoutConstructor' ) ) {
65 Assert
::markTestSkipped(
66 'ReflectionClass::newInstanceWithoutConstructor isn\'t available'
70 $ret = $rc->newInstanceWithoutConstructor();
71 TestingAccessWrapper
::newFromObject( $ret )->logger
= new TestLogger
;
76 * If you need a Session for testing but don't want to create a backend to
77 * construct one, use this.
78 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
79 * @param object|null $backend Object to serve as the SessionBackend
81 * @param LoggerInterface|null $logger
84 public static function getDummySession( $backend = null, $index = -1, $logger = null ) {
85 $rc = new ReflectionClass( Session
::class );
87 $session = $rc->newInstanceWithoutConstructor();
88 $priv = TestingAccessWrapper
::newFromObject( $session );
89 $priv->backend
= $backend ??
new DummySessionBackend();
90 $priv->index
= $index;
91 $priv->logger
= $logger ??
new TestLogger();