TableDiffFormatter: Don't repeatedly call array_shift()
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiTestCase.php
1 <?php
2
3 abstract class ApiTestCase extends MediaWikiLangTestCase {
4 protected static $apiUrl;
5
6 /**
7 * @var ApiTestContext
8 */
9 protected $apiContext;
10
11 /**
12 * @var array
13 */
14 protected $tablesUsed = [ 'user', 'user_groups', 'user_properties' ];
15
16 protected function setUp() {
17 global $wgServer;
18
19 parent::setUp();
20 self::$apiUrl = $wgServer . wfScript( 'api' );
21
22 ApiQueryInfo::resetTokenCache(); // tokens are invalid because we cleared the session
23
24 self::$users = [
25 'sysop' => new TestUser(
26 'Apitestsysop',
27 'Api Test Sysop',
28 'api_test_sysop@example.com',
29 [ 'sysop' ]
30 ),
31 'uploader' => new TestUser(
32 'Apitestuser',
33 'Api Test User',
34 'api_test_user@example.com',
35 []
36 )
37 ];
38
39 $this->setMwGlobals( [
40 'wgAuth' => new StubObject( 'wgAuth', 'AuthPlugin' ),
41 'wgRequest' => new FauxRequest( [] ),
42 'wgUser' => self::$users['sysop']->user,
43 ] );
44
45 $this->apiContext = new ApiTestContext();
46 }
47
48 protected function tearDown() {
49 // Avoid leaking session over tests
50 MediaWiki\Session\SessionManager::getGlobalSession()->clear();
51
52 parent::tearDown();
53 }
54
55 /**
56 * Edits or creates a page/revision
57 * @param string $pageName Page title
58 * @param string $text Content of the page
59 * @param string $summary Optional summary string for the revision
60 * @param int $defaultNs Optional namespace id
61 * @return array Array as returned by WikiPage::doEditContent()
62 */
63 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN ) {
64 $title = Title::newFromText( $pageName, $defaultNs );
65 $page = WikiPage::factory( $title );
66
67 return $page->doEditContent( ContentHandler::makeContent( $text, $title ), $summary );
68 }
69
70 /**
71 * Does the API request and returns the result.
72 *
73 * The returned value is an array containing
74 * - the result data (array)
75 * - the request (WebRequest)
76 * - the session data of the request (array)
77 * - if $appendModule is true, the Api module $module
78 *
79 * @param array $params
80 * @param array|null $session
81 * @param bool $appendModule
82 * @param User|null $user
83 *
84 * @return array
85 */
86 protected function doApiRequest( array $params, array $session = null,
87 $appendModule = false, User $user = null
88 ) {
89 global $wgRequest, $wgUser;
90
91 if ( is_null( $session ) ) {
92 // re-use existing global session by default
93 $session = $wgRequest->getSessionArray();
94 }
95
96 // set up global environment
97 if ( $user ) {
98 $wgUser = $user;
99 }
100
101 $wgRequest = new FauxRequest( $params, true, $session );
102 RequestContext::getMain()->setRequest( $wgRequest );
103 RequestContext::getMain()->setUser( $wgUser );
104
105 // set up local environment
106 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
107
108 $module = new ApiMain( $context, true );
109
110 // run it!
111 $module->execute();
112
113 // construct result
114 $results = [
115 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
116 $context->getRequest(),
117 $context->getRequest()->getSessionArray()
118 ];
119
120 if ( $appendModule ) {
121 $results[] = $module;
122 }
123
124 return $results;
125 }
126
127 /**
128 * Add an edit token to the API request
129 * This is cheating a bit -- we grab a token in the correct format and then
130 * add it to the pseudo-session and to the request, without actually
131 * requesting a "real" edit token.
132 *
133 * @param array $params Key-value API params
134 * @param array|null $session Session array
135 * @param User|null $user A User object for the context
136 * @return array Result of the API call
137 * @throws Exception In case wsToken is not set in the session
138 */
139 protected function doApiRequestWithToken( array $params, array $session = null,
140 User $user = null
141 ) {
142 global $wgRequest;
143
144 if ( $session === null ) {
145 $session = $wgRequest->getSessionArray();
146 }
147
148 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
149 // @todo Why does this directly mess with the session? Fix that.
150 // add edit token to fake session
151 $session['wsTokenSecrets']['default'] = $session['wsToken'];
152 // add token to request parameters
153 $timestamp = wfTimestamp();
154 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
155 dechex( $timestamp ) .
156 MediaWiki\Session\Token::SUFFIX;
157
158 return $this->doApiRequest( $params, $session, false, $user );
159 } else {
160 throw new Exception( "Session token not available" );
161 }
162 }
163
164 protected function doLogin( $user = 'sysop' ) {
165 if ( !array_key_exists( $user, self::$users ) ) {
166 throw new MWException( "Can not log in to undefined user $user" );
167 }
168
169 $data = $this->doApiRequest( [
170 'action' => 'login',
171 'lgname' => self::$users[$user]->username,
172 'lgpassword' => self::$users[$user]->password ] );
173
174 $token = $data[0]['login']['token'];
175
176 $data = $this->doApiRequest(
177 [
178 'action' => 'login',
179 'lgtoken' => $token,
180 'lgname' => self::$users[$user]->username,
181 'lgpassword' => self::$users[$user]->password,
182 ],
183 $data[2]
184 );
185
186 return $data;
187 }
188
189 protected function getTokenList( $user, $session = null ) {
190 $data = $this->doApiRequest( [
191 'action' => 'tokens',
192 'type' => 'edit|delete|protect|move|block|unblock|watch'
193 ], $session, false, $user->user );
194
195 if ( !array_key_exists( 'tokens', $data[0] ) ) {
196 throw new MWException( 'Api failed to return a token list' );
197 }
198
199 return $data[0]['tokens'];
200 }
201
202 public function testApiTestGroup() {
203 $groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
204 $constraint = PHPUnit_Framework_Assert::logicalOr(
205 $this->contains( 'medium' ),
206 $this->contains( 'large' )
207 );
208 $this->assertThat( $groups, $constraint,
209 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
210 );
211 }
212 }