MediaWiki  REL1_31
SpecialSearchTest.php
Go to the documentation of this file.
1 <?php
3 
12 
24  public function testProfileAndNamespaceLoading( $requested, $userOptions,
25  $expectedProfile, $expectedNS, $message = 'Profile name and namespaces mismatches!'
26  ) {
28  $context->setUser(
29  $this->newUserWithSearchNS( $userOptions )
30  );
31  /*
32  $context->setRequest( new FauxRequest( [
33  'ns5'=>true,
34  'ns6'=>true,
35  ] ));
36  */
37  $context->setRequest( new FauxRequest( $requested ) );
38  $search = new SpecialSearch();
39  $search->setContext( $context );
40  $search->load();
41 
47  $this->assertEquals(
48  [
49  'ProfileName' => $expectedProfile,
50  'Namespaces' => $expectedNS,
51  ],
52  [
53  'ProfileName' => $search->getProfile(),
54  'Namespaces' => $search->getNamespaces(),
55  ],
56  $message
57  );
58  }
59 
60  public static function provideSearchOptionsTests() {
61  $defaultNS = MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
62  $EMPTY_REQUEST = [];
63  $NO_USER_PREF = null;
64 
65  return [
73  [
74  $EMPTY_REQUEST, $NO_USER_PREF,
75  'default', $defaultNS,
76  'T35270: No request nor user preferences should give default profile'
77  ],
78  [
79  [ 'ns5' => 1 ], $NO_USER_PREF,
80  'advanced', [ 5 ],
81  'Web request with specific NS should override user preference'
82  ],
83  [
84  $EMPTY_REQUEST, [
85  'searchNs2' => 1,
86  'searchNs14' => 1,
87  ] + array_fill_keys( array_map( function ( $ns ) {
88  return "searchNs$ns";
89  }, $defaultNS ), 0 ),
90  'advanced', [ 2, 14 ],
91  'T35583: search with no option should honor User search preferences'
92  . ' and have all other namespace disabled'
93  ],
94  ];
95  }
96 
102  function newUserWithSearchNS( $opt = null ) {
103  $u = User::newFromId( 0 );
104  if ( $opt === null ) {
105  return $u;
106  }
107  foreach ( $opt as $name => $value ) {
108  $u->setOption( $name, $value );
109  }
110 
111  return $u;
112  }
113 
118  public function testSearchTermIsNotExpanded() {
119  $this->setMwGlobals( [
120  'wgSearchType' => null,
121  ] );
122 
123  # Initialize [[Special::Search]]
124  $ctx = new RequestContext();
125  $term = '{{SITENAME}}';
126  $ctx->setRequest( new FauxRequest( [ 'search' => $term, 'fulltext' => 1 ] ) );
127  $ctx->setTitle( Title::newFromText( 'Special:Search' ) );
128  $search = new SpecialSearch();
129  $search->setContext( $ctx );
130 
131  # Simulate a user searching for a given term
132  $search->execute( '' );
133 
134  # Lookup the HTML page title set for that page
135  $pageTitle = $search
136  ->getContext()
137  ->getOutput()
138  ->getHTMLTitle();
139 
140  # Compare :-]
141  $this->assertRegExp(
142  '/' . preg_quote( $term, '/' ) . '/',
143  $pageTitle,
144  "Search term '{$term}' should not be expanded in Special:Search <title>"
145  );
146  }
147 
149  return [
150  [
151  'With suggestion and no rewritten query shows did you mean',
152  '/Did you mean: <a[^>]+>first suggestion/',
153  'first suggestion',
154  null,
155  [ Title::newMainPage() ]
156  ],
157 
158  [
159  'With rewritten query informs user of change',
160  '/Showing results for <a[^>]+>first suggestion/',
161  'asdf',
162  'first suggestion',
163  [ Title::newMainPage() ]
164  ],
165 
166  [
167  'When both queries have no results user gets no results',
168  '/There were no results matching the query/',
169  'first suggestion',
170  'first suggestion',
171  []
172  ],
173  ];
174  }
175 
180  $message,
181  $expectRegex,
182  $suggestion,
183  $rewrittenQuery,
184  array $resultTitles
185  ) {
186  $results = array_map( function ( $title ) {
188  }, $resultTitles );
189 
190  $searchResults = new SpecialSearchTestMockResultSet(
191  $suggestion,
192  $rewrittenQuery,
193  $results
194  );
195 
196  $mockSearchEngine = $this->mockSearchEngine( $searchResults );
197  $search = $this->getMockBuilder( SpecialSearch::class )
198  ->setMethods( [ 'getSearchEngine' ] )
199  ->getMock();
200  $search->expects( $this->any() )
201  ->method( 'getSearchEngine' )
202  ->will( $this->returnValue( $mockSearchEngine ) );
203 
204  $search->getContext()->setTitle( Title::makeTitle( NS_SPECIAL, 'Search' ) );
205  $search->getContext()->setLanguage( Language::factory( 'en' ) );
206  $search->load();
207  $search->showResults( 'this is a fake search' );
208 
209  $html = $search->getContext()->getOutput()->getHTML();
210  foreach ( (array)$expectRegex as $regex ) {
211  $this->assertRegExp( $regex, $html, $message );
212  }
213  }
214 
215  protected function mockSearchEngine( $results ) {
216  $mock = $this->getMockBuilder( SearchEngine::class )
217  ->setMethods( [ 'searchText', 'searchTitle' ] )
218  ->getMock();
219 
220  $mock->expects( $this->any() )
221  ->method( 'searchText' )
222  ->will( $this->returnValue( $results ) );
223 
224  return $mock;
225  }
226 
227  public function testSubPageRedirect() {
228  $this->setMwGlobals( [
229  'wgScript' => '/w/index.php',
230  ] );
231 
232  $ctx = new RequestContext;
233  $sp = Title::newFromText( 'Special:Search/foo_bar' );
234  SpecialPageFactory::executePath( $sp, $ctx );
235  $url = $ctx->getOutput()->getRedirect();
236  // some older versions of hhvm have a bug that doesn't parse relative
237  // urls with a port, so help it out a little bit.
238  // https://github.com/facebook/hhvm/issues/7136
239  $url = wfExpandUrl( $url, PROTO_CURRENT );
240 
241  $parts = parse_url( $url );
242  $this->assertEquals( '/w/index.php', $parts['path'] );
243  parse_str( $parts['query'], $query );
244  $this->assertEquals( 'Special:Search', $query['title'] );
245  $this->assertEquals( 'foo bar', $query['search'] );
246  }
247 }
248 
250  protected $results;
251  protected $suggestion;
252 
253  public function __construct(
254  $suggestion = null,
255  $rewrittenQuery = null,
256  array $results = [],
257  $containedSyntax = false
258  ) {
259  $this->suggestion = $suggestion;
260  $this->rewrittenQuery = $rewrittenQuery;
261  $this->results = $results;
262  $this->containedSyntax = $containedSyntax;
263  }
264 
265  public function numRows() {
266  return count( $this->results );
267  }
268 
269  public function getTotalHits() {
270  return $this->numRows();
271  }
272 
273  public function hasSuggestion() {
274  return $this->suggestion !== null;
275  }
276 
277  public function getSuggestionQuery() {
278  return $this->suggestion;
279  }
280 
281  public function getSuggestionSnippet() {
282  return $this->suggestion;
283  }
284 
285  public function hasRewrittenQuery() {
286  return $this->rewrittenQuery !== null;
287  }
288 
289  public function getQueryAfterRewrite() {
290  return $this->rewrittenQuery;
291  }
292 
293  public function getQueryAfterRewriteSnippet() {
294  return htmlspecialchars( $this->rewrittenQuery );
295  }
296 }
SpecialSearchTestMockResultSet\getSuggestionQuery
getSuggestionQuery()
Definition: SpecialSearchTest.php:277
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:614
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:273
SpecialSearchTest\provideRewriteQueryWithSuggestion
provideRewriteQueryWithSuggestion()
Definition: SpecialSearchTest.php:148
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
SpecialSearchTestMockResultSet\$results
$results
Definition: SpecialSearchTest.php:250
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:2013
array
the array() calling protocol came about after MediaWiki 1.4rc1.
SpecialSearchTestMockResultSet\hasRewrittenQuery
hasRewrittenQuery()
Some search modes will run an alternative query that it thinks gives a better result than the provide...
Definition: SpecialSearchTest.php:285
$opt
$opt
Definition: postprocess-phan.php:119
Title\newMainPage
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:586
SpecialSearchTestMockResultSet\getTotalHits
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.
Definition: SpecialSearchTest.php:269
SpecialSearchTest\testRewriteQueryWithSuggestion
testRewriteQueryWithSuggestion( $message, $expectRegex, $suggestion, $rewrittenQuery, array $resultTitles)
provideRewriteQueryWithSuggestion
Definition: SpecialSearchTest.php:179
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:63
$term
For QUnit the mediawiki tests qunit testrunner dependency will be added to any module whereas SearchGetNearMatch runs after $term
Definition: hooks.txt:2845
SpecialSearchTestMockResultSet\getSuggestionSnippet
getSuggestionSnippet()
Definition: SpecialSearchTest.php:281
SpecialSearchTestMockResultSet\numRows
numRows()
Definition: SpecialSearchTest.php:265
SpecialSearchTestMockResultSet\$suggestion
$suggestion
Definition: SpecialSearchTest.php:251
SpecialSearchTest\newUserWithSearchNS
newUserWithSearchNS( $opt=null)
Helper to create a new User object with given options User remains anonymous though.
Definition: SpecialSearchTest.php:102
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:678
MediaWikiTestCase
Definition: MediaWikiTestCase.php:17
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:232
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:534
SearchResultSet
Definition: SearchResultSet.php:27
RequestContext
Group all the pieces relevant to the context of a request into one instance.
Definition: RequestContext.php:32
SpecialSearchTestMockResultSet\getQueryAfterRewrite
getQueryAfterRewrite()
Definition: SpecialSearchTest.php:289
SpecialSearchTest\mockSearchEngine
mockSearchEngine( $results)
Definition: SpecialSearchTest.php:215
SpecialSearchTest\provideSearchOptionsTests
static provideSearchOptionsTests()
Definition: SpecialSearchTest.php:60
SpecialSearchTestMockResultSet
Definition: SpecialSearchTest.php:249
SpecialSearchTestMockResultSet\__construct
__construct( $suggestion=null, $rewrittenQuery=null, array $results=[], $containedSyntax=false)
Definition: SpecialSearchTest.php:253
$value
$value
Definition: styleTest.css.php:45
SpecialSearchTest\testProfileAndNamespaceLoading
testProfileAndNamespaceLoading( $requested, $userOptions, $expectedProfile, $expectedNS, $message='Profile name and namespaces mismatches!')
SpecialSearch::load provideSearchOptionsTests.
Definition: SpecialSearchTest.php:24
SpecialSearch
implements Special:Search - Run text & title search and display the output
Definition: SpecialSearch.php:38
SpecialSearchTest\testSubPageRedirect
testSubPageRedirect()
Definition: SpecialSearchTest.php:227
SpecialSearchTest\testSearchTermIsNotExpanded
testSearchTermIsNotExpanded()
Verify we do not expand search term in <title> on search result page https://gerrit....
Definition: SpecialSearchTest.php:118
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
SpecialSearchTest
Test class for SpecialSearch class Copyright © 2012, Antoine Musso.
Definition: SpecialSearchTest.php:11
SearchResult\newFromTitle
static newFromTitle( $title, SearchResultSet $parentSet=null)
Return a new SearchResult and initializes it with a title.
Definition: SearchResult.php:72
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
SpecialPageFactory\executePath
static executePath(Title &$title, IContextSource &$context, $including=false, LinkRenderer $linkRenderer=null)
Execute a special page path.
Definition: SpecialPageFactory.php:501
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:183
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:56
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:25
$query
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1620
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2811
SpecialSearchTestMockResultSet\hasSuggestion
hasSuggestion()
Some search modes return a suggested alternate term if there are no exact hits.
Definition: SpecialSearchTest.php:273
SearchResultSet\$containedSyntax
$containedSyntax
Types of interwiki results.
Definition: SearchResultSet.php:43
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:521
SpecialSearchTestMockResultSet\getQueryAfterRewriteSnippet
getQueryAfterRewriteSnippet()
Definition: SpecialSearchTest.php:293