Add AuthManager
[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, $wgDisableAuthManager;
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' => $wgDisableAuthManager ? new AuthPlugin : new MediaWiki\Auth\AuthManagerAuthPlugin,
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 MediaWiki\Auth\AuthManager::resetCache();
105
106 // set up local environment
107 $context = $this->apiContext->newTestContext( $wgRequest, $wgUser );
108
109 $module = new ApiMain( $context, true );
110
111 // run it!
112 $module->execute();
113
114 // construct result
115 $results = [
116 $module->getResult()->getResultData( null, [ 'Strip' => 'all' ] ),
117 $context->getRequest(),
118 $context->getRequest()->getSessionArray()
119 ];
120
121 if ( $appendModule ) {
122 $results[] = $module;
123 }
124
125 return $results;
126 }
127
128 /**
129 * Add an edit token to the API request
130 * This is cheating a bit -- we grab a token in the correct format and then
131 * add it to the pseudo-session and to the request, without actually
132 * requesting a "real" edit token.
133 *
134 * @param array $params Key-value API params
135 * @param array|null $session Session array
136 * @param User|null $user A User object for the context
137 * @return array Result of the API call
138 * @throws Exception In case wsToken is not set in the session
139 */
140 protected function doApiRequestWithToken( array $params, array $session = null,
141 User $user = null
142 ) {
143 global $wgRequest;
144
145 if ( $session === null ) {
146 $session = $wgRequest->getSessionArray();
147 }
148
149 if ( isset( $session['wsToken'] ) && $session['wsToken'] ) {
150 // @todo Why does this directly mess with the session? Fix that.
151 // add edit token to fake session
152 $session['wsTokenSecrets']['default'] = $session['wsToken'];
153 // add token to request parameters
154 $timestamp = wfTimestamp();
155 $params['token'] = hash_hmac( 'md5', $timestamp, $session['wsToken'] ) .
156 dechex( $timestamp ) .
157 MediaWiki\Session\Token::SUFFIX;
158
159 return $this->doApiRequest( $params, $session, false, $user );
160 } else {
161 throw new Exception( "Session token not available" );
162 }
163 }
164
165 protected function doLogin( $user = 'sysop' ) {
166 if ( !array_key_exists( $user, self::$users ) ) {
167 throw new MWException( "Can not log in to undefined user $user" );
168 }
169
170 $data = $this->doApiRequest( [
171 'action' => 'login',
172 'lgname' => self::$users[$user]->username,
173 'lgpassword' => self::$users[$user]->password ] );
174
175 $token = $data[0]['login']['token'];
176
177 $data = $this->doApiRequest(
178 [
179 'action' => 'login',
180 'lgtoken' => $token,
181 'lgname' => self::$users[$user]->username,
182 'lgpassword' => self::$users[$user]->password,
183 ],
184 $data[2]
185 );
186
187 return $data;
188 }
189
190 protected function getTokenList( $user, $session = null ) {
191 $data = $this->doApiRequest( [
192 'action' => 'tokens',
193 'type' => 'edit|delete|protect|move|block|unblock|watch'
194 ], $session, false, $user->user );
195
196 if ( !array_key_exists( 'tokens', $data[0] ) ) {
197 throw new MWException( 'Api failed to return a token list' );
198 }
199
200 return $data[0]['tokens'];
201 }
202
203 public function testApiTestGroup() {
204 $groups = PHPUnit_Util_Test::getGroups( get_class( $this ) );
205 $constraint = PHPUnit_Framework_Assert::logicalOr(
206 $this->contains( 'medium' ),
207 $this->contains( 'large' )
208 );
209 $this->assertThat( $groups, $constraint,
210 'ApiTestCase::setUp can be slow, tests must be "medium" or "large"'
211 );
212 }
213 }