MediaWiki REL1_28
SearchEngineTest.php
Go to the documentation of this file.
1<?php
2
11
15 protected $search;
16
21 protected function setUp() {
22 parent::setUp();
23
24 // Search tests require MySQL or SQLite with FTS
25 $dbType = $this->db->getType();
26 $dbSupported = ( $dbType === 'mysql' )
27 || ( $dbType === 'sqlite' && $this->db->getFulltextSearchModule() == 'FTS3' );
28
29 if ( !$dbSupported ) {
30 $this->markTestSkipped( "MySQL or SQLite with FTS3 only" );
31 }
32
33 $searchType = SearchEngineFactory::getSearchEngineClass( $this->db );
34 $this->setMwGlobals( [
35 'wgSearchType' => $searchType
36 ] );
37
38 $this->search = new $searchType( $this->db );
39 }
40
41 protected function tearDown() {
42 unset( $this->search );
43
44 parent::tearDown();
45 }
46
47 public function addDBDataOnce() {
48 if ( !$this->isWikitextNS( NS_MAIN ) ) {
49 // @todo cover the case of non-wikitext content in the main namespace
50 return;
51 }
52
53 // Reset the search type back to default - some extensions may have
54 // overridden it.
55 $this->setMwGlobals( [ 'wgSearchType' => null ] );
56
57 $this->insertPage( 'Not_Main_Page', 'This is not a main page' );
58 $this->insertPage(
59 'Talk:Not_Main_Page',
60 'This is not a talk page to the main page, see [[smithee]]'
61 );
62 $this->insertPage( 'Smithee', 'A smithee is one who smiths. See also [[Alan Smithee]]' );
63 $this->insertPage( 'Talk:Smithee', 'This article sucks.' );
64 $this->insertPage( 'Unrelated_page', 'Nothing in this page is about the S word.' );
65 $this->insertPage( 'Another_page', 'This page also is unrelated.' );
66 $this->insertPage( 'Help:Help', 'Help me!' );
67 $this->insertPage( 'Thppt', 'Blah blah' );
68 $this->insertPage( 'Alan_Smithee', 'yum' );
69 $this->insertPage( 'Pages', 'are\'food' );
70 $this->insertPage( 'HalfOneUp', 'AZ' );
71 $this->insertPage( 'FullOneUp', 'AZ' );
72 $this->insertPage( 'HalfTwoLow', 'az' );
73 $this->insertPage( 'FullTwoLow', 'az' );
74 $this->insertPage( 'HalfNumbers', '1234567890' );
75 $this->insertPage( 'FullNumbers', '1234567890' );
76 $this->insertPage( 'DomainName', 'example.com' );
77 }
78
79 protected function fetchIds( $results ) {
80 if ( !$this->isWikitextNS( NS_MAIN ) ) {
81 $this->markTestIncomplete( __CLASS__ . " does no yet support non-wikitext content "
82 . "in the main namespace" );
83 }
84 $this->assertTrue( is_object( $results ) );
85
86 $matches = [];
87 $row = $results->next();
88 while ( $row ) {
89 $matches[] = $row->getTitle()->getPrefixedText();
90 $row = $results->next();
91 }
92 $results->free();
93 # Search is not guaranteed to return results in a certain order;
94 # sort them numerically so we will compare simply that we received
95 # the expected matches.
96 sort( $matches );
97
98 return $matches;
99 }
100
101 public function testFullWidth() {
102 $this->assertEquals(
103 [ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
104 $this->fetchIds( $this->search->searchText( 'AZ' ) ),
105 "Search for normalized from Half-width Upper" );
106 $this->assertEquals(
107 [ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
108 $this->fetchIds( $this->search->searchText( 'az' ) ),
109 "Search for normalized from Half-width Lower" );
110 $this->assertEquals(
111 [ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
112 $this->fetchIds( $this->search->searchText( 'AZ' ) ),
113 "Search for normalized from Full-width Upper" );
114 $this->assertEquals(
115 [ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
116 $this->fetchIds( $this->search->searchText( 'az' ) ),
117 "Search for normalized from Full-width Lower" );
118 }
119
120 public function testTextSearch() {
121 $this->assertEquals(
122 [ 'Smithee' ],
123 $this->fetchIds( $this->search->searchText( 'smithee' ) ),
124 "Plain search failed" );
125 }
126
127 public function testWildcardSearch() {
128 $res = $this->search->searchText( 'smith*' );
129 $this->assertEquals(
130 [ 'Smithee' ],
131 $this->fetchIds( $res ),
132 "Search with wildcards" );
133
134 $res = $this->search->searchText( 'smithson*' );
135 $this->assertEquals(
136 [],
137 $this->fetchIds( $res ),
138 "Search with wildcards must not find unrelated articles" );
139
140 $res = $this->search->searchText( 'smith* smithee' );
141 $this->assertEquals(
142 [ 'Smithee' ],
143 $this->fetchIds( $res ),
144 "Search with wildcards can be combined with simple terms" );
145
146 $res = $this->search->searchText( 'smith* "one who smiths"' );
147 $this->assertEquals(
148 [ 'Smithee' ],
149 $this->fetchIds( $res ),
150 "Search with wildcards can be combined with phrase search" );
151 }
152
153 public function testPhraseSearch() {
154 $res = $this->search->searchText( '"smithee is one who smiths"' );
155 $this->assertEquals(
156 [ 'Smithee' ],
157 $this->fetchIds( $res ),
158 "Search a phrase" );
159
160 $res = $this->search->searchText( '"smithee is who smiths"' );
161 $this->assertEquals(
162 [],
163 $this->fetchIds( $res ),
164 "Phrase search is not sloppy, search terms must be adjacent" );
165
166 $res = $this->search->searchText( '"is smithee one who smiths"' );
167 $this->assertEquals(
168 [],
169 $this->fetchIds( $res ),
170 "Phrase search is ordered" );
171 }
172
173 public function testPhraseSearchHighlight() {
174 $phrase = "smithee is one who smiths";
175 $res = $this->search->searchText( "\"$phrase\"" );
176 $match = $res->next();
177 $snippet = "A <span class='searchmatch'>" . $phrase . "</span>";
178 $this->assertStringStartsWith( $snippet,
179 $match->getTextSnippet( $res->termMatches() ),
180 "Phrase search failed to highlight" );
181 }
182
183 public function testTextPowerSearch() {
184 $this->search->setNamespaces( [ 0, 1, 4 ] );
185 $this->assertEquals(
186 [
187 'Smithee',
188 'Talk:Not Main Page',
189 ],
190 $this->fetchIds( $this->search->searchText( 'smithee' ) ),
191 "Power search failed" );
192 }
193
194 public function testTitleSearch() {
195 $this->assertEquals(
196 [
197 'Alan Smithee',
198 'Smithee',
199 ],
200 $this->fetchIds( $this->search->searchTitle( 'smithee' ) ),
201 "Title search failed" );
202 }
203
204 public function testTextTitlePowerSearch() {
205 $this->search->setNamespaces( [ 0, 1, 4 ] );
206 $this->assertEquals(
207 [
208 'Alan Smithee',
209 'Smithee',
210 'Talk:Smithee',
211 ],
212 $this->fetchIds( $this->search->searchTitle( 'smithee' ) ),
213 "Title power search failed" );
214 }
215
219 public function testSearchIndexFields() {
223 $mockEngine = $this->getMock( 'SearchEngine', [ 'makeSearchFieldMapping' ] );
224
225 $mockFieldBuilder = function ( $name, $type ) {
226 $mockField =
227 $this->getMockBuilder( 'SearchIndexFieldDefinition' )->setConstructorArgs( [
228 $name,
229 $type
230 ] )->getMock();
231
232 $mockField->expects( $this->any() )->method( 'getMapping' )->willReturn( [
233 'testData' => 'test',
234 'name' => $name,
235 'type' => $type,
236 ] );
237
238 $mockField->expects( $this->any() )
239 ->method( 'merge' )
240 ->willReturn( $mockField );
241
242 return $mockField;
243 };
244
245 $mockEngine->expects( $this->atLeastOnce() )
246 ->method( 'makeSearchFieldMapping' )
247 ->willReturnCallback( $mockFieldBuilder );
248
249 // Not using mock since PHPUnit mocks do not work properly with references in params
250 $this->setTemporaryHook( 'SearchIndexFields',
251 function ( &$fields, SearchEngine $engine ) use ( $mockFieldBuilder ) {
252 $fields['testField'] =
253 $mockFieldBuilder( "testField", SearchIndexField::INDEX_TYPE_TEXT );
254 return true;
255 } );
256
257 $fields = $mockEngine->getSearchIndexFields();
258 $this->assertArrayHasKey( 'language', $fields );
259 $this->assertArrayHasKey( 'category', $fields );
260 $this->assertInstanceOf( 'SearchIndexField', $fields['testField'] );
261
262 $mapping = $fields['testField']->getMapping( $mockEngine );
263 $this->assertArrayHasKey( 'testData', $mapping );
264 $this->assertEquals( 'test', $mapping['testData'] );
265 }
266
267 public function hookSearchIndexFields( $mockFieldBuilder, &$fields, SearchEngine $engine ) {
268 $fields['testField'] = $mockFieldBuilder( "testField", SearchIndexField::INDEX_TYPE_TEXT );
269 return true;
270 }
271
272 public function testAugmentorSearch() {
273 $this->search->setNamespaces( [ 0, 1, 4 ] );
274 $resultSet = $this->search->searchText( 'smithee' );
275 // Not using mock since PHPUnit mocks do not work properly with references in params
276 $this->mergeMwGlobalArrayValue( 'wgHooks',
277 [ 'SearchResultsAugment' => [ [ $this, 'addAugmentors' ] ] ] );
278 $this->search->augmentSearchResults( $resultSet );
279 for ( $result = $resultSet->next(); $result; $result = $resultSet->next() ) {
280 $id = $result->getTitle()->getArticleID();
281 $augmentData = "Result:$id:" . $result->getTitle()->getText();
282 $augmentData2 = "Result2:$id:" . $result->getTitle()->getText();
283 $this->assertEquals( [ 'testSet' => $augmentData, 'testRow' => $augmentData2 ],
284 $result->getExtensionData() );
285 }
286 }
287
288 public function addAugmentors( &$setAugmentors, &$rowAugmentors ) {
289 $setAugmentor = $this->getMock( 'ResultSetAugmentor' );
290 $setAugmentor->expects( $this->once() )
291 ->method( 'augmentAll' )
292 ->willReturnCallback( function ( SearchResultSet $resultSet ) {
293 $data = [];
294 for ( $result = $resultSet->next(); $result; $result = $resultSet->next() ) {
295 $id = $result->getTitle()->getArticleID();
296 $data[$id] = "Result:$id:" . $result->getTitle()->getText();
297 }
298 $resultSet->rewind();
299 return $data;
300 } );
301 $setAugmentors['testSet'] = $setAugmentor;
302
303 $rowAugmentor = $this->getMock( 'ResultAugmentor' );
304 $rowAugmentor->expects( $this->exactly( 2 ) )
305 ->method( 'augment' )
306 ->willReturnCallback( function ( SearchResult $result ) {
307 $id = $result->getTitle()->getArticleID();
308 return "Result2:$id:" . $result->getTitle()->getText();
309 } );
310 $rowAugmentors['testRow'] = $rowAugmentor;
311 }
312}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Base class that store and restore the Language objects.
insertPage( $pageName, $text='Sample page for unit test.', $namespace=null)
Insert a new page.
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
setMwGlobals( $pairs, $value=null)
isWikitextNS( $ns)
Returns true if the given namespace defaults to Wikitext according to $wgNamespaceContentModels.
setTemporaryHook( $hookName, $handler)
Create a temporary hook handler which will be reset by tearDown.
Search Database.
hookSearchIndexFields( $mockFieldBuilder, &$fields, SearchEngine $engine)
addAugmentors(&$setAugmentors, &$rowAugmentors)
setUp()
Checks for database type & version.
testSearchIndexFields()
SearchEngine::getSearchIndexFields.
Contain a class for special pages.
rewind()
Rewind result set back to beginning.
next()
Fetches next search result, or false.
$res
Definition database.txt:21
const NS_MAIN
Definition Defines.php:56
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2568
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
the value to return A Title object or null for latest all implement SearchIndexField must implement ResultSetAugmentor & $rowAugmentors
Definition hooks.txt:2756
the value to return A Title object or null for latest all implement SearchIndexField $engine
Definition hooks.txt:2755
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
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
const INDEX_TYPE_TEXT
Field types.