Remove hard deprecation of PasswordPolicyChecks::checkPopularPasswordBlacklist
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiTestCase.php
1 <?php
2
3 use MediaWiki\Session\SessionManager;
4
5 abstract class ApiTestCase extends MediaWikiLangTestCase {
6 protected static $apiUrl;
7
8 protected static $errorFormatter = null;
9
10 /**
11 * @var ApiTestContext
12 */
13 protected $apiContext;
14
15 protected function setUp() {
16 global $wgServer;
17
18 parent::setUp();
19 self::$apiUrl = $wgServer . wfScript( 'api' );
20
21 ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
22
23 self::$users = [
24 'sysop' => static::getTestSysop(),
25 'uploader' => static::getTestUser(),
26 ];
27
28 $this->setMwGlobals( [
29 'wgRequest' => new FauxRequest( [] ),
30 'wgUser' => self::$users['sysop']->getUser(),
31 ] );
32
33 $this->apiContext = new ApiTestContext();
34 }
35
36 protected function tearDown() {
37 // Avoid leaking session over tests
38 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
39
40 parent::tearDown();
41 }
42
43 /**
44 * Does the API request and returns the result.
45 *
46 * The returned value is an array containing
47 * - the result data (array)
48 * - the request (WebRequest)
49 * - the session data of the request (array)
50 * - if $appendModule is true, the Api module $module
51 *
52 * @param array $params
53 * @param array|null $session
54 * @param bool $appendModule
55 * @param User|null $user
56 * @param string|null $tokenType Set to a string like 'csrf' to send an
57 * appropriate token
58 *
59 * @throws ApiUsageException
60 * @return array
61 */
62 protected function doApiRequest( array $params, array $session = null,
63 $appendModule = false, User $user = null, $tokenType = null
64 ) {
65 global $wgRequest, $wgUser;
66
67 if ( is_null( $session ) ) {
68 // re-use existing global session by default
69 $session = $wgRequest->getSessionArray();
70 }
71
72 $sessionObj = SessionManager::singleton()->getEmptySession();
73
74 if ( $session !== null ) {
75 foreach ( $session as $key => $value ) {
76 $sessionObj->set( $key, $value );
77 }
78 }
79
80 // set up global environment
81 if ( $user ) {
82 $wgUser = $user;
83 }
84
85 if ( $tokenType !== null ) {
86 if ( $tokenType === 'auto' ) {
87 $tokenType = ( new ApiMain() )->getModuleManager()
88 ->getModule( $params['action'], 'action' )->needsToken();
89 }
90 $params['token'] = ApiQueryTokens::getToken(
91 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
92 )->toString();
93 }
94
95 $wgRequest = new FauxRequest( $params, true, $sessionObj );
96 RequestContext::getMain()->setRequest( $wgRequest );
97 RequestContext::getMain()->setUser( $wgUser );
98 MediaWiki\Auth\AuthManager::resetCache();
99
100 // set up local environment
101 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
102
103 $module = new ApiMain( $context, true );
104
105 // run it!
106 $module->execute();
107
108 // construct result
109 $results = [
110 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
111 $context->getRequest(),
112 $context->getRequest()->getSessionArray()
113 ];
114
115 if ( $appendModule ) {
116 $results[] = $module;
117 }
118
119 return $results;
120 }
121
122 /**
123 * Convenience function to access the token parameter of doApiRequest()
124 * more succinctly.
125 *
126 * @param array $params Key-value API params
127 * @param array|null $session Session array
128 * @param User|null $user A User object for the context
129 * @param string $tokenType Which token type to pass
130 * @return array Result of the API call
131 */
132 protected function doApiRequestWithToken( array $params, array $session = null,
133 User $user = null, $tokenType = 'auto'
134 ) {
135 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
136 }
137
138 /**
139 * Previously this would do API requests to log in, as well as setting $wgUser and the request
140 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
141 * this method should not be called. Instead, pass appropriate User values directly to
142 * functions that need them. For functions that still rely on $wgUser, set that directly. If
143 * you just want to log in the test sysop user, don't do anything -- that's the default.
144 *
145 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
146 * @deprecated since 1.31
147 */
148 protected function doLogin( $testUser = null ) {
149 global $wgUser;
150
151 if ( $testUser === null ) {
152 $testUser = static::getTestSysop();
153 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
154 $testUser = self::$users[$testUser];
155 } elseif ( !$testUser instanceof TestUser ) {
156 throw new MWException( "Can't log in to undefined user $testUser" );
157 }
158
159 $wgUser = $testUser->getUser();
160 RequestContext::getMain()->setUser( $wgUser );
161 }
162
163 protected function getTokenList( TestUser $user, $session = null ) {
164 $data = $this->doApiRequest( [
165 'action' => 'tokens',
166 'type' => 'edit|delete|protect|move|block|unblock|watch'
167 ], $session, false, $user->getUser() );
168
169 if ( !array_key_exists( 'tokens', $data[0] ) ) {
170 throw new MWException( 'Api failed to return a token list' );
171 }
172
173 return $data[0]['tokens'];
174 }
175
176 protected static function getErrorFormatter() {
177 if ( self::$errorFormatter === null ) {
178 self::$errorFormatter = new ApiErrorFormatter(
179 new ApiResult( false ),
180 Language::factory( 'en' ),
181 'none'
182 );
183 }
184 return self::$errorFormatter;
185 }
186
187 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
188 return (bool)array_filter(
189 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
190 function ( $e ) use ( $code ) {
191 return is_array( $e ) && $e['code'] === $code;
192 }
193 );
194 }
195
196 /**
197 * @coversNothing
198 */
199 public function testApiTestGroup() {
200 $groups = PHPUnit_Util_Test::getGroups( static::class );
201 $constraint = PHPUnit_Framework_Assert::logicalOr(
202 $this->contains( 'medium' ),
203 $this->contains( 'large' )
204 );
205 $this->assertThat( $groups, $constraint,
206 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
207 );
208 }
209
210 /**
211 * Expect an ApiUsageException to be thrown with the given parameters, which are the same as
212 * ApiUsageException::newWithMessage()'s parameters. This allows checking for an exception
213 * whose text is given by a message key instead of text, so as not to hard-code the message's
214 * text into test code.
215 */
216 protected function setExpectedApiException(
217 $msg, $code = null, array $data = null, $httpCode = 0
218 ) {
219 $expected = ApiUsageException::newWithMessage( null, $msg, $code, $data, $httpCode );
220 $this->setExpectedException( ApiUsageException::class, $expected->getMessage() );
221 }
222 }