MediaWiki  master
SpecialSearchTest.php
Go to the documentation of this file.
1 <?php
2 
4 
13 
18  public function testValidateSortOrder() {
19  $ctx = new RequestContext();
20  $ctx->setRequest( new FauxRequest( [
21  'search' => 'foo',
22  'fulltext' => 1,
23  'sort' => 'invalid',
24  ] ) );
25  $sp = Title::makeTitle( NS_SPECIAL, 'Search' );
26  MediaWikiServices::getInstance()
27  ->getSpecialPageFactory()
28  ->executePath( $sp, $ctx );
29  $html = $ctx->getOutput()->getHTML();
30  $this->assertRegExp( '/class="warningbox"/', $html, 'must contain warnings' );
31  $this->assertRegExp( '/Sort order of invalid is unrecognized/',
32  $html, 'must tell user sort order is invalid' );
33  }
34 
46  public function testProfileAndNamespaceLoading( $requested, $userOptions,
47  $expectedProfile, $expectedNS, $message = 'Profile name and namespaces mismatches!'
48  ) {
50  $context->setUser(
51  $this->newUserWithSearchNS( $userOptions )
52  );
53  /*
54  $context->setRequest( new FauxRequest( [
55  'ns5'=>true,
56  'ns6'=>true,
57  ] ));
58  */
59  $context->setRequest( new FauxRequest( $requested ) );
60  $search = new SpecialSearch();
61  $search->setContext( $context );
62  $search->load();
63 
69  $this->assertEquals(
70  [
71  'ProfileName' => $expectedProfile,
72  'Namespaces' => $expectedNS,
73  ],
74  [
75  'ProfileName' => $search->getProfile(),
76  'Namespaces' => $search->getNamespaces(),
77  ],
78  $message
79  );
80  }
81 
82  public static function provideSearchOptionsTests() {
83  $defaultNS = MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
84  $EMPTY_REQUEST = [];
85  $NO_USER_PREF = null;
86 
87  return [
95  [
96  $EMPTY_REQUEST, $NO_USER_PREF,
97  'default', $defaultNS,
98  'T35270: No request nor user preferences should give default profile'
99  ],
100  [
101  [ 'ns5' => 1 ], $NO_USER_PREF,
102  'advanced', [ 5 ],
103  'Web request with specific NS should override user preference'
104  ],
105  [
106  $EMPTY_REQUEST, [
107  'searchNs2' => 1,
108  'searchNs14' => 1,
109  ] + array_fill_keys( array_map( function ( $ns ) {
110  return "searchNs$ns";
111  }, $defaultNS ), 0 ),
112  'advanced', [ 2, 14 ],
113  'T35583: search with no option should honor User search preferences'
114  . ' and have all other namespace disabled'
115  ],
116  ];
117  }
118 
124  function newUserWithSearchNS( $opt = null ) {
125  $u = User::newFromId( 0 );
126  if ( $opt === null ) {
127  return $u;
128  }
129  foreach ( $opt as $name => $value ) {
130  $u->setOption( $name, $value );
131  }
132 
133  return $u;
134  }
135 
141  public function testSearchTermIsNotExpanded() {
142  $this->setMwGlobals( [
143  'wgSearchType' => null,
144  ] );
145 
146  # Initialize [[Special::Search]]
147  $ctx = new RequestContext();
148  $term = '{{SITENAME}}';
149  $ctx->setRequest( new FauxRequest( [ 'search' => $term, 'fulltext' => 1 ] ) );
150  $ctx->setTitle( Title::newFromText( 'Special:Search' ) );
151  $search = new SpecialSearch();
152  $search->setContext( $ctx );
153 
154  # Simulate a user searching for a given term
155  $search->execute( '' );
156 
157  # Lookup the HTML page title set for that page
158  $pageTitle = $search
159  ->getContext()
160  ->getOutput()
161  ->getHTMLTitle();
162 
163  # Compare :-]
164  $this->assertRegExp(
165  '/' . preg_quote( $term, '/' ) . '/',
166  $pageTitle,
167  "Search term '{$term}' should not be expanded in Special:Search <title>"
168  );
169  }
170 
172  return [
173  [
174  'With suggestion and no rewritten query shows did you mean',
175  '/Did you mean: <a[^>]+>first suggestion/',
176  'first suggestion',
177  null,
178  [ Title::newMainPage() ]
179  ],
180 
181  [
182  'With rewritten query informs user of change',
183  '/Showing results for <a[^>]+>first suggestion/',
184  'asdf',
185  'first suggestion',
186  [ Title::newMainPage() ]
187  ],
188 
189  [
190  'When both queries have no results user gets no results',
191  '/There were no results matching the query/',
192  'first suggestion',
193  'first suggestion',
194  []
195  ],
196  ];
197  }
198 
204  $message,
205  $expectRegex,
206  $suggestion,
207  $rewrittenQuery,
208  array $resultTitles
209  ) {
210  $results = array_map( function ( $title ) {
212  }, $resultTitles );
213 
214  $searchResults = new SpecialSearchTestMockResultSet(
215  $suggestion,
216  $rewrittenQuery,
217  $results
218  );
219 
220  $mockSearchEngine = $this->mockSearchEngine( $searchResults );
221  $search = $this->getMockBuilder( SpecialSearch::class )
222  ->setMethods( [ 'getSearchEngine' ] )
223  ->getMock();
224  $search->expects( $this->any() )
225  ->method( 'getSearchEngine' )
226  ->will( $this->returnValue( $mockSearchEngine ) );
227 
228  $search->getContext()->setTitle( Title::makeTitle( NS_SPECIAL, 'Search' ) );
229  $search->getContext()->setLanguage( Language::factory( 'en' ) );
230  $search->load();
231  $search->showResults( 'this is a fake search' );
232 
233  $html = $search->getContext()->getOutput()->getHTML();
234  foreach ( (array)$expectRegex as $regex ) {
235  $this->assertRegExp( $regex, $html, $message );
236  }
237  }
238 
239  protected function mockSearchEngine( $results ) {
240  $mock = $this->getMockBuilder( SearchEngine::class )
241  ->setMethods( [ 'searchText', 'searchTitle' ] )
242  ->getMock();
243 
244  $mock->expects( $this->any() )
245  ->method( 'searchText' )
246  ->will( $this->returnValue( $results ) );
247 
248  return $mock;
249  }
250 
254  public function testSubPageRedirect() {
255  $this->setMwGlobals( [
256  'wgScript' => '/w/index.php',
257  ] );
258 
259  $ctx = new RequestContext;
260  $sp = Title::newFromText( 'Special:Search/foo_bar' );
261  MediaWikiServices::getInstance()->getSpecialPageFactory()->executePath( $sp, $ctx );
262  $url = $ctx->getOutput()->getRedirect();
263  // some older versions of hhvm have a bug that doesn't parse relative
264  // urls with a port, so help it out a little bit.
265  // https://github.com/facebook/hhvm/issues/7136
266  $url = wfExpandUrl( $url, PROTO_CURRENT );
267 
268  $parts = parse_url( $url );
269  $this->assertEquals( '/w/index.php', $parts['path'] );
270  parse_str( $parts['query'], $query );
271  $this->assertEquals( 'Special:Search', $query['title'] );
272  $this->assertEquals( 'foo bar', $query['search'] );
273  }
274 }
275 
277  protected $results;
278  protected $suggestion;
279 
280  public function __construct(
281  $suggestion = null,
282  $rewrittenQuery = null,
283  array $results = [],
284  $containedSyntax = false
285  ) {
286  $this->suggestion = $suggestion;
287  $this->rewrittenQuery = $rewrittenQuery;
288  $this->results = $results;
289  $this->containedSyntax = $containedSyntax;
290  }
291 
292  public function expandResults() {
293  return $this->results;
294  }
295 
296  public function getTotalHits() {
297  return $this->numRows();
298  }
299 
300  public function hasSuggestion() {
301  return $this->suggestion !== null;
302  }
303 
304  public function getSuggestionQuery() {
305  return $this->suggestion;
306  }
307 
308  public function getSuggestionSnippet() {
309  return $this->suggestion;
310  }
311 
312  public function hasRewrittenQuery() {
313  return $this->rewrittenQuery !== null;
314  }
315 
316  public function getQueryAfterRewrite() {
317  return $this->rewrittenQuery;
318  }
319 
320  public function getQueryAfterRewriteSnippet() {
321  return htmlspecialchars( $this->rewrittenQuery );
322  }
323 }
static newFromTitle( $title, ISearchResultSet $parentSet=null)
Return a new SearchResult and initializes it with a title.
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:1972
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local 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:1529
whereas SearchGetNearMatch runs after $term
Definition: hooks.txt:2863
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:656
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.
$value
const NS_SPECIAL
Definition: Defines.php:49
const PROTO_CURRENT
Definition: Defines.php:202
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:23
__construct( $suggestion=null, $rewrittenQuery=null, array $results=[], $containedSyntax=false)
testProfileAndNamespaceLoading( $requested, $userOptions, $expectedProfile, $expectedNS, $message='Profile name and namespaces mismatches!')
SpecialSearch::load provideSearchOptionsTests.
testRewriteQueryWithSuggestion( $message, $expectRegex, $suggestion, $rewrittenQuery, array $resultTitles)
provideRewriteQueryWithSuggestion SpecialSearch::showResults
hasRewrittenQuery()
Some search modes will run an alternative query that it thinks gives a better result than the provide...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:216
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:9
testValidateSortOrder()
SpecialSearch::load SpecialSearch::showResults.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
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:35
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:559
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:52
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:2621
Test class for SpecialSearch class Copyright © 2012, Antoine Musso.
newUserWithSearchNS( $opt=null)
Helper to create a new User object with given options User remains anonymous though.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
static provideSearchOptionsTests()
testSubPageRedirect()
SpecialSearch::execute.
hasSuggestion()
Some search modes return a suggested alternate term if there are no exact hits.
testSearchTermIsNotExpanded()
Verify we do not expand search term in <title> on search result page https://gerrit.wikimedia.org/r/4841 SpecialSearch::setupPage.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322