Debian Codegraph @

tests/phpunit/MediaWikiUnitTestCase.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Testing
20 */
21
22 use MediaWiki\Config\ConfigException;
23 use MediaWiki\Config\HashConfig;
24 use MediaWiki\Deferred\DeferredUpdates;
25 use MediaWiki\Deferred\DeferredUpdatesScopeMediaWikiStack;
26 use MediaWiki\Deferred\DeferredUpdatesScopeStack;
27 use MediaWiki\Logger\LoggerFactory;
28 use MediaWiki\Logger\NullSpi;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\Registration\ExtensionRegistry;
31 use MediaWiki\Settings\SettingsBuilder;
32 use PHPUnit\Framework\Exception;
33 use PHPUnit\Framework\TestCase;
34 use Wikimedia\ObjectFactory\ObjectFactory;
35 use Wikimedia\Services\NoSuchServiceException;
36
37 /**
38 * Base class for unit tests.
39 *
40 * Extend this class if you are testing classes which use dependency injection and do not access
41 * global functions, variables, services or a storage backend.
42 *
43 * @stable to extend
44 * @since 1.34
45 */
46 abstract class MediaWikiUnitTestCase extends TestCase {
47 use MediaWikiCoversValidator;
48 use MediaWikiTestCaseTrait;
49
50 /** @var array */
51 private static $originalGlobals;
52 /** @var array */
53 private static $unitGlobals;
54
55 private ?MediaWikiServices $serviceContainer = null;
56
57 /**
58 * @var array<string,object>
59 */
60 private array $services = [];
61
62 /**
63 * List of allowed globals to allow in MediaWikiUnitTestCase.
64 *
65 * Please, keep this list to the bare minimum.
66 *
67 * @return string[]
68 */
69 private static function getAllowedGlobalsList() {
70 return [
71 // The autoloader may change between bootstrap and the first test,
72 // so (lazily) capture these here instead.
73 'wgAutoloadClasses',
74 'wgAutoloadLocalClasses',
75 // Need for LoggerFactory. Default is NullSpi.
76 'wgMWLoggerDefaultSpi',
77 'wgLegalTitleChars',
78 'wgDevelopmentWarnings',
79 // Dependency of wfParseUrl()
80 'wgUrlProtocols',
81 // For LegacyLogger, injected by DevelopmentSettings.php
82 'wgDebugLogFile',
83 'wgDebugLogGroups',
84 ];
85 }
86
87 /**
88 * The annotation causes this to be called immediately before setUpBeforeClass()
89 * @beforeClass
90 */
91 final public static function mediaWikiSetUpBeforeClass(): void {
92 $reflection = new ReflectionClass( static::class );
93 $dirSeparator = DIRECTORY_SEPARATOR;
94 if ( stripos( $reflection->getFileName(), "{$dirSeparator}unit{$dirSeparator}" ) === false ) {
95 self::fail( 'This unit test needs to be in "tests/phpunit/unit"!' );
96 }
97
98 self::$unitGlobals =& TestSetup::$bootstrapGlobals;
99
100 foreach ( self::getAllowedGlobalsList() as $global ) {
101 self::$unitGlobals[ $global ] =& $GLOBALS[ $global ];
102 }
103
104 // Would be nice if we could simply replace $GLOBALS as a whole,
105 // but un-setting or re-assigning that breaks the reference of this magic
106 // variable. Thus we have to modify it in place.
107 self::$originalGlobals = [];
108 foreach ( $GLOBALS as $key => $_ ) {
109 // Stash current values
110 self::$originalGlobals[$key] =& $GLOBALS[$key];
111
112 // Remove globals not part of the snapshot (see bootstrap.php, phpunit.php).
113 if ( $key !== 'GLOBALS' && !array_key_exists( $key, self::$unitGlobals ) ) {
114 unset( $GLOBALS[$key] );
115 }
116 }
117 // Restore values from the early snapshot
118 // Not by ref because tests must not be able to modify the snapshot.
119 foreach ( self::$unitGlobals as $key => $value ) {
120 $GLOBALS[ $key ] = $value;
121 }
122
123 // Set DeferredUpdates into standalone mode
124 DeferredUpdates::setScopeStack( new DeferredUpdatesScopeStack() );
125 MediaWikiServices::disallowGlobalInstanceInUnitTests();
126 ExtensionRegistry::disableForTest();
127 SettingsBuilder::disableAccessForUnitTests();
128 }
129
130 /**
131 * @inheritDoc
132 */
133 protected function runTest() {
134 try {
135 // Don't let LoggerFactory::getProvider() access globals or other things we don't want.
136 LoggerFactory::registerProvider( ObjectFactory::getObjectFromSpec( [
137 'class' => NullSpi::class
138 ] ) );
139 return parent::runTest();
140 } catch ( ConfigException $exception ) {
141 throw new Exception(
142 'Config variables must be mocked, they cannot be accessed directly in tests which extend '
143 . self::class,
144 $exception->getCode(),
145 $exception
146 );
147 }
148 }
149
150 /**
151 * The annotation causes this to be called immediately after tearDown()
152 * @after
153 */
154 final protected function mediaWikiTearDown(): void {
155 // Quick reset between tests
156 foreach ( $GLOBALS as $key => $_ ) {
157 if ( $key !== 'GLOBALS' && !array_key_exists( $key, self::$unitGlobals ) ) {
158 unset( $GLOBALS[$key] );
159 }
160 }
161 foreach ( self::$unitGlobals as $key => $value ) {
162 $GLOBALS[ $key ] = $value;
163 }
164 }
165
166 /**
167 * The annotation causes this to be called immediately after tearDownAfterClass()
168 * @afterClass
169 */
170 final public static function mediaWikiTearDownAfterClass(): void {
171 // Remove globals created by the test
172 foreach ( $GLOBALS as $key => $_ ) {
173 if ( $key !== 'GLOBALS' && !array_key_exists( $key, self::$originalGlobals ) ) {
174 unset( $GLOBALS[$key] );
175 }
176 }
177 // Restore values (including reference!)
178 foreach ( self::$originalGlobals as $key => &$value ) {
179 $GLOBALS[ $key ] =& $value;
180 }
181 unset( $value );
182
183 MediaWikiServices::allowGlobalInstanceAfterUnitTests();
184 DeferredUpdates::setScopeStack( new DeferredUpdatesScopeMediaWikiStack() );
185 ExtensionRegistry::enableForTest();
186 SettingsBuilder::enableAccessAfterUnitTests();
187 }
188
189 /**
190 * Returns a mock service container.
191 * To populate the service container with service objects, use setService().
192 *
193 * @since 1.43
194 */
195 protected function getServiceContainer(): MediaWikiServices {
196 if ( !$this->serviceContainer ) {
197 $this->serviceContainer = $this->getMockBuilder( MediaWikiServices::class )
198 ->setConstructorArgs( [ new HashConfig() ] )
199 ->onlyMethods( [
200 'getService',
201 'disableStorage',
202 'isStorageDisabled',
203 'redefineService',
204 'resetServiceForTesting',
205 'resetChildProcessServices',
206 'peekService'
207 ] )
208 ->getMock();
209
210 $this->serviceContainer
211 ->method( 'getService' )
212 ->willReturnCallback( function ( $name ) {
213 return $this->getService( $name );
214 } );
215 }
216
217 return $this->serviceContainer;
218 }
219
220 /**
221 * Returns a service previously defined with setService().
222 *
223 * @param string $name
224 *
225 * @return mixed The service instance
226 */
227 protected function getService( string $name ) {
228 if ( !isset( $this->services[$name] ) ) {
229 throw new NoSuchServiceException( $name );
230 }
231
232 if ( is_callable( $this->services[$name] ) ) {
233 $func = $this->services[$name];
234 $this->services[$name] = $func( $this->serviceContainer );
235 }
236
237 return $this->services[$name];
238 }
239
240 /**
241 * Register a service object with the service container returned by
242 * getServiceContainer().
243 *
244 * @param string $name
245 * @param mixed $service
246 *
247 * @since 1.43
248 */
249 protected function setService( string $name, $service ) {
250 $this->services[$name] = $service;
251 }
252
253 }