Merge "RCFilters: Convert patrolled filter to three states"
[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 'wgAuth' => new MediaWiki\Auth\AuthManagerAuthPlugin,
30 'wgRequest' => new FauxRequest( [] ),
31 'wgUser' => self::$users['sysop']->getUser(),
32 ] );
33
34 $this->apiContext = new ApiTestContext();
35 }
36
37 protected function tearDown() {
38 // Avoid leaking session over tests
39 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
40
41 parent::tearDown();
42 }
43
44 /**
45 * Edits or creates a page/revision
46 * @param string $pageName Page title
47 * @param string $text Content of the page
48 * @param string $summary Optional summary string for the revision
49 * @param int $defaultNs Optional namespace id
50 * @return array Array as returned by WikiPage::doEditContent()
51 */
52 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
53 $title = Title::newFromText( $pageName, $defaultNs );
54 $page = WikiPage::factory( $title );
55
56 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
57 }
58
59 /**
60 * Does the API request and returns the result.
61 *
62 * The returned value is an array containing
63 * - the result data (array)
64 * - the request (WebRequest)
65 * - the session data of the request (array)
66 * - if $appendModule is true, the Api module $module
67 *
68 * @param array $params
69 * @param array|null $session
70 * @param bool $appendModule
71 * @param User|null $user
72 * @param string|null $tokenType Set to a string like 'csrf' to send an
73 * appropriate token
74 *
75 * @throws ApiUsageException
76 * @return array
77 */
78 protected function doApiRequest( array $params, array $session = null,
79 $appendModule = false, User $user = null, $tokenType = null
80 ) {
81 global $wgRequest, $wgUser;
82
83 if ( is_null( $session ) ) {
84 // re-use existing global session by default
85 $session = $wgRequest->getSessionArray();
86 }
87
88 $sessionObj = SessionManager::singleton()->getEmptySession();
89
90 if ( $session !== null ) {
91 foreach ( $session as $key => $value ) {
92 $sessionObj->set( $key, $value );
93 }
94 }
95
96 // set up global environment
97 if ( $user ) {
98 $wgUser = $user;
99 }
100
101 if ( $tokenType !== null ) {
102 $params['token'] = ApiQueryTokens::getToken(
103 $wgUser, $sessionObj, ApiQueryTokens::getTokenTypeSalts()[$tokenType]
104 )->toString();
105 }
106
107 $wgRequest = new FauxRequest( $params, true, $sessionObj );
108 RequestContext::getMain()->setRequest( $wgRequest );
109 RequestContext::getMain()->setUser( $wgUser );
110 MediaWiki\Auth\AuthManager::resetCache();
111
112 // set up local environment
113 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
114
115 $module = new ApiMain( $context, true );
116
117 // run it!
118 $module->execute();
119
120 // construct result
121 $results = [
122 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
123 $context->getRequest(),
124 $context->getRequest()->getSessionArray()
125 ];
126
127 if ( $appendModule ) {
128 $results[] = $module;
129 }
130
131 return $results;
132 }
133
134 /**
135 * Convenience function to access the token parameter of doApiRequest()
136 * more succinctly.
137 *
138 * @param array $params Key-value API params
139 * @param array|null $session Session array
140 * @param User|null $user A User object for the context
141 * @param string $tokenType Which token type to pass
142 * @return array Result of the API call
143 */
144 protected function doApiRequestWithToken( array $params, array $session = null,
145 User $user = null, $tokenType = 'csrf'
146 ) {
147 return $this->doApiRequest( $params, $session, false, $user, $tokenType );
148 }
149
150 /**
151 * Previously this would do API requests to log in, as well as setting $wgUser and the request
152 * context's user. The API requests are unnecessary, and the global-setting is unwanted, so
153 * this method should not be called. Instead, pass appropriate User values directly to
154 * functions that need them. For functions that still rely on $wgUser, set that directly. If
155 * you just want to log in the test sysop user, don't do anything -- that's the default.
156 *
157 * @param TestUser|string $testUser Object, or key to self::$users such as 'sysop' or 'uploader'
158 * @deprecated since 1.31
159 */
160 protected function doLogin( $testUser = null ) {
161 global $wgUser;
162
163 if ( $testUser === null ) {
164 $testUser = static::getTestSysop();
165 } elseif ( is_string( $testUser ) && array_key_exists( $testUser, self::$users ) ) {
166 $testUser = self::$users[$testUser];
167 } elseif ( !$testUser instanceof TestUser ) {
168 throw new MWException( "Can't log in to undefined user $testUser" );
169 }
170
171 $wgUser = $testUser->getUser();
172 RequestContext::getMain()->setUser( $wgUser );
173 }
174
175 protected function getTokenList( TestUser $user, $session = null ) {
176 $data = $this->doApiRequest( [
177 'action' => 'tokens',
178 'type' => 'edit|delete|protect|move|block|unblock|watch'
179 ], $session, false, $user->getUser() );
180
181 if ( !array_key_exists( 'tokens', $data[0] ) ) {
182 throw new MWException( 'Api failed to return a token list' );
183 }
184
185 return $data[0]['tokens'];
186 }
187
188 protected static function getErrorFormatter() {
189 if ( self::$errorFormatter === null ) {
190 self::$errorFormatter = new ApiErrorFormatter(
191 new ApiResult( false ),
192 Language::factory( 'en' ),
193 'none'
194 );
195 }
196 return self::$errorFormatter;
197 }
198
199 public static function apiExceptionHasCode( ApiUsageException $ex, $code ) {
200 return (bool)array_filter(
201 self::getErrorFormatter()->arrayFromStatus( $ex->getStatusValue() ),
202 function ( $e ) use ( $code ) {
203 return is_array( $e ) && $e['code'] === $code;
204 }
205 );
206 }
207
208 /**
209 * @coversNothing
210 */
211 public function testApiTestGroup() {
212 $groups = PHPUnit_Util_Test::getGroups( static::class );
213 $constraint = PHPUnit_Framework_Assert::logicalOr(
214 $this->contains( 'medium' ),
215 $this->contains( 'large' )
216 );
217 $this->assertThat( $groups, $constraint,
218 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
219 );
220 }
221 }