Debian Codegraph @

tests/phpunit/unit/includes/Rest/Handler/ActionModuleBasedHandlerTestTrait.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use Exception;
6 use MediaWiki\Api\ApiBase;
7 use MediaWiki\Api\ApiMain;
8 use MediaWiki\Context\RequestContext;
9 use MediaWiki\Language\Language;
10 use MediaWiki\Request\FauxRequest;
11 use PHPUnit\Framework\MockObject\MockBuilder;
12 use PHPUnit\Framework\MockObject\MockObject;
13
14 /**
15 * A trait providing utility functions for testing Handler classes
16 * derived from ActionModuleBasedHandler.
17 * This trait is intended to be used on subclasses of MediaWikiUnitTestCase
18 * or MediaWikiIntegrationTestCase.
19 *
20 * @method MockBuilder getMockBuilder(string $className)
21 */
22 trait ActionModuleBasedHandlerTestTrait {
23
24 use HandlerTestTrait;
25
26 /**
27 * @param ApiMain $main
28 * @param string $name
29 * @param array $resultData
30 * @param Exception|null $throwException
31 *
32 * @return ApiBase|MockObject
33 */
34 private function getDummyApiModule(
35 ApiMain $main,
36 $name,
37 $resultData,
38 ?Exception $throwException = null
39 ) {
40 /** @var ApiBase|MockObject $module */
41 $module = $this->getMockBuilder( ApiBase::class )
42 ->setConstructorArgs( [ $main, $name ] )
43 ->onlyMethods( [ 'execute' ] )
44 ->getMock();
45
46 $module->method( 'execute' )
47 ->willReturnCallback(
48 static function () use ( $module, $resultData, $throwException ) {
49 if ( $throwException ) {
50 throw $throwException;
51 }
52
53 $res = $module->getResult();
54 foreach ( $resultData as $key => $value ) {
55 $res->addValue( null, $key, $value );
56 }
57 }
58 );
59
60 return $module;
61 }
62
63 /**
64 * @param bool $csrfSafe
65 * @return ApiMain
66 */
67 private function getApiMain( $csrfSafe = false ) {
68 $session = $this->getSession( $csrfSafe );
69
70 // NOTE: This being a MediaWiki\Request\FauxRequest instance triggers special case behavior
71 // in ApiMain, causing ApiMain::isInternalMode() to return true. Among other things,
72 // this causes ApiMain to throw errors rather than encode them in the result data.
73 /** @var MockObject|FauxRequest $fauxRequest */
74 $fauxRequest = $this->getMockBuilder( FauxRequest::class )
75 ->onlyMethods( [ 'getSession', 'getSessionId' ] )
76 ->getMock();
77 $fauxRequest->method( 'getSession' )->willReturn( $session );
78 $fauxRequest->method( 'getSessionId' )->willReturn( $session->getSessionId() );
79
80 /** @var Language|MockObject $language */
81 $language = $this->createNoOpMock( Language::class );
82 $testContext = RequestContext::getMain();
83
84 $fauxContext = new RequestContext();
85 $fauxContext->setRequest( $fauxRequest );
86 $fauxContext->setUser( $testContext->getUser() );
87 $fauxContext->setLanguage( $language );
88
89 return new ApiMain( $fauxContext, true );
90 }
91
92 }