searchModel.test.ts 12.0 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';
R
Rob Lourens 已提交
9
import { timeout } from 'vs/base/common/async';
J
Johannes Rieken 已提交
10
import URI from 'vs/base/common/uri';
R
Rob Lourens 已提交
11 12
import { TPromise } from 'vs/base/common/winjs.base';
import { DeferredTPromise } from 'vs/base/test/common/utils';
13
import { Range } from 'vs/editor/common/core/range';
14
import { IModelService } from 'vs/editor/common/services/modelService';
R
Rob Lourens 已提交
15
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
16 17
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
R
Rob Lourens 已提交
18 19 20 21 22
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { IFileMatch, IFolderQuery, ILineMatch, ISearchComplete, ISearchProgressItem, ISearchQuery, ISearchService, IUncachedSearchStats } from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { SearchModel } from 'vs/workbench/parts/search/common/searchModel';
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('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

R
Rob Lourens 已提交
174 175 176 177
		return result.then(() => {
			return timeout(1).then(() => {
				// timeout because promise handlers may run in a different order. We only care that these
				// are fired at some point.
J
Joao Moreno 已提交
178 179 180 181
				assert.ok(target1.calledWith('searchResultsFirstRender'));
				assert.ok(target1.calledWith('searchResultsFinished'));
				// assert.equal(1, target2.callCount);
			});
182
		});
183 184
	});

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

191
		instantiationService.stub(ISearchService, searchServiceWithError(new Error('error')));
192

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

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

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

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

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

		promise.cancel();

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

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

235
		instantiationService.stub(ISearchService, searchServiceWithResults([]));
236

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

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

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

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

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

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

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

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

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

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

281 282 283 284 285 286 287 288
	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 };
	}

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

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

300
});