MediaWiki  master
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 
119  public function testSearchTermIsNotExpanded() {
120  $this->setMwGlobals( [
121  'wgSearchType' => null,
122  ] );
123 
124  # Initialize [[Special::Search]]
125  $ctx = new RequestContext();
126  $term = '{{SITENAME}}';
127  $ctx->setRequest( new FauxRequest( [ 'search' => $term, 'fulltext' => 1 ] ) );
128  $ctx->setTitle( Title::newFromText( 'Special:Search' ) );
129  $search = new SpecialSearch();
130  $search->setContext( $ctx );
131 
132  # Simulate a user searching for a given term
133  $search->execute( '' );
134 
135  # Lookup the HTML page title set for that page
136  $pageTitle = $search
137  ->getContext()
138  ->getOutput()
139  ->getHTMLTitle();
140 
141  # Compare :-]
142  $this->assertRegExp(
143  '/' . preg_quote( $term, '/' ) . '/',
144  $pageTitle,
145  "Search term '{$term}' should not be expanded in Special:Search <title>"
146  );
147  }
148 
150  return [
151  [
152  'With suggestion and no rewritten query shows did you mean',
153  '/Did you mean: <a[^>]+>first suggestion/',
154  'first suggestion',
155  null,
156  [ Title::newMainPage() ]
157  ],
158 
159  [
160  'With rewritten query informs user of change',
161  '/Showing results for <a[^>]+>first suggestion/',
162  'asdf',
163  'first suggestion',
164  [ Title::newMainPage() ]
165  ],
166 
167  [
168  'When both queries have no results user gets no results',
169  '/There were no results matching the query/',
170  'first suggestion',
171  'first suggestion',
172  []
173  ],
174  ];
175  }
176 
182  $message,
183  $expectRegex,
184  $suggestion,
185  $rewrittenQuery,
186  array $resultTitles
187  ) {
188  $results = array_map( function ( $title ) {
190  }, $resultTitles );
191 
192  $searchResults = new SpecialSearchTestMockResultSet(
193  $suggestion,
194  $rewrittenQuery,
195  $results
196  );
197 
198  $mockSearchEngine = $this->mockSearchEngine( $searchResults );
199  $search = $this->getMockBuilder( SpecialSearch::class )
200  ->setMethods( [ 'getSearchEngine' ] )
201  ->getMock();
202  $search->expects( $this->any() )
203  ->method( 'getSearchEngine' )
204  ->will( $this->returnValue( $mockSearchEngine ) );
205 
206  $search->getContext()->setTitle( Title::makeTitle( NS_SPECIAL, 'Search' ) );
207  $search->getContext()->setLanguage( Language::factory( 'en' ) );
208  $search->load();
209  $search->showResults( 'this is a fake search' );
210 
211  $html = $search->getContext()->getOutput()->getHTML();
212  foreach ( (array)$expectRegex as $regex ) {
213  $this->assertRegExp( $regex, $html, $message );
214  }
215  }
216 
217  protected function mockSearchEngine( $results ) {
218  $mock = $this->getMockBuilder( SearchEngine::class )
219  ->setMethods( [ 'searchText', 'searchTitle' ] )
220  ->getMock();
221 
222  $mock->expects( $this->any() )
223  ->method( 'searchText' )
224  ->will( $this->returnValue( $results ) );
225 
226  return $mock;
227  }
228 
232  public function testSubPageRedirect() {
233  $this->setMwGlobals( [
234  'wgScript' => '/w/index.php',
235  ] );
236 
237  $ctx = new RequestContext;
238  $sp = Title::newFromText( 'Special:Search/foo_bar' );
239  MediaWikiServices::getInstance()->getSpecialPageFactory()->executePath( $sp, $ctx );
240  $url = $ctx->getOutput()->getRedirect();
241  // some older versions of hhvm have a bug that doesn't parse relative
242  // urls with a port, so help it out a little bit.
243  // https://github.com/facebook/hhvm/issues/7136
244  $url = wfExpandUrl( $url, PROTO_CURRENT );
245 
246  $parts = parse_url( $url );
247  $this->assertEquals( '/w/index.php', $parts['path'] );
248  parse_str( $parts['query'], $query );
249  $this->assertEquals( 'Special:Search', $query['title'] );
250  $this->assertEquals( 'foo bar', $query['search'] );
251  }
252 }
253 
255  protected $results;
256  protected $suggestion;
257 
258  public function __construct(
259  $suggestion = null,
260  $rewrittenQuery = null,
261  array $results = [],
262  $containedSyntax = false
263  ) {
264  $this->suggestion = $suggestion;
265  $this->rewrittenQuery = $rewrittenQuery;
266  $this->results = $results;
267  $this->containedSyntax = $containedSyntax;
268  }
269 
270  public function expandResults() {
271  return $this->results;
272  }
273 
274  public function getTotalHits() {
275  return $this->numRows();
276  }
277 
278  public function hasSuggestion() {
279  return $this->suggestion !== null;
280  }
281 
282  public function getSuggestionQuery() {
283  return $this->suggestion;
284  }
285 
286  public function getSuggestionSnippet() {
287  return $this->suggestion;
288  }
289 
290  public function hasRewrittenQuery() {
291  return $this->rewrittenQuery !== null;
292  }
293 
294  public function getQueryAfterRewrite() {
295  return $this->rewrittenQuery;
296  }
297 
298  public function getQueryAfterRewriteSnippet() {
299  return htmlspecialchars( $this->rewrittenQuery );
300  }
301 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
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:1982
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:1585
whereas SearchGetNearMatch runs after $term
Definition: hooks.txt:2875
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:653
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.
$value
const NS_SPECIAL
Definition: Defines.php:53
const PROTO_CURRENT
Definition: Defines.php:222
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)
static newFromTitle( $title, SearchResultSet $parentSet=null)
Return a new SearchResult and initializes it with a title.
testProfileAndNamespaceLoading( $requested, $userOptions, $expectedProfile, $expectedNS, $message='Profile name and namespaces mismatches!')
SpecialSearch::load provideSearchOptionsTests.
testRewriteQueryWithSuggestion( $message, $expectRegex, $suggestion, $rewrittenQuery, array $resultTitles)
provideRewriteQueryWithSuggestion SpecialSearch::showResults
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:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:215
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown...
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
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
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:611
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:2633
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.
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:319