searchModel.test.ts 11.9 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import * as assert from 'assert';
8
import * as sinon from 'sinon';
9
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
10
import { SearchModel } from 'vs/workbench/parts/search/common/searchModel';
J
Johannes Rieken 已提交
11
import URI from 'vs/base/common/uri';
12
import { IFileMatch, IFolderQuery, ILineMatch, ISearchService, ISearchComplete, ISearchProgressItem, IUncachedSearchStats, ISearchQuery } from 'vs/platform/search/common/search';
13 14
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
15
import { Range } from 'vs/editor/common/core/range';
16
import { IModelService } from 'vs/editor/common/services/modelService';
17 18 19
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
20
import { timeout } from 'vs/base/common/async';
21 22
import { TPromise } from 'vs/base/common/winjs.base';
import { DeferredTPromise } from 'vs/base/test/common/utils';
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
const nullEvent = new class {

	public id: number;
	public topic: string;
	public name: string;
	public description: string;
	public data: any;

	public startTime: Date;
	public stopTime: Date;

	public stop(): void {
		return;
	}

	public timeTaken(): number {
		return -1;
	}
};


45
suite('SearchModel', () => {
E
Erich Gamma 已提交
46

47
	let instantiationService: TestInstantiationService;
48
	let restoreStubs: sinon.SinonStub[];
E
Erich Gamma 已提交
49

50 51 52
	const testSearchStats: IUncachedSearchStats = {
		fromCache: false,
		resultCount: 4,
C
Christof Marti 已提交
53 54
		traversal: 'node',
		errors: [],
C
chrmarti 已提交
55 56 57 58 59 60
		fileWalkStartTime: 0,
		fileWalkResultTime: 1,
		directoriesWalked: 2,
		filesWalked: 3
	};

61 62 63 64
	const folderQueries: IFolderQuery[] = [
		{ folder: URI.parse('file://c:/') }
	];

E
Erich Gamma 已提交
65
	setup(() => {
J
Johannes Rieken 已提交
66 67
		restoreStubs = [];
		instantiationService = new TestInstantiationService();
68
		instantiationService.stub(ITelemetryService, NullTelemetryService);
69
		instantiationService.stub(IModelService, stubModelService(instantiationService));
70
		instantiationService.stub(ISearchService, {});
71
		instantiationService.stub(ISearchService, 'search', TPromise.as({ results: [] }));
72 73 74 75 76 77 78 79
	});

	teardown(() => {
		restoreStubs.forEach(element => {
			element.restore();
		});
	});

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	function searchServiceWithResults(results: IFileMatch[], complete: ISearchComplete = null): ISearchService {
		return <ISearchService>{
			search(query: ISearchQuery, onProgress: (result: ISearchProgressItem) => void): TPromise<ISearchComplete> {
				return new TPromise(resolve => {
					process.nextTick(() => {
						results.forEach(onProgress);
						resolve(complete);
					});
				});
			}
		};
	}

	function searchServiceWithError(error: Error): ISearchService {
		return <ISearchService>{
			search(query: ISearchQuery, onProgress: (result: ISearchProgressItem) => void): TPromise<ISearchComplete> {
				return new TPromise((resolve, reject) => {
					reject(error);
				});
			}
		};
101 102 103
	}

	test('Search Model: Search adds to results', async () => {
J
Johannes Rieken 已提交
104
		let results = [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
105
		instantiationService.stub(ISearchService, searchServiceWithResults(results));
106

107
		let testObject: SearchModel = instantiationService.createInstance(SearchModel);
108
		await testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
109

J
Johannes Rieken 已提交
110
		let actual = testObject.searchResult.matches();
111 112 113 114

		assert.equal(2, actual.length);
		assert.equal('file://c:/1', actual[0].resource().toString());

J
Johannes Rieken 已提交
115
		let actuaMatches = actual[0].matches();
116 117 118 119 120 121
		assert.equal(2, actuaMatches.length);
		assert.equal('preview 1', actuaMatches[0].text());
		assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
		assert.equal('preview 1', actuaMatches[1].text());
		assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));

J
Johannes Rieken 已提交
122
		actuaMatches = actual[1].matches();
123 124 125 126 127
		assert.equal(1, actuaMatches.length);
		assert.equal('preview 2', actuaMatches[0].text());
		assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
	});

128
	test('Search Model: Search reports telemetry on search completed', async () => {
J
Johannes Rieken 已提交
129 130
		let target = instantiationService.spy(ITelemetryService, 'publicLog');
		let results = [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
131
		instantiationService.stub(ISearchService, searchServiceWithResults(results));
132

133
		let testObject: SearchModel = instantiationService.createInstance(SearchModel);
134
		await testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
135

136
		assert.ok(target.calledThrice);
137 138
		const data = target.args[0];
		data[1].duration = -1;
139
		assert.deepEqual(['searchResultsFirstRender', { duration: -1 }], data);
140 141
	});

R
Rob Lourens 已提交
142 143 144 145 146
	test('Search Model: Search reports timed telemetry on search when progress is not called', () => {
		let target2 = sinon.spy();
		stub(nullEvent, 'stop', target2);
		let target1 = sinon.stub().returns(nullEvent);
		instantiationService.stub(ITelemetryService, 'publicLog', target1);
147

148
		instantiationService.stub(ISearchService, searchServiceWithResults([]));
J
Joao Moreno 已提交
149

R
Rob Lourens 已提交
150 151
		let testObject = instantiationService.createInstance(SearchModel);
		const result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
152

R
Rob Lourens 已提交
153 154 155 156 157 158 159
		return result.then(() => {
			return timeout(1).then(() => {
				assert.ok(target1.calledWith('searchResultsFirstRender'));
				assert.ok(target1.calledWith('searchResultsFinished'));
			});
		});
	});
160

R
Rob Lourens 已提交
161
	test.skip('Search Model: Search reports timed telemetry on search when progress is called', () => {
J
Johannes Rieken 已提交
162
		let target2 = sinon.spy();
163
		stub(nullEvent, 'stop', target2);
J
Johannes Rieken 已提交
164
		let target1 = sinon.stub().returns(nullEvent);
J
Joao Moreno 已提交
165
		instantiationService.stub(ITelemetryService, 'publicLog', target1);
166

167 168 169
		instantiationService.stub(ISearchService, searchServiceWithResults(
			[aRawMatch('file://c:/1', aLineMatch('some preview'))],
			{ results: [], stats: testSearchStats }));
170

J
Johannes Rieken 已提交
171
		let testObject = instantiationService.createInstance(SearchModel);
172
		let result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
173

174
		return timeout(1).then(() => {
175
			return result.then(() => {
J
Joao Moreno 已提交
176 177 178 179
				assert.ok(target1.calledWith('searchResultsFirstRender'));
				assert.ok(target1.calledWith('searchResultsFinished'));
				// assert.equal(1, target2.callCount);
			});
180
		});
181 182
	});

183
	test('Search Model: Search reports timed telemetry on search when error is called', () => {
J
Johannes Rieken 已提交
184
		let target2 = sinon.spy();
185
		stub(nullEvent, 'stop', target2);
J
Johannes Rieken 已提交
186
		let target1 = sinon.stub().returns(nullEvent);
J
Joao Moreno 已提交
187
		instantiationService.stub(ITelemetryService, 'publicLog', target1);
188

189
		instantiationService.stub(ISearchService, searchServiceWithError(new Error('error')));
190

J
Johannes Rieken 已提交
191
		let testObject = instantiationService.createInstance(SearchModel);
192
		let result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
193

194
		return timeout(1).then(() => {
195
			return result.then(() => { }, () => {
J
Joao Moreno 已提交
196 197 198 199
				assert.ok(target1.calledWith('searchResultsFirstRender'));
				assert.ok(target1.calledWith('searchResultsFinished'));
				// assert.ok(target2.calledOnce);
			});
200
		});
201 202
	});

203
	test('Search Model: Search reports timed telemetry on search when error is cancelled error', () => {
J
Johannes Rieken 已提交
204
		let target2 = sinon.spy();
205
		stub(nullEvent, 'stop', target2);
J
Johannes Rieken 已提交
206
		let target1 = sinon.stub().returns(nullEvent);
J
Joao Moreno 已提交
207
		instantiationService.stub(ITelemetryService, 'publicLog', target1);
208

209
		let promise = new DeferredTPromise<ISearchComplete>();
J
Johannes Rieken 已提交
210
		instantiationService.stub(ISearchService, 'search', promise);
211

J
Johannes Rieken 已提交
212
		let testObject = instantiationService.createInstance(SearchModel);
213
		let result = testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
214 215 216

		promise.cancel();

217
		return timeout(1).then(() => {
218
			return result.then(() => { }, () => {
J
Joao Moreno 已提交
219 220 221 222
				assert.ok(target1.calledWith('searchResultsFirstRender'));
				assert.ok(target1.calledWith('searchResultsFinished'));
				// assert.ok(target2.calledOnce);
			});
223
		});
224 225
	});

226
	test('Search Model: Search results are cleared during search', async () => {
J
Johannes Rieken 已提交
227
		let results = [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
228
		instantiationService.stub(ISearchService, searchServiceWithResults(results));
J
Johannes Rieken 已提交
229
		let testObject: SearchModel = instantiationService.createInstance(SearchModel);
230
		await testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
231 232
		assert.ok(!testObject.searchResult.isEmpty());

233
		instantiationService.stub(ISearchService, searchServiceWithResults([]));
234

235
		testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
236 237 238
		assert.ok(testObject.searchResult.isEmpty());
	});

239
	test('Search Model: Previous search is cancelled when new search is called', async () => {
J
Johannes Rieken 已提交
240
		let target = sinon.spy();
241
		instantiationService.stub(ISearchService, 'search', new DeferredTPromise(target));
J
Johannes Rieken 已提交
242
		let testObject: SearchModel = instantiationService.createInstance(SearchModel);
243

244
		testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
245
		instantiationService.stub(ISearchService, searchServiceWithResults([]));
246
		testObject.search({ contentPattern: { pattern: 'somestring' }, type: 1, folderQueries });
247 248 249 250

		assert.ok(target.calledOnce);
	});

251
	test('getReplaceString returns proper replace string for regExpressions', async () => {
J
Johannes Rieken 已提交
252
		let results = [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]))];
253
		instantiationService.stub(ISearchService, searchServiceWithResults(results));
S
Sandeep Somavarapu 已提交
254

J
Johannes Rieken 已提交
255
		let testObject: SearchModel = instantiationService.createInstance(SearchModel);
256
		await testObject.search({ contentPattern: { pattern: 're' }, type: 1, folderQueries });
S
Sandeep Somavarapu 已提交
257 258 259 260
		testObject.replaceString = 'hello';
		let match = testObject.searchResult.matches()[0].matches()[0];
		assert.equal('hello', match.replaceString);

261
		await testObject.search({ contentPattern: { pattern: 're', isRegExp: true }, type: 1, folderQueries });
S
Sandeep Somavarapu 已提交
262 263 264
		match = testObject.searchResult.matches()[0].matches()[0];
		assert.equal('hello', match.replaceString);

265
		await testObject.search({ contentPattern: { pattern: 're(?:vi)', isRegExp: true }, type: 1, folderQueries });
S
Sandeep Somavarapu 已提交
266 267 268
		match = testObject.searchResult.matches()[0].matches()[0];
		assert.equal('hello', match.replaceString);

269
		await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: 1, folderQueries });
S
Sandeep Somavarapu 已提交
270 271 272
		match = testObject.searchResult.matches()[0].matches()[0];
		assert.equal('hello', match.replaceString);

273
		await testObject.search({ contentPattern: { pattern: 'r(e)(?:vi)', isRegExp: true }, type: 1, folderQueries });
S
Sandeep Somavarapu 已提交
274 275 276 277 278
		testObject.replaceString = 'hello$1';
		match = testObject.searchResult.matches()[0].matches()[0];
		assert.equal('helloe', match.replaceString);
	});

279 280 281 282 283 284 285 286
	function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
		return { resource: URI.parse(resource), lineMatches };
	}

	function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
		return { preview, lineNumber, offsetAndLengths };
	}

287
	function stub(arg1: any, arg2: any, arg3: any): sinon.SinonStub {
J
Johannes Rieken 已提交
288
		const stub = sinon.stub(arg1, arg2, arg3);
289 290 291 292
		restoreStubs.push(stub);
		return stub;
	}

293 294 295 296 297
	function stubModelService(instantiationService: TestInstantiationService): IModelService {
		instantiationService.stub(IConfigurationService, new TestConfigurationService());
		return instantiationService.createInstance(ModelServiceImpl);
	}

298
});