MediaWiki  master
SpecialSearchTest.php
Go to the documentation of this file.
1 <?php
2 
4 
13 
25  public function testProfileAndNamespaceLoading( $requested, $userOptions,
26  $expectedProfile, $expectedNS, $message = 'Profile name and namespaces mismatches!'
27  ) {
29  $context->setUser(
30  $this->newUserWithSearchNS( $userOptions )
31  );
32  /*
33  $context->setRequest( new FauxRequest( [
34  'ns5'=>true,
35  'ns6'=>true,
36  ] ));
37  */
38  $context->setRequest( new FauxRequest( $requested ) );
39  $search = new SpecialSearch();
40  $search->setContext( $context );
41  $search->load();
42 
48  $this->assertEquals(
49  [
50  'ProfileName' => $expectedProfile,
51  'Namespaces' => $expectedNS,
52  ],
53  [
54  'ProfileName' => $search->getProfile(),
55  'Namespaces' => $search->getNamespaces(),
56  ],
57  $message
58  );
59  }
60 
61  public static function provideSearchOptionsTests() {
62  $defaultNS = MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
63  $EMPTY_REQUEST = [];
64  $NO_USER_PREF = null;
65 
66  return [
74  [
75  $EMPTY_REQUEST, $NO_USER_PREF,
76  'default', $defaultNS,
77  'T35270: No request nor user preferences should give default profile'
78  ],
79  [
80  [ 'ns5' => 1 ], $NO_USER_PREF,
81  'advanced', [ 5 ],
82  'Web request with specific NS should override user preference'
83  ],
84  [
85  $EMPTY_REQUEST, [
86  'searchNs2' => 1,
87  'searchNs14' => 1,
88  ] + array_fill_keys( array_map( function ( $ns ) {
89  return "searchNs$ns";
90  }, $defaultNS ), 0 ),
91  'advanced', [ 2, 14 ],
92  'T35583: search with no option should honor User search preferences'
93  . ' and have all other namespace disabled'
94  ],
95  ];
96  }
97 
103  function newUserWithSearchNS( $opt = null ) {
104  $u = User::newFromId( 0 );
105  if ( $opt === null ) {
106  return $u;
107  }
108  foreach ( $opt as $name => $value ) {
109  $u->setOption( $name, $value );
110  }
111 
112  return $u;
113  }
114 
120  public function testSearchTermIsNotExpanded() {
121  $this->setMwGlobals( [
122  'wgSearchType' => null,
123  ] );
124 
125  # Initialize [[Special::Search]]
126  $ctx = new RequestContext();
127  $term = '{{SITENAME}}';
128  $ctx->setRequest( new FauxRequest( [ 'search' => $term, 'fulltext' => 1 ] ) );
129  $ctx->setTitle( Title::newFromText( 'Special:Search' ) );
130  $search = new SpecialSearch();
131  $search->setContext( $ctx );
132 
133  # Simulate a user searching for a given term
134  $search->execute( '' );
135 
136  # Lookup the HTML page title set for that page
137  $pageTitle = $search
138  ->getContext()
139  ->getOutput()
140  ->getHTMLTitle();
141 
142  # Compare :-]
143  $this->assertRegExp(
144  '/' . preg_quote( $term, '/' ) . '/',
145  $pageTitle,
146  "Search term '{$term}' should not be expanded in Special:Search <title>"
147  );
148  }
149 
151  return [
152  [
153  'With suggestion and no rewritten query shows did you mean',
154  '/Did you mean: <a[^>]+>first suggestion/',
155  'first suggestion',
156  null,
157  [ Title::newMainPage() ]
158  ],
159 
160  [
161  'With rewritten query informs user of change',
162  '/Showing results for <a[^>]+>first suggestion/',
163  'asdf',
164  'first suggestion',
165  [ Title::newMainPage() ]
166  ],
167 
168  [
169  'When both queries have no results user gets no results',
170  '/There were no results matching the query/',
171  'first suggestion',
172  'first suggestion',
173  []
174  ],
175  ];
176  }
177 
183  $message,
184  $expectRegex,
185  $suggestion,
186  $rewrittenQuery,
187  array $resultTitles
188  ) {
189  $results = array_map( function ( $title ) {
191  }, $resultTitles );
192 
193  $searchResults = new SpecialSearchTestMockResultSet(
194  $suggestion,
195  $rewrittenQuery,
196  $results
197  );
198 
199  $mockSearchEngine = $this->mockSearchEngine( $searchResults );
200  $search = $this->getMockBuilder( SpecialSearch::class )
201  ->setMethods( [ 'getSearchEngine' ] )
202  ->getMock();
203  $search->expects( $this->any() )
204  ->method( 'getSearchEngine' )
205  ->will( $this->returnValue( $mockSearchEngine ) );
206 
207  $search->getContext()->setTitle( Title::makeTitle( NS_SPECIAL, 'Search' ) );
208  $search->getContext()->setLanguage( Language::factory( 'en' ) );
209  $search->load();
210  $search->showResults( 'this is a fake search' );
211 
212  $html = $search->getContext()->getOutput()->getHTML();
213  foreach ( (array)$expectRegex as $regex ) {
214  $this->assertRegExp( $regex, $html, $message );
215  }
216  }
217 
218  protected function mockSearchEngine( $results ) {
219  $mock = $this->getMockBuilder( SearchEngine::class )
220  ->setMethods( [ 'searchText', 'searchTitle' ] )
221  ->getMock();
222 
223  $mock->expects( $this->any() )
224  ->method( 'searchText' )
225  ->will( $this->returnValue( $results ) );
226 
227  return $mock;
228  }
229 
233  public function testSubPageRedirect() {
234  $this->setMwGlobals( [
235  'wgScript' => '/w/index.php',
236  ] );
237 
238  $ctx = new RequestContext;
239  $sp = Title::newFromText( 'Special:Search/foo_bar' );
240  MediaWikiServices::getInstance()->getSpecialPageFactory()->executePath( $sp, $ctx );
241  $url = $ctx->getOutput()->getRedirect();
242  // some older versions of hhvm have a bug that doesn't parse relative
243  // urls with a port, so help it out a little bit.
244  // https://github.com/facebook/hhvm/issues/7136
245  $url = wfExpandUrl( $url, PROTO_CURRENT );
246 
247  $parts = parse_url( $url );
248  $this->assertEquals( '/w/index.php', $parts['path'] );
249  parse_str( $parts['query'], $query );
250  $this->assertEquals( 'Special:Search', $query['title'] );
251  $this->assertEquals( 'foo bar', $query['search'] );
252  }
253 }
254 
256  protected $results;
257  protected $suggestion;
258 
259  public function __construct(
260  $suggestion = null,
261  $rewrittenQuery = null,
262  array $results = [],
263  $containedSyntax = false
264  ) {
265  $this->suggestion = $suggestion;
266  $this->rewrittenQuery = $rewrittenQuery;
267  $this->results = $results;
268  $this->containedSyntax = $containedSyntax;
269  }
270 
271  public function expandResults() {
272  return $this->results;
273  }
274 
275  public function getTotalHits() {
276  return $this->numRows();
277  }
278 
279  public function hasSuggestion() {
280  return $this->suggestion !== null;
281  }
282 
283  public function getSuggestionQuery() {
284  return $this->suggestion;
285  }
286 
287  public function getSuggestionSnippet() {
288  return $this->suggestion;
289  }
290 
291  public function hasRewrittenQuery() {
292  return $this->rewrittenQuery !== null;
293  }
294 
295  public function getQueryAfterRewrite() {
296  return $this->rewrittenQuery;
297  }
298 
299  public function getQueryAfterRewriteSnippet() {
300  return htmlspecialchars( $this->rewrittenQuery );
301  }
302 }
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:49
const PROTO_CURRENT
Definition: Defines.php:218
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:216
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:618
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