summaryrefslogtreecommitdiff
path: root/www/wiki/tests/phpunit/includes/search/SearchEngineTest.php
blob: b7bc1530307bde830e8d22dbcd3d0308d3d55cac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php

/**
 * @group Search
 * @group Database
 *
 * @covers SearchEngine<extended>
 * @note Coverage will only ever show one of on of the Search* classes
 */
class SearchEngineTest extends MediaWikiLangTestCase {

	/**
	 * @var SearchEngine
	 */
	protected $search;

	/**
	 * Checks for database type & version.
	 * Will skip current test if DB does not support search.
	 */
	protected function setUp() {
		parent::setUp();

		// Search tests require MySQL or SQLite with FTS
		$dbType = $this->db->getType();
		$dbSupported = ( $dbType === 'mysql' )
			|| ( $dbType === 'sqlite' && $this->db->getFulltextSearchModule() == 'FTS3' );

		if ( !$dbSupported ) {
			$this->markTestSkipped( "MySQL or SQLite with FTS3 only" );
		}

		$searchType = SearchEngineFactory::getSearchEngineClass( $this->db );
		$this->setMwGlobals( [
			'wgSearchType' => $searchType,
			'wgCapitalLinks' => true,
			'wgCapitalLinkOverrides' => [
				NS_CATEGORY => false // for testCompletionSearchMustRespectCapitalLinkOverrides
			]
		] );

		$this->search = new $searchType( $this->db );
	}

	protected function tearDown() {
		unset( $this->search );

		parent::tearDown();
	}

	public function addDBDataOnce() {
		if ( !$this->isWikitextNS( NS_MAIN ) ) {
			// @todo cover the case of non-wikitext content in the main namespace
			return;
		}

		// Reset the search type back to default - some extensions may have
		// overridden it.
		$this->setMwGlobals( [
			'wgSearchType' => null,
			'wgCapitalLinks' => true,
			'wgCapitalLinkOverrides' => [
				NS_CATEGORY => false // for testCompletionSearchMustRespectCapitalLinkOverrides
			]
		] );

		$this->insertPage( 'Not_Main_Page', 'This is not a main page' );
		$this->insertPage(
			'Talk:Not_Main_Page',
			'This is not a talk page to the main page, see [[smithee]]'
		);
		$this->insertPage( 'Smithee', 'A smithee is one who smiths. See also [[Alan Smithee]]' );
		$this->insertPage( 'Talk:Smithee', 'This article sucks.' );
		$this->insertPage( 'Unrelated_page', 'Nothing in this page is about the S word.' );
		$this->insertPage( 'Another_page', 'This page also is unrelated.' );
		$this->insertPage( 'Help:Help', 'Help me!' );
		$this->insertPage( 'Thppt', 'Blah blah' );
		$this->insertPage( 'Alan_Smithee', 'yum' );
		$this->insertPage( 'Pages', 'are\'food' );
		$this->insertPage( 'HalfOneUp', 'AZ' );
		$this->insertPage( 'FullOneUp', 'AZ' );
		$this->insertPage( 'HalfTwoLow', 'az' );
		$this->insertPage( 'FullTwoLow', 'az' );
		$this->insertPage( 'HalfNumbers', '1234567890' );
		$this->insertPage( 'FullNumbers', '1234567890' );
		$this->insertPage( 'DomainName', 'example.com' );
		$this->insertPage( 'DomainName', 'example.com' );
		$this->insertPage( 'Category:search is not Search', '' );
		$this->insertPage( 'Category:Search is not search', '' );
	}

	protected function fetchIds( $results ) {
		if ( !$this->isWikitextNS( NS_MAIN ) ) {
			$this->markTestIncomplete( __CLASS__ . " does no yet support non-wikitext content "
				. "in the main namespace" );
		}
		$this->assertTrue( is_object( $results ) );

		$matches = [];
		$row = $results->next();
		while ( $row ) {
			$matches[] = $row->getTitle()->getPrefixedText();
			$row = $results->next();
		}
		$results->free();
		# Search is not guaranteed to return results in a certain order;
		# sort them numerically so we will compare simply that we received
		# the expected matches.
		sort( $matches );

		return $matches;
	}

	public function testFullWidth() {
		$this->assertEquals(
			[ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
			$this->fetchIds( $this->search->searchText( 'AZ' ) ),
			"Search for normalized from Half-width Upper" );
		$this->assertEquals(
			[ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
			$this->fetchIds( $this->search->searchText( 'az' ) ),
			"Search for normalized from Half-width Lower" );
		$this->assertEquals(
			[ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
			$this->fetchIds( $this->search->searchText( 'AZ' ) ),
			"Search for normalized from Full-width Upper" );
		$this->assertEquals(
			[ 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ],
			$this->fetchIds( $this->search->searchText( 'az' ) ),
			"Search for normalized from Full-width Lower" );
	}

	public function testTextSearch() {
		$this->assertEquals(
			[ 'Smithee' ],
			$this->fetchIds( $this->search->searchText( 'smithee' ) ),
			"Plain search" );
	}

	public function testWildcardSearch() {
		$res = $this->search->searchText( 'smith*' );
		$this->assertEquals(
			[ 'Smithee' ],
			$this->fetchIds( $res ),
			"Search with wildcards" );

		$res = $this->search->searchText( 'smithson*' );
		$this->assertEquals(
			[],
			$this->fetchIds( $res ),
			"Search with wildcards must not find unrelated articles" );

		$res = $this->search->searchText( 'smith* smithee' );
		$this->assertEquals(
			[ 'Smithee' ],
			$this->fetchIds( $res ),
			"Search with wildcards can be combined with simple terms" );

		$res = $this->search->searchText( 'smith* "one who smiths"' );
		$this->assertEquals(
			[ 'Smithee' ],
			$this->fetchIds( $res ),
			"Search with wildcards can be combined with phrase search" );
	}

	public function testPhraseSearch() {
		$res = $this->search->searchText( '"smithee is one who smiths"' );
		$this->assertEquals(
			[ 'Smithee' ],
			$this->fetchIds( $res ),
			"Search a phrase" );

		$res = $this->search->searchText( '"smithee is who smiths"' );
		$this->assertEquals(
			[],
			$this->fetchIds( $res ),
			"Phrase search is not sloppy, search terms must be adjacent" );

		$res = $this->search->searchText( '"is smithee one who smiths"' );
		$this->assertEquals(
			[],
			$this->fetchIds( $res ),
			"Phrase search is ordered" );
	}

	public function testPhraseSearchHighlight() {
		$phrase = "smithee is one who smiths";
		$res = $this->search->searchText( "\"$phrase\"" );
		$match = $res->next();
		$snippet = "A <span class='searchmatch'>" . $phrase . "</span>";
		$this->assertStringStartsWith( $snippet,
			$match->getTextSnippet( $res->termMatches() ),
			"Highlight a phrase search" );
	}

	public function testTextPowerSearch() {
		$this->search->setNamespaces( [ 0, 1, 4 ] );
		$this->assertEquals(
			[
				'Smithee',
				'Talk:Not Main Page',
			],
			$this->fetchIds( $this->search->searchText( 'smithee' ) ),
			"Power search" );
	}

	public function testTitleSearch() {
		$this->assertEquals(
			[
				'Alan Smithee',
				'Smithee',
			],
			$this->fetchIds( $this->search->searchTitle( 'smithee' ) ),
			"Title search" );
	}

	public function testTextTitlePowerSearch() {
		$this->search->setNamespaces( [ 0, 1, 4 ] );
		$this->assertEquals(
			[
				'Alan Smithee',
				'Smithee',
				'Talk:Smithee',
			],
			$this->fetchIds( $this->search->searchTitle( 'smithee' ) ),
			"Title power search" );
	}

	public function provideCompletionSearchMustRespectCapitalLinkOverrides() {
		return [
			'Searching for "smithee" finds Smithee on NS_MAIN' => [
				'smithee',
				'Smithee',
				[ NS_MAIN ],
			],
			'Searching for "search is" will finds "search is not Search" on NS_CATEGORY' => [
				'search is',
				'Category:search is not Search',
				[ NS_CATEGORY ],
			],
			'Searching for "Search is" will finds "search is not Search" on NS_CATEGORY' => [
				'Search is',
				'Category:Search is not search',
				[ NS_CATEGORY ],
			],
		];
	}

	/**
	 * Test that the search query is not munged using wrong CapitalLinks setup
	 * (in other test that the default search backend can benefit from wgCapitalLinksOverride)
	 * Guard against regressions like T208255
	 * @dataProvider provideCompletionSearchMustRespectCapitalLinkOverrides
	 * @covers SearchEngine::completionSearch
	 * @covers PrefixSearch::defaultSearchBackend
	 * @param string $search
	 * @param string $expectedSuggestion
	 * @param int[] $namespaces
	 */
	public function testCompletionSearchMustRespectCapitalLinkOverrides(
		$search,
		$expectedSuggestion,
		array $namespaces
	) {
		$this->search->setNamespaces( $namespaces );
		$results = $this->search->completionSearch( $search );
		$this->assertEquals( 1, $results->getSize() );
		$this->assertEquals( $expectedSuggestion, $results->getSuggestions()[0]->getText() );
	}

	/**
	 * @covers SearchEngine::getSearchIndexFields
	 */
	public function testSearchIndexFields() {
		/**
		 * @var $mockEngine SearchEngine
		 */
		$mockEngine = $this->getMockBuilder( SearchEngine::class )
			->setMethods( [ 'makeSearchFieldMapping' ] )->getMock();

		$mockFieldBuilder = function ( $name, $type ) {
			$mockField =
				$this->getMockBuilder( SearchIndexFieldDefinition::class )->setConstructorArgs( [
					$name,
					$type
				] )->getMock();

			$mockField->expects( $this->any() )->method( 'getMapping' )->willReturn( [
				'testData' => 'test',
				'name' => $name,
				'type' => $type,
			] );

			$mockField->expects( $this->any() )
				->method( 'merge' )
				->willReturn( $mockField );

			return $mockField;
		};

		$mockEngine->expects( $this->atLeastOnce() )
			->method( 'makeSearchFieldMapping' )
			->willReturnCallback( $mockFieldBuilder );

		// Not using mock since PHPUnit mocks do not work properly with references in params
		$this->setTemporaryHook( 'SearchIndexFields',
			function ( &$fields, SearchEngine $engine ) use ( $mockFieldBuilder ) {
				$fields['testField'] =
					$mockFieldBuilder( "testField", SearchIndexField::INDEX_TYPE_TEXT );
				return true;
			} );

		$fields = $mockEngine->getSearchIndexFields();
		$this->assertArrayHasKey( 'language', $fields );
		$this->assertArrayHasKey( 'category', $fields );
		$this->assertInstanceOf( SearchIndexField::class, $fields['testField'] );

		$mapping = $fields['testField']->getMapping( $mockEngine );
		$this->assertArrayHasKey( 'testData', $mapping );
		$this->assertEquals( 'test', $mapping['testData'] );
	}

	public function hookSearchIndexFields( $mockFieldBuilder, &$fields, SearchEngine $engine ) {
		$fields['testField'] = $mockFieldBuilder( "testField", SearchIndexField::INDEX_TYPE_TEXT );
		return true;
	}

	public function testAugmentorSearch() {
		$this->search->setNamespaces( [ 0, 1, 4 ] );
		$resultSet = $this->search->searchText( 'smithee' );
		// Not using mock since PHPUnit mocks do not work properly with references in params
		$this->mergeMwGlobalArrayValue( 'wgHooks',
			[ 'SearchResultsAugment' => [ [ $this, 'addAugmentors' ] ] ] );
		$this->search->augmentSearchResults( $resultSet );
		for ( $result = $resultSet->next(); $result; $result = $resultSet->next() ) {
			$id = $result->getTitle()->getArticleID();
			$augmentData = "Result:$id:" . $result->getTitle()->getText();
			$augmentData2 = "Result2:$id:" . $result->getTitle()->getText();
			$this->assertEquals( [ 'testSet' => $augmentData, 'testRow' => $augmentData2 ],
				$result->getExtensionData() );
		}
	}

	public function addAugmentors( &$setAugmentors, &$rowAugmentors ) {
		$setAugmentor = $this->createMock( ResultSetAugmentor::class );
		$setAugmentor->expects( $this->once() )
			->method( 'augmentAll' )
			->willReturnCallback( function ( SearchResultSet $resultSet ) {
				$data = [];
				for ( $result = $resultSet->next(); $result; $result = $resultSet->next() ) {
					$id = $result->getTitle()->getArticleID();
					$data[$id] = "Result:$id:" . $result->getTitle()->getText();
				}
				$resultSet->rewind();
				return $data;
			} );
		$setAugmentors['testSet'] = $setAugmentor;

		$rowAugmentor = $this->createMock( ResultAugmentor::class );
		$rowAugmentor->expects( $this->exactly( 2 ) )
			->method( 'augment' )
			->willReturnCallback( function ( SearchResult $result ) {
				$id = $result->getTitle()->getArticleID();
				return "Result2:$id:" . $result->getTitle()->getText();
			} );
		$rowAugmentors['testRow'] = $rowAugmentor;
	}
}