1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
|
<?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
use MediaWiki\Config\ServiceOptions;
use MediaWiki\Http\HttpRequestFactory;
use MediaWiki\MainConfigNames;
use MediaWiki\Status\Status;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\NullLogger;
use Wikimedia\Http\MultiHttpClient;
/**
* Trait for test cases that need to mock HTTP requests.
*
* @stable to use in extensions
* @since 1.36
*/
trait MockHttpTrait {
/**
* @see MediaWikiIntegrationTestCase::setService()
*
* @param string $name
* @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
* @param object|callable $service
*/
abstract protected function setService( string $name, $service );
/**
* Install a mock HttpRequestFactory in MediaWikiServices, for the duration
* of the current test case.
*
* @param null|string|array|callable|MWHttpRequest|MultiHttpClient|GuzzleHttp\Client $request
* A list of MWHttpRequest to return on consecutive calls to HttpRequestFactory::create().
* These MWHttpRequest also represent the desired response.
* For convenience, a single MWHttpRequest can be given,
* or a callable producing such an MWHttpRequest,
* or a string that will be used as the response body of a successful request.
* If a MultiHttpClient is given, createMultiClient() is supported.
* If a GuzzleHttp\Client is given, createGuzzleClient() is supported.
* Array of MultiHttpClient or GuzzleHttp\Client mocks is supported, but not an array
* that contains the mix of the two.
* If null is given, any call to create(), createMultiClient() or createGuzzleClient()
* will cause the test to fail.
*/
private function installMockHttp( $request = null ) {
$this->setService( 'HttpRequestFactory', function () use ( $request ) {
return $this->makeMockHttpRequestFactory( $request );
} );
}
/**
* Return a mock HttpRequestFactory in MediaWikiServices.
*
* @param null|string|array|callable|MWHttpRequest|MultiHttpClient $request A list of
* MWHttpRequest to return on consecutive calls to HttpRequestFactory::create().
* These MWHttpRequest also represent the desired response.
* For convenience, a single MWHttpRequest can be given,
* or a callable producing such an MWHttpRequest,
* or a string that will be used as the response body of a successful request.
* If a MultiHttpClient is given, createMultiClient() is supported.
* If a GuzzleHttp\Client is given, createGuzzleClient() is supported.
* Array of MultiHttpClient or GuzzleHttp\Client mocks is supported, but not an array
* that contains the mix of the two.
* If null or a MultiHttpClient is given instead of a MWHttpRequest,
* a call to create() will cause the test to fail.
*
* @return HttpRequestFactory
*/
private function makeMockHttpRequestFactory( $request = null ) {
$options = new ServiceOptions( HttpRequestFactory::CONSTRUCTOR_OPTIONS, [
MainConfigNames::HTTPTimeout => 1,
MainConfigNames::HTTPConnectTimeout => 1,
MainConfigNames::HTTPMaxTimeout => 1,
MainConfigNames::HTTPMaxConnectTimeout => 1,
MainConfigNames::LocalVirtualHosts => [],
MainConfigNames::LocalHTTPProxy => false,
] );
$failCallback = static function ( /* discard any arguments */ ) {
TestCase::fail( 'method should not be called' );
};
/** @var HttpRequestFactory|MockObject $mockHttpRequestFactory */
$mockHttpRequestFactory = $this->getMockBuilder( HttpRequestFactory::class )
->setConstructorArgs( [ $options, new NullLogger() ] )
->onlyMethods( [ 'create', 'createMultiClient', 'createGuzzleClient' ] )
->getMock();
foreach ( [
MultiHttpClient::class => 'createMultiClient',
GuzzleHttp\Client::class => 'createGuzzleClient'
] as $class => $method ) {
if ( $request instanceof $class ) {
$mockHttpRequestFactory->method( $method )
->willReturn( $request );
} elseif ( $this->isArrayOfClass( $class, $request ) ) {
$mockHttpRequestFactory->method( $method )
->willReturnOnConsecutiveCalls( ...$request );
} else {
$mockHttpRequestFactory->method( $method )
->willReturn( $this->createNoOpMock( $class ) );
}
}
if ( $request === null ) {
$mockHttpRequestFactory->method( 'create' )
->willReturnCallback( $failCallback );
} elseif ( $request instanceof MultiHttpClient ) {
$mockHttpRequestFactory->method( 'create' )
->willReturnCallback( $failCallback );
} elseif ( $request instanceof GuzzleHttp\Client ) {
$mockHttpRequestFactory->method( 'create' )
->willReturnCallback( $failCallback );
} elseif ( $request instanceof MWHttpRequest ) {
$mockHttpRequestFactory->method( 'create' )
->willReturn( $request );
} elseif ( is_callable( $request ) ) {
$mockHttpRequestFactory->method( 'create' )
->willReturnCallback( $request );
} elseif ( is_array( $request ) ) {
$mockHttpRequestFactory->method( 'create' )
->willReturnOnConsecutiveCalls( ...$request );
} elseif ( is_string( $request ) ) {
$mockHttpRequestFactory->method( 'create' )
->willReturn( $this->makeFakeHttpRequest( $request ) );
}
return $mockHttpRequestFactory;
}
/**
* Check whether $array is an array where all elements are instances of $class.
*
* @internal to the trait
* @param string $class
* @param mixed $array
* @return bool
*/
private function isArrayOfClass( string $class, $array ): bool {
if ( !is_array( $array ) || !count( $array ) ) {
return false;
}
foreach ( $array as $item ) {
if ( !$item instanceof $class ) {
return false;
}
}
return true;
}
/**
* Constructs a fake MWHTTPRequest. The request also represents the desired response.
*
* @note Not all methods on MWHTTPRequest are mocked, calling other methods will
* cause the test to fail.
*
* @param string $body The response body.
* @param int|StatusValue $responseStatus The response status code. Use 0 to indicate an internal error.
* Alternatively, you can provide a configured StatusValue with status code as a value and
* whatever warnings or errors you want.
* @param string[] $headers Any response headers.
*
* @return MWHttpRequest
*/
private function makeFakeHttpRequest(
$body = 'Lorem Ipsum',
$responseStatus = 200,
$headers = []
) {
$mockHttpRequest = $this->createNoOpMock(
MWHttpRequest::class,
[ 'execute', 'setCallback', 'isRedirect', 'getFinalUrl',
'getResponseHeaders', 'getResponseHeader', 'setHeader',
'getStatus', 'getContent'
]
);
$statusCode = $responseStatus instanceof StatusValue ? $responseStatus->getValue() : $responseStatus;
$mockHttpRequest->method( 'isRedirect' )->willReturn(
$statusCode >= 300 && $statusCode < 400
);
$mockHttpRequest->method( 'getFinalUrl' )->willReturn( $headers[ 'Location' ] ?? '' );
$mockHttpRequest->method( 'getResponseHeaders' )->willReturn( $headers );
$mockHttpRequest->method( 'getResponseHeader' )->willReturnCallback(
static function ( $name ) use ( $headers ) {
return $headers[$name] ?? null;
}
);
$dataCallback = null;
$mockHttpRequest->method( 'setCallback' )->willReturnCallback(
static function ( $callback ) use ( &$dataCallback ) {
$dataCallback = $callback;
}
);
if ( is_int( $responseStatus ) ) {
$statusObject = Status::newGood( $statusCode );
if ( $statusCode === 0 ) {
$statusObject->fatal( 'http-internal-error' );
} elseif ( $statusCode >= 400 ) {
$statusObject->fatal( "http-bad-status", $statusCode, $body );
}
} else {
$statusObject = Status::wrap( $responseStatus );
}
$mockHttpRequest->method( 'getContent' )->willReturn( $body );
$mockHttpRequest->method( 'getStatus' )->willReturn( $statusCode );
$mockHttpRequest->method( 'execute' )->willReturnCallback(
function () use ( &$dataCallback, $body, $statusObject ) {
if ( $dataCallback ) {
$dataCallback( $this, $body );
}
return $statusObject;
}
);
return $mockHttpRequest;
}
/**
* Construct a fake HTTP request that will result in an HTTP timeout.
*
* @see self::makeFakeHttpRequest
* @param string $body
* @param string $requestUrl
* @return MWHttpRequest
*/
private function makeFakeTimeoutRequest(
string $body = 'HTTP Timeout',
string $requestUrl = 'https://dummy.org'
) {
$responseStatus = StatusValue::newGood( 504 );
$responseStatus->fatal( 'http-timed-out', $requestUrl );
return $this->makeFakeHttpRequest( $body, $responseStatus, [] );
}
/**
* Constructs a fake MultiHttpClient which will return the given response.
*
* @note Not all methods on MultiHttpClient are mocked, calling other methods will
* cause the test to fail.
*
* @param array $responses An array mapping request keys to responses.
* Each response may be a string (the response body), or an array with the
* following keys (all optional): 'code', 'reason', 'headers', 'body', 'error'.
* If the 'response' key is set, the associated value is expected to be the
* response array and contain the 'code', 'body', etc fields. This allows
* $responses to have the same structure as the return value of runMulti().
*
* @return MultiHttpClient
*/
private function makeFakeHttpMultiClient( $responses = [] ) {
$mockHttpRequestMulti = $this->createNoOpMock(
MultiHttpClient::class,
[ 'run', 'runMulti' ]
);
$mockHttpRequestMulti->method( 'run' )->willReturnCallback(
static function ( array $req, array $opts = [] ) use ( $mockHttpRequestMulti ) {
return $mockHttpRequestMulti->runMulti( [ $req ], $opts )[0]['response'];
}
);
$mockHttpRequestMulti->method( 'runMulti' )->willReturnCallback(
static function ( array $reqs, array $opts = [] ) use ( $responses ) {
foreach ( $reqs as $key => &$req ) {
$resp = $responses[$key] ?? [ 'code' => 0, 'error' => 'unknown' ];
if ( is_string( $resp ) ) {
$resp = [ 'body' => $resp ];
}
if ( isset( $resp['response'] ) ) {
// $responses is not just an array of responses,
// but a request/response structure.
$resp = $resp['response'];
}
$req['response'] = $resp + [
'code' => 200,
'reason' => '',
'headers' => [],
'body' => '',
'error' => '',
];
$req['response'][0] = $req['response']['code'];
$req['response'][1] = $req['response']['reason'];
$req['response'][2] = $req['response']['headers'];
$req['response'][3] = $req['response']['body'];
$req['response'][4] = $req['response']['error'];
unset( $req );
}
return $reqs;
}
);
return $mockHttpRequestMulti;
}
/**
* Constructs a fake GuzzleHttp\Client which will return the given response.
*
* @note Not all methods on GuzzleHttp\Client are mocked, calling other methods will
* cause the test to fail.
*
* @param ResponseInterface|string $response The response to return.
*
* @return GuzzleHttp\Client
*/
private function makeFakeGuzzleClient( $response ) {
if ( is_string( $response ) ) {
$response = new GuzzleHttp\Psr7\Response( 200, [], $response );
}
$mockHttpClient = $this->createNoOpMock(
GuzzleHttp\Client::class,
[ 'request', 'get', 'put', 'post' ]
);
$mockHttpClient->method( 'request' )->willReturn( $response );
$mockHttpClient->method( 'get' )->willReturn( $response );
$mockHttpClient->method( 'put' )->willReturn( $response );
$mockHttpClient->method( 'post' )->willReturn( $response );
return $mockHttpClient;
}
}
|