Revert changes to unit tests

This commit is contained in:
Ron Buckton committed 2018-02-05 23:29:20 -08:00
1 parent 0b963489a7
commit f153b04f35
37 files changed
+10089 -13170

No files matched your search

+27 -277
View File
@@ -1,145 +1,64 @@
/// <reference path="./core.ts" />
/// <reference path="./assert.ts" />
/// <reference path="./utils.ts" />
/// <reference path="./vfs.ts" />
/// <reference path="./typemock.ts" />
// NOTE: The contents of this file are all exported from the namespace 'fakes'. This is to
// support the eventual conversion of harness into a modular system.
// harness fakes
namespace fakes {
export interface FakeServerHostOptions {
/**
* The `VirtualFleSystem` to use. If not specified, a new case-sensitive `VirtualFileSystem`
* is created.
*/
vfs?: vfs.FileSystem | { currentDirectory?: string, useCaseSensitiveFileNames?: boolean };
const processExitSentinel = new Error("System exit");
export interface ServerHostOptions {
/**
* The virtual path to tsc.js. If not specified, a default of `"/.ts/tsc.js"` is used.
*/
executingFilePath?: string;
/**
* The new-line style. If not specified, a default of `"\n"` is used.
*/
newLine?: "\r\n" | "\n";
/**
* Indicates whether to include _safeList.json_.
*/
safeList?: boolean;
/**
* Indicates whether to include a bare _lib.d.ts_.
*/
lib?: boolean;
/**
* Indicates whether to use DOS paths by default.
*/
dos?: boolean;
}
export class FakeServerHost implements ts.server.ServerHost, ts.FormatDiagnosticsHost, ts.ModuleResolutionHost {
public static readonly dosExecutingFilePath = vpath.combine(vfsutils.dosBuiltFolder, "tsc.js");
public static readonly defaultExecutingFilePath = vpath.combine(vfsutils.builtFolder, "tsc.js");
public static readonly dosDefaultCurrentDirectory = "c:/";
public static readonly defaultCurrentDirectory = "/";
public static readonly dosSafeListPath = "c:/safelist.json";
public static readonly safeListPath = "/safelist.json";
public static readonly safeListContent =
`{\n` +
` "commander": "commander",\n` +
` "express": "express",\n` +
` "jquery": "jquery",\n` +
` "lodash": "lodash",\n` +
` "moment": "moment",\n` +
` "chroma": "chroma-js"\n` +
`}`;
public static readonly dosLibPath = vpath.combine(vfsutils.dosBuiltFolder, "lib.d.ts");
public static readonly libPath = vpath.combine(vfsutils.builtFolder, "lib.d.ts");
public static readonly libContent =
`/// <reference no-default-lib="true"/>\n` +
`interface Boolean {}\n` +
`interface Function {}\n` +
`interface IArguments {}\n` +
`interface Number { toExponential: any; }\n` +
`interface Object {}\n` +
`interface RegExp {}\n` +
`interface String { charAt: any; }\n` +
`interface Array<T> {}`;
public readonly timers = new typemock.Timers();
export class ServerHost implements ts.server.ServerHost, ts.FormatDiagnosticsHost {
public readonly vfs: vfs.FileSystem;
public exitCode: number;
public watchFiles = true;
public watchDirectories = true;
private static readonly processExitSentinel = new Error("System exit");
private readonly _output: string[] = [];
private readonly _trace: string[] = [];
private readonly _executingFilePath: string;
private readonly _getCanonicalFileName: (file: string) => string;
private _screenClears = 0;
private _watchedFiles: core.SortedMap<string, number> | undefined;
private _watchedFilesSet: core.SortedSet<string> | undefined;
private _watchedRecursiveDirectories: core.SortedMap<string, number> | undefined;
private _watchedRecursiveDirectoriesSet: core.SortedSet<string> | undefined;
private _watchedNonRecursiveDirectories: core.SortedMap<string, number> | undefined;
private _watchedNonRecursiveDirectoriesSet: core.SortedSet<string> | undefined;
constructor(options: FakeServerHostOptions = {}, files?: vfs.FileSet) {
constructor(vfs: vfs.FileSystem, options: ServerHostOptions = {}) {
const {
dos = false,
vfs: _vfs = {},
executingFilePath = dos
? FakeServerHost.dosExecutingFilePath
: FakeServerHost.defaultExecutingFilePath,
? vfsutils.dosTscPath
: vfsutils.tscPath,
newLine = "\n",
safeList = false,
lib = false,
} = options;
const currentDirectory = _vfs instanceof vfs.FileSystem ? _vfs.cwd() :
_vfs.currentDirectory !== undefined ? _vfs.currentDirectory :
dos ? FakeServerHost.dosDefaultCurrentDirectory :
FakeServerHost.defaultCurrentDirectory;
const useCaseSensitiveFileNames = _vfs instanceof vfs.FileSystem ? !_vfs.ignoreCase :
_vfs.useCaseSensitiveFileNames !== undefined ? _vfs.useCaseSensitiveFileNames :
false;
this.vfs = _vfs instanceof vfs.FileSystem
? _vfs
: new vfs.FileSystem(!useCaseSensitiveFileNames, { cwd: currentDirectory });
if (this.vfs.isReadonly) {
this.vfs = this.vfs.shadow();
}
this.vfs.mkdirpSync(currentDirectory);
this.vfs.chdir(currentDirectory);
this.vfs = vfs.isReadonly ? vfs.shadow() : vfs;
this.useCaseSensitiveFileNames = !this.vfs.ignoreCase;
this.newLine = newLine;
this._executingFilePath = executingFilePath;
this._getCanonicalFileName = ts.createGetCanonicalFileName(this.useCaseSensitiveFileNames);
if (files) {
this.vfs.apply(files);
}
if (safeList) {
const safeListPath = dos ? FakeServerHost.dosSafeListPath : FakeServerHost.safeListPath;
this.vfs.mkdirpSync(vpath.dirname(safeListPath));
this.vfs.writeFileSync(safeListPath, FakeServerHost.safeListContent);
const safelistPath = dos ? vfsutils.dosSafelistPath : vfsutils.safelistPath;
this.vfs.mkdirpSync(vpath.dirname(safelistPath));
this.vfs.writeFileSync(safelistPath, vfsutils.safelistContent);
}
if (lib) {
const libPath = dos ? FakeServerHost.dosLibPath : FakeServerHost.libPath;
const libPath = dos ? vfsutils.dosLibPath : vfsutils.libPath;
this.vfs.mkdirpSync(vpath.dirname(libPath));
this.vfs.writeFileSync(libPath, FakeServerHost.libContent);
this.vfs.writeFileSync(libPath, vfsutils.emptyLibContent);
}
}
// #region DirectoryStructureHost members
// #region System members
public readonly newLine: string;
public readonly useCaseSensitiveFileNames: boolean;
@@ -183,17 +102,9 @@ namespace fakes {
public exit(exitCode?: number) {
this.exitCode = exitCode;
throw FakeServerHost.processExitSentinel;
throw processExitSentinel;
}
// #endregion DirectoryStructureHost members
// #region ModuleResolutionHost members
public trace(message: string) {
this._trace.push(message);
}
// #endregion
// #region System members
public readonly args: string[] = [];
public getFileSize(path: string) {
@@ -201,77 +112,11 @@ namespace fakes {
}
public watchFile(path: string, cb: ts.FileWatcherCallback) {
if (!this._watchedFiles) this._watchedFiles = new core.SortedMap<string, number>({ comparer: this.vfs.stringComparer, sort: "insertion" });
if (!this._watchedFilesSet) this._watchedFilesSet = new core.SortedSet<string>(this.vfs.stringComparer);
const previousCount = this._watchedFiles.get(path) || 0;
if (previousCount === 0) {
this._watchedFilesSet.add(path);
}
this._watchedFiles.set(path, previousCount + 1);
let watching = true;
const watcher = vfsutils.watchFile(this.vfs, path, (fileName, eventKind) => {
if (this.watchFiles) cb(fileName, eventKind);
});
return {
close: () => {
if (watching) {
const previousCount = this._watchedFiles.get(path) || 0;
if (previousCount === 1) {
this._watchedFiles.delete(path);
this._watchedFilesSet.delete(path);
}
else {
this._watchedFiles.set(path, previousCount - 1);
}
watcher.close();
watching = false;
}
}
};
return vfsutils.watchFile(this.vfs, path, cb);
}
public watchDirectory(path: string, cb: ts.DirectoryWatcherCallback, recursive?: boolean): ts.FileWatcher {
const watchedDirectories = recursive
? this._watchedRecursiveDirectories || (this._watchedRecursiveDirectories = new core.SortedMap({ comparer: this.vfs.stringComparer, sort: "insertion" }))
: this._watchedNonRecursiveDirectories || (this._watchedNonRecursiveDirectories = new core.SortedMap({ comparer: this.vfs.stringComparer, sort: "insertion" }));
const watchedDirectoriesSet = recursive
? this._watchedRecursiveDirectoriesSet || (this._watchedRecursiveDirectoriesSet = new core.SortedSet(this.vfs.stringComparer))
: this._watchedNonRecursiveDirectoriesSet || (this._watchedNonRecursiveDirectoriesSet = new core.SortedSet(this.vfs.stringComparer));
const previousCount = watchedDirectories.get(path) || 0;
if (previousCount === 0) {
watchedDirectoriesSet.add(path);
}
watchedDirectories.set(path, previousCount + 1);
let watcher: ts.FileWatcher | undefined = vfsutils.watchDirectory(this.vfs, path, fileName => {
if (this.watchDirectories) {
cb(fileName);
}
}, recursive);
return {
close: () => {
if (watcher) {
const previousCount = watchedDirectories.get(path) || 0;
if (previousCount === 1) {
watchedDirectories.delete(path);
watchedDirectoriesSet.delete(path);
}
else {
watchedDirectories.set(path, previousCount - 1);
}
watcher.close();
watcher = undefined;
}
}
};
return vfsutils.watchDirectory(this.vfs, path, cb, recursive);
}
public resolvePath(path: string) {
@@ -303,16 +148,12 @@ namespace fakes {
return undefined;
}
public setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]) {
return this.timers.setTimeout(callback, timeout, ...args);
public setTimeout(_callback: (...args: any[]) => void, _timeout: number, ..._args: any[]) {
return ts.notImplemented();
}
public clearTimeout(timeoutId: any): void {
this.timers.clearTimeout(timeoutId);
}
public clearScreen(): void {
this._screenClears++;
public clearTimeout(_timeoutId: any): void {
return ts.notImplemented();
}
// #endregion System members
@@ -327,105 +168,14 @@ namespace fakes {
// #endregion FormatDiagnosticsHost members
// #region ServerHost members
public setImmediate(callback: (...args: any[]) => void, ...args: any[]): any {
return this.timers.setImmediate(callback, args);
public setImmediate(_callback: (...args: any[]) => void, ..._args: any[]): any {
return ts.notImplemented();
}
public clearImmediate(timeoutId: any): void {
this.timers.clearImmedate(timeoutId);
public clearImmediate(_timeoutId: any): void {
return ts.notImplemented();
}
// #endregion ServerHost members
public getOutput(): ReadonlyArray<string> {
return this._output;
}
public clearOutput() {
this._output.length = 0;
}
public getTrace(): ReadonlyArray<string> {
return this._trace;
}
public clearTrace() {
this._trace.length = 0;
}
// expectations
public checkTimeoutQueueLength(expected: number) {
const callbacksCount = this.timers.getPending({ kind: "timeout", ms: this.timers.remainingTime }).length;
assert.equal(callbacksCount, expected, `expected ${expected} timeout callbacks queued but found ${callbacksCount}.`);
}
public checkTimeoutQueueLengthAndRun(count: number) {
this.checkTimeoutQueueLength(count);
this.runQueuedTimeoutCallbacks();
}
public runQueuedImmediateCallbacks() {
try {
this.timers.executeImmediates();
}
catch (e) {
if (e !== FakeServerHost.processExitSentinel) {
throw e;
}
}
}
public runQueuedTimeoutCallbacks() {
try {
this.timers.advanceToEnd();
}
catch (e) {
if (e !== FakeServerHost.processExitSentinel) {
throw e;
}
}
}
public checkOutputContains(expected: Iterable<string>) {
const mapExpected = new Set(expected);
const mapSeen = new Set<string>();
for (const f of this._output) {
assert.isFalse(mapSeen.has(f), `Already found ${f} in ${JSON.stringify(this._output)}`);
if (mapExpected.has(f)) {
mapExpected.delete(f);
mapSeen.add(f);
}
}
assert.equal(mapExpected.size, 0, `Output is missing ${JSON.stringify(ts.flatMap(Array.from(mapExpected.keys()), key => key))} in ${JSON.stringify(this._output)}`);
}
public checkOutputDoesNotContain(notExpected: Iterable<string>) {
const mapExpectedToBeAbsent = new Set(notExpected);
for (const f of this._output) {
assert.isFalse(mapExpectedToBeAbsent.has(f), `Contains ${f} in ${JSON.stringify(this._output)}`);
}
}
public checkWatchedFiles(expected: Iterable<string>) {
return checkSortedSet(this._watchedFilesSet, expected);
}
public checkWatchedDirectories(expected: Iterable<string>, recursive = false) {
return checkSortedSet(recursive ? this._watchedRecursiveDirectoriesSet : this._watchedNonRecursiveDirectoriesSet, expected);
}
public checkScreenClears(expected: number) {
assert.equal(this._screenClears, expected);
}
}
}
function checkSortedSet<T>(set: ReadonlySet<T> | undefined, values: Iterable<T>) {
const array = Array.from(values);
const size = set ? set.size : 0;
assert.strictEqual(size, array.length, `Actual: ${set ? Array.from(set) : []}, expected: ${array}.`);
if (set) {
for (const value of array) {
assert.isTrue(set.has(value));
}
}
}
}
+3 -2
View File
@@ -73,10 +73,10 @@
"../services/codefixes/disableJsDiagnostics.ts",
"harness.ts",
"assert.ts",
"core.ts",
"utils.ts",
"typemock.ts",
"events.ts",
"documents.ts",
"vpath.ts",
@@ -101,6 +101,7 @@
"./parallel/host.ts",
"./parallel/worker.ts",
"runner.ts",
"virtualFileSystemWithWatch.ts",
"../server/protocol.ts",
"../server/session.ts",
"../server/client.ts",
-41
View File
@@ -1,41 +0,0 @@
// NOTE: This namespace re-exports all of the exports from the typemock private package.
// typemock library
namespace typemock {
const module = require("typemock");
typemock.Arg = module.Arg;
typemock.Times = module.Times;
typemock.Mock = module.Mock;
typemock.Spy = module.Spy;
typemock.Inject = module.Inject;
typemock.Timers = module.Timers;
typemock.spy = module.spy;
}
declare module "typemock_" {
import * as typemock_ from "typemock";
global {
namespace typemock {
export import Arg = typemock_.Arg;
export import Times = typemock_.Times;
export import Mock = typemock_.Mock;
export import Spy = typemock_.Spy;
export import Returns = typemock_.Returns;
export import Throws = typemock_.Throws;
export import ThisArg = typemock_.ThisArg;
export import Callback = typemock_.Callback;
export import Fallback = typemock_.Fallback;
export import Setup = typemock_.Setup;
export import Callable = typemock_.Callable;
export import Constructable = typemock_.Constructable;
export import Inject = typemock_.Inject;
export import Timers = typemock_.Timers;
export import Timer = typemock_.Timer;
export import Timeout = typemock_.Timeout;
export import Interval = typemock_.Interval;
export import Immediate = typemock_.Immediate;
export import AnimationFrame = typemock_.AnimationFrame;
export import spy = typemock_.spy;
}
}
}
File diff suppressed because it is too large. Load diff
+8 -6
View File
@@ -111,7 +111,7 @@ namespace ts {
function runBaseline(extension: Extension) {
const path = "/a" + extension;
const program = makeProgram({ path, content: t.source }, includeLib);
const program = makeProgram(path, t.source, includeLib);
if (hasSyntacticDiagnostics(program)) {
// Don't bother generating JS baselines for inputs that aren't valid JS.
@@ -146,18 +146,19 @@ namespace ts {
const newTextWithRename = newText.slice(0, renameLocation) + "/*RENAME*/" + newText.slice(renameLocation);
data.push(newTextWithRename);
const diagProgram = makeProgram({ path, content: newText }, includeLib);
const diagProgram = makeProgram(path, newText, includeLib);
assert.isFalse(hasSyntacticDiagnostics(diagProgram));
}
return data.join(newLineCharacter);
});
}
function makeProgram(f: {path: string, content: string }, includeLib?: boolean) {
function makeProgram(path: string, content: string, includeLib?: boolean) {
// libFile is expensive to parse repeatedly - only test when required
const host = new fakes.FakeServerHost({ lib: includeLib }, /*files*/ { [f.path]: f.content });
const fs = new vfs.FileSystem(/*ignoreCase*/ true, { files: { [path]: content } });
const host = new fakes.ServerHost(fs, { lib: includeLib });
const projectService = projectSystem.createProjectService(host);
projectService.openClientFile(f.path);
projectService.openClientFile(path);
const program = projectService.inferredProjects[0].getLanguageService().getProgram();
return program;
}
@@ -175,7 +176,8 @@ namespace ts {
if (!selectionRange) {
throw new Error(`Test ${caption} does not specify selection range`);
}
const host = new fakes.FakeServerHost({ lib: true }, /*files*/ { "/a.ts": t.source });
const fs = new vfs.FileSystem(/*ignoreCase*/ true, { files: { "/a.ts": t.source } });
const host = new fakes.ServerHost(fs, { lib: true });
const projectService = projectSystem.createProjectService(host);
projectService.openClientFile("/a.ts");
const program = projectService.inferredProjects[0].getLanguageService().getProgram();
+144 -99
View File
@@ -1,7 +1,6 @@
/// <reference path="../harness.ts" />
/// <reference path="./tsserverProjectSystem.ts" />
/// <reference path="../../server/typingsInstaller/typingsInstaller.ts" />
/// <reference path="../fakes.ts" />
namespace ts.projectSystem {
describe("Project errors", () => {
@@ -31,131 +30,177 @@ namespace ts.projectSystem {
}
it("external project - diagnostics for missing files", () => {
const host = new fakes.FakeServerHost({ safeList: true, lib: true }, /*files*/ {
"/a/b/app.ts": ``,
});
const projectFileName = "/a/b/test.csproj";
const file1 = {
path: "/a/b/app.ts",
content: ""
};
const file2 = {
path: "/a/b/applib.ts",
content: ""
};
const host = createServerHost([file1, libFile]);
const session = createSession(host);
const projectService = session.getProjectService();
projectService.openExternalProject({
projectFileName,
options: {},
rootFiles: toExternalFiles(["/a/b/app.ts", "/a/b/applib.ts"])
});
const projectFileName = "/a/b/test.csproj";
const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = {
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName }
};
// only file1 exists - expect error
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags1 = sendCompilerOptionsDiagnosticsRequest(session, { projectFileName }, /*seq*/ 2);
checkDiagnosticsWithLinePos(diags1, ["File '/a/b/applib.ts' not found."]);
{
projectService.openExternalProject({
projectFileName,
options: {},
rootFiles: toExternalFiles([file1.path, file2.path])
});
host.vfs.unlinkSync("/a/b/app.ts");
host.vfs.writeFileSync("/a/b/applib.ts", ``);
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[];
// only file1 exists - expect error
checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]);
}
host.reloadFS([file2, libFile]);
{
// only file2 exists - expect error
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[];
checkDiagnosticsWithLinePos(diags, ["File '/a/b/app.ts' not found."]);
}
// only file2 exists - expect error
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags2 = sendCompilerOptionsDiagnosticsRequest(session, { projectFileName }, /*seq*/ 2);
checkDiagnosticsWithLinePos(diags2, ["File '/a/b/app.ts' not found."]);
host.vfs.writeFileSync("/a/b/app.ts", ``);
// both files exist - expect no errors
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags3 = sendCompilerOptionsDiagnosticsRequest(session, { projectFileName }, /*seq*/ 2);
checkDiagnosticsWithLinePos(diags3, []);
host.reloadFS([file1, file2, libFile]);
{
// both files exist - expect no errors
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[];
checkDiagnosticsWithLinePos(diags, []);
}
});
it("configured projects - diagnostics for missing files", () => {
const host = new fakes.FakeServerHost({ safeList: true, lib: true }, /*files*/ {
"/a/b/app.ts": ``,
"/a/b/tsconfig.json": `{ "files": ["app.ts", "applib.ts"] }`,
});
const file1 = {
path: "/a/b/app.ts",
content: ""
};
const file2 = {
path: "/a/b/applib.ts",
content: ""
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) })
};
const host = createServerHost([file1, config, libFile]);
const session = createSession(host);
const projectService = session.getProjectService();
openFilesForSession(["/a/b/app.ts"], session);
openFilesForSession([file1], session);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const project = configuredProjectAt(projectService, 0);
const diags1 = sendCompilerOptionsDiagnosticsRequest(session, { projectFileName: project.getProjectName() }, /*seq*/ 2);
checkDiagnosticsWithLinePos(diags1, ["File '/a/b/applib.ts' not found."]);
const compilerOptionsRequest: server.protocol.CompilerOptionsDiagnosticsRequest = {
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName: project.getProjectName() }
};
let diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[];
checkDiagnosticsWithLinePos(diags, ["File '/a/b/applib.ts' not found."]);
host.vfs.writeFileSync("/a/b/applib.ts", ``);
host.reloadFS([file1, file2, config, libFile]);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const diags2 = sendCompilerOptionsDiagnosticsRequest(session, { projectFileName: project.getProjectName() }, /*seq*/ 2);
checkDiagnosticsWithLinePos(diags2, []);
diags = session.executeCommand(compilerOptionsRequest).response as server.protocol.DiagnosticWithLinePosition[];
checkDiagnosticsWithLinePos(diags, []);
});
it("configured projects - diagnostics for corrupted config 1", () => {
const host = new fakes.FakeServerHost({ safeList: true }, /*files*/ {
"/a/b/app.ts": ``,
"/a/b/lib.ts": ``,
"/a/b/tsconfig.json": ` "files": ["app.ts", "lib.ts"] }`,
});
const file1 = {
path: "/a/b/app.ts",
content: ""
};
const file2 = {
path: "/a/b/lib.ts",
content: ""
};
const correctConfig = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) })
};
const corruptedConfig = {
path: correctConfig.path,
content: correctConfig.content.substr(1)
};
const host = createServerHost([file1, file2, corruptedConfig]);
const projectService = createProjectService(host);
projectService.openClientFile("/a/b/app.ts");
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject1 = find(projectService.synchronizeProjectList([]), f => f.info.projectName === "/a/b/tsconfig.json");
assert.isTrue(configuredProject1 !== undefined, "should find configured project");
checkProjectErrors(configuredProject1, []);
const projectErrors1 = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors1, ["'{' expected."]);
assert.isNotNull(projectErrors1[0].file);
assert.equal(projectErrors1[0].file.fileName, "/a/b/tsconfig.json");
projectService.openClientFile(file1.path);
{
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f);
assert.isTrue(configuredProject !== undefined, "should find configured project");
checkProjectErrors(configuredProject, []);
const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors, [
"'{' expected."
]);
assert.isNotNull(projectErrors[0].file);
assert.equal(projectErrors[0].file.fileName, corruptedConfig.path);
}
// fix config and trigger watcher
host.vfs.writeFileSync("/a/b/tsconfig.json", `{ "files": ["app.ts", "lib.ts"] }`);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject2 = find(projectService.synchronizeProjectList([]), f => f.info.projectName === "/a/b/tsconfig.json");
assert.isTrue(configuredProject2 !== undefined, "should find configured project");
checkProjectErrors(configuredProject2, []);
const projectErrors2 = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors2, []);
host.reloadFS([file1, file2, correctConfig]);
{
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f);
assert.isTrue(configuredProject !== undefined, "should find configured project");
checkProjectErrors(configuredProject, []);
const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors, []);
}
});
it("configured projects - diagnostics for corrupted config 2", () => {
const host = new fakes.FakeServerHost({ safeList: true }, /*files*/ {
"/a/b/app.ts": ``,
"/a/b/lib.ts": ``,
"/a/b/tsconfig.json": `{ "files": ["app.ts", "lib.ts"] }`,
});
const file1 = {
path: "/a/b/app.ts",
content: ""
};
const file2 = {
path: "/a/b/lib.ts",
content: ""
};
const correctConfig = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ files: [file1, file2].map(f => getBaseFileName(f.path)) })
};
const corruptedConfig = {
path: correctConfig.path,
content: correctConfig.content.substr(1)
};
const host = createServerHost([file1, file2, correctConfig]);
const projectService = createProjectService(host);
projectService.openClientFile("/a/b/app.ts");
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject1 = find(projectService.synchronizeProjectList([]), f => f.info.projectName === "/a/b/tsconfig.json");
assert.isTrue(configuredProject1 !== undefined, "should find configured project");
checkProjectErrors(configuredProject1, []);
const projectErrors1 = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors1, []);
projectService.openClientFile(file1.path);
{
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f);
assert.isTrue(configuredProject !== undefined, "should find configured project");
checkProjectErrors(configuredProject, []);
const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors, []);
}
// break config and trigger watcher
host.vfs.writeFileSync("/a/b/tsconfig.json", ` "files": ["app.ts", "lib.ts"] }`);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject2 = find(projectService.synchronizeProjectList([]), f => f.info.projectName === "/a/b/tsconfig.json");
assert.isTrue(configuredProject2 !== undefined, "should find configured project");
checkProjectErrors(configuredProject2, []);
const projectErrors2 = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors2, ["'{' expected."]);
assert.isNotNull(projectErrors2[0].file);
assert.equal(projectErrors2[0].file.fileName, "/a/b/tsconfig.json");
host.reloadFS([file1, file2, corruptedConfig]);
{
projectService.checkNumberOfProjects({ configuredProjects: 1 });
const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f);
assert.isTrue(configuredProject !== undefined, "should find configured project");
checkProjectErrors(configuredProject, []);
const projectErrors = configuredProjectAt(projectService, 0).getAllProjectErrors();
checkProjectErrorsWorker(projectErrors, [
"'{' expected."
]);
assert.isNotNull(projectErrors[0].file);
assert.equal(projectErrors[0].file.fileName, corruptedConfig.path);
}
});
});
}
+86 -64
View File
@@ -1,6 +1,5 @@
/// <reference path="..\harness.ts" />
/// <reference path="..\..\harness\harnessLanguageService.ts" />
/// <reference path="../fakes.ts" />
namespace ts {
@@ -885,6 +884,10 @@ namespace ts {
});
});
type FileOrFolder = ts.TestFSWithWatch.FileOrFolder;
import createTestSystem = ts.TestFSWithWatch.createWatchedSystem;
import libFile = ts.TestFSWithWatch.libFile;
describe("isProgramUptoDate should return true when there is no change in compiler options and", () => {
function verifyProgramIsUptoDate(
program: Program,
@@ -917,37 +920,48 @@ namespace ts {
verifyProgramIsUptoDate(program, fileNames, options);
}
function verifyProgram(vfs: vfs.FileSystem, rootFiles: string[], options: CompilerOptions, configFile: string) {
const system = new fakes.FakeServerHost({ vfs });
function verifyProgram(files: FileOrFolder[], rootFiles: string[], options: CompilerOptions, configFile: string) {
const system = createTestSystem(files);
verifyProgramWithoutConfigFile(system, rootFiles, options);
verifyProgramWithConfigFile(system, configFile);
}
it("has empty options", () => {
const file1 = "/a/b/file1.ts";
const file2 = "/a/b/file2.ts";
const configFile = "/a/b/tsconfig.json";
const fs = new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/", files: {
[file1]: "let x = 1",
[file2]: "let y = 1",
[configFile]: "{}",
[fakes.FakeServerHost.libPath]: fakes.FakeServerHost.libContent,
}});
verifyProgram(fs, [file1, file2], {}, configFile);
const file1: FileOrFolder = {
path: "/a/b/file1.ts",
content: "let x = 1"
};
const file2: FileOrFolder = {
path: "/a/b/file2.ts",
content: "let y = 1"
};
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: "{}"
};
verifyProgram([file1, file2, libFile, configFile], [file1.path, file2.path], {}, configFile.path);
});
it("has lib specified in the options", () => {
const app = "/src/app.ts";
const configFile = "/src/tsconfig.json";
const compilerOptions: CompilerOptions = { lib: ["es5", "es2015.promise"] };
const fs = new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/", files: {
[app]: "var x: Promise<string>;",
[configFile]: JSON.stringify({ compilerOptions }),
"/compiler/lib.es5.d.ts": "declare const eval: any;",
"/compiler/lib.es2015.promise.d.ts": "declare class Promise<T> {}",
}});
verifyProgram(fs, [app], compilerOptions, configFile);
const app: FileOrFolder = {
path: "/src/app.ts",
content: "var x: Promise<string>;"
};
const configFile: FileOrFolder = {
path: "/src/tsconfig.json",
content: JSON.stringify({ compilerOptions })
};
const es5Lib: FileOrFolder = {
path: "/compiler/lib.es5.d.ts",
content: "declare const eval: any"
};
const es2015Promise: FileOrFolder = {
path: "/compiler/lib.es2015.promise.d.ts",
content: "declare class Promise<T> {}"
};
verifyProgram([app, configFile, es5Lib, es2015Promise], [app.path], compilerOptions, configFile.path);
});
it("has paths specified in the options", () => {
@@ -961,26 +975,31 @@ namespace ts {
]
}
};
const app = "/src/packages/framework/app.ts";
const configFile = "/src/tsconfig.json";
const fs = new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/", files: {
[app]:
`import classC from "module1/lib/file1";\n` +
`import classD from "module3/file3";\n` +
`let x = new classC();\n` +
`let y = new classD();`,
"/src/packages/mail/data/module1/lib/file1.ts":
`import classC from "module2/file2";\n` +
`export default classC;`,
"/src/packages/mail/data/module1/lib/module2/file2.ts":
`class classC { method2() { return "hello"; } }\n` +
`export default classC;`,
"/src/packages/styles/module3/file3.ts":
`class classD { method() { return 10; } }\n` +
`export default classD;`,
[configFile]: JSON.stringify({ compilerOptions }),
}});
verifyProgram(fs, [app], compilerOptions, configFile);
const app: FileOrFolder = {
path: "/src/packages/framework/app.ts",
content: 'import classc from "module1/lib/file1";\
import classD from "module3/file3";\
let x = new classc();\
let y = new classD();'
};
const module1: FileOrFolder = {
path: "/src/packages/mail/data/module1/lib/file1.ts",
content: 'import classc from "module2/file2";export default classc;',
};
const module2: FileOrFolder = {
path: "/src/packages/mail/data/module1/lib/module2/file2.ts",
content: 'class classc { method2() { return "hello"; } }\nexport default classc',
};
const module3: FileOrFolder = {
path: "/src/packages/styles/module3/file3.ts",
content: "class classD { method() { return 10; } }\nexport default classD;"
};
const configFile: FileOrFolder = {
path: "/src/tsconfig.json",
content: JSON.stringify({ compilerOptions })
};
verifyProgram([app, module1, module2, module3, libFile, configFile], [app.path], compilerOptions, configFile.path);
});
it("has include paths specified in tsconfig file", () => {
@@ -994,27 +1013,30 @@ namespace ts {
]
}
};
const configFile = "/src/tsconfig.json";
const fs = new vfs.FileSystem(/*ignoreCase*/ false, { cwd: "/", files: {
"/src/packages/framework/app.ts":
`import classC from "module1/lib/file1";\n` +
`import classD from "module3/file3";\n` +
`let x = new classC();\n` +
`let y = new classD();`,
"/src/packages/mail/data/module1/lib/file1.ts":
`import classC from "module2/file2";\n` +
`export default classC;`,
"/src/packages/mail/data/module1/lib/module2/file2.ts":
`class classC { method2() { return "hello"; } }\n` +
`export default classC;`,
"/src/packages/styles/module3/file3.ts":
`class classD { method() { return 10; } }\n` +
`export default classD;`,
[configFile]:
JSON.stringify({ compilerOptions, include: ["packages/**/*.ts"] }),
}});
const watchingSystemHost = new fakes.FakeServerHost({ vfs: fs });
verifyProgramWithConfigFile(watchingSystemHost, configFile);
const app: FileOrFolder = {
path: "/src/packages/framework/app.ts",
content: 'import classc from "module1/lib/file1";\
import classD from "module3/file3";\
let x = new classc();\
let y = new classD();'
};
const module1: FileOrFolder = {
path: "/src/packages/mail/data/module1/lib/file1.ts",
content: 'import classc from "module2/file2";export default classc;',
};
const module2: FileOrFolder = {
path: "/src/packages/mail/data/module1/lib/module2/file2.ts",
content: 'class classc { method2() { return "hello"; } }\nexport default classc',
};
const module3: FileOrFolder = {
path: "/src/packages/styles/module3/file3.ts",
content: "class classD { method() { return 10; } }\nexport default classD;"
};
const configFile: FileOrFolder = {
path: "/src/tsconfig.json",
content: JSON.stringify({ compilerOptions, include: ["packages/**/*.ts"] })
};
verifyProgramWithConfigFile(createTestSystem([app, module1, module2, module3, libFile, configFile]), configFile.path);
});
});
}
+57 -78
View File
@@ -1,59 +1,46 @@
/// <reference path="../harness.ts" />
/// <reference path="./tsserverProjectSystem.ts" />
/// <reference path="../fakes.ts" />
namespace ts.projectSystem {
describe("project telemetry", () => {
it("does nothing for inferred project", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a.js": "",
});
const et = new TestServerEventManager(host);
et.service.openClientFile("/a.js");
const file = makeFile("/a.js");
const et = new TestServerEventManager([file]);
et.service.openClientFile(file.path);
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
});
it("only sends an event once", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a/a.ts": ``,
"/b.ts": ``,
"/a/tsconfig.json": `{}`,
});
const file = makeFile("/a/a.ts");
const file2 = makeFile("/b.ts");
const tsconfig = makeFile("/a/tsconfig.json", {});
const et = new TestServerEventManager(host);
et.service.openClientFile("/a/a.ts");
et.assertProjectInfoTelemetryEvent({}, "/a/tsconfig.json");
const et = new TestServerEventManager([file, file2, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({}, tsconfig.path);
et.service.closeClientFile("/a/a.ts");
et.service.closeClientFile(file.path);
checkNumberOfProjects(et.service, { configuredProjects: 1 });
et.service.openClientFile("/b.ts");
et.service.openClientFile(file2.path);
checkNumberOfProjects(et.service, { inferredProjects: 1 });
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
et.service.openClientFile("/a/a.ts");
et.service.openClientFile(file.path);
checkNumberOfProjects(et.service, { configuredProjects: 1, inferredProjects: 1 });
et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent);
});
it("counts files by extension", () => {
const files = ["ts.ts", "tsx.tsx", "moo.ts", "dts.d.ts", "jsx.jsx", "js.js", "badExtension.badExtension"].map(f => makeFile(`/src/${f}`));
const notIncludedFile = makeFile("/bin/ts.js");
const compilerOptions: ts.CompilerOptions = { allowJs: true };
const host = new fakes.FakeServerHost({}, /*files*/ {
"/src/ts.ts": ``,
"/src/tsx.tsx": ``,
"/src/moo.ts": ``,
"/src/dts.d.ts": ``,
"/src/jsx.jsx": ``,
"/src/js.js": ``,
"/src/badExtension.badExtension": ``,
"/bin/ts.js": ``,
"/tsconfig.json": JSON.stringify({ compilerOptions, include: ["src"] }),
});
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, include: ["src"] });
const et = new TestServerEventManager(host);
et.service.openClientFile("/src/ts.ts");
const et = new TestServerEventManager([...files, notIncludedFile, tsconfig]);
et.service.openClientFile(files[0].path);
et.assertProjectInfoTelemetryEvent({
fileStats: { ts: 2, tsx: 1, js: 1, jsx: 1, dts: 1 },
compilerOptions,
@@ -62,11 +49,8 @@ namespace ts.projectSystem {
});
it("works with external project", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a.ts": ``,
});
const et = new TestServerEventManager(host);
const file1 = makeFile("/a.ts");
const et = new TestServerEventManager([file1]);
const compilerOptions: ts.server.protocol.CompilerOptions = { strict: true };
const projectFileName = "/hunter2/foo.csproj";
@@ -75,7 +59,7 @@ namespace ts.projectSystem {
// TODO: Apparently compilerOptions is mutated, so have to repeat it here!
et.assertProjectInfoTelemetryEvent({
projectId: core.sha1("/hunter2/foo.csproj"),
projectId: Harness.mockHash("/hunter2/foo.csproj"),
compilerOptions: { strict: true },
compileOnSave: true,
// These properties can't be present for an external project, so they are undefined instead of false.
@@ -97,7 +81,7 @@ namespace ts.projectSystem {
function open(): void {
et.service.openExternalProject({
rootFiles: toExternalFiles(["/a.ts"]),
rootFiles: toExternalFiles([file1.path]),
options: compilerOptions,
projectFileName,
});
@@ -106,6 +90,8 @@ namespace ts.projectSystem {
});
it("does not expose paths", () => {
const file = makeFile("/a.ts");
const compilerOptions: ts.CompilerOptions = {
project: "",
outFile: "hunter2.js",
@@ -160,14 +146,10 @@ namespace ts.projectSystem {
lib: ["es6", "dom"],
};
(compilerOptions as any).unknownCompilerOption = "hunter2"; // These are always ignored.
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, files: ["/a.ts"] });
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a.ts": ``,
"/tsconfig.json": JSON.stringify({ compilerOptions, files: ["/a.ts"] }),
});
const et = new TestServerEventManager(host);
et.service.openClientFile("/a.ts");
const et = new TestServerEventManager([file, tsconfig]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
compilerOptions: safeCompilerOptions,
@@ -176,20 +158,18 @@ namespace ts.projectSystem {
});
it("sends telemetry for extends, files, include, exclude, and compileOnSave", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/hunter2/a.ts": ``,
"/tsconfig.json": JSON.stringify({
compilerOptions: {},
extends: "hunter2.json",
files: ["hunter2/a.ts"],
include: ["hunter2"],
exclude: ["hunter2"],
compileOnSave: true,
})
const file = makeFile("/hunter2/a.ts");
const tsconfig = makeFile("/tsconfig.json", {
compilerOptions: {},
extends: "hunter2.json",
files: ["hunter2/a.ts"],
include: ["hunter2"],
exclude: ["hunter2"],
compileOnSave: true,
});
const et = new TestServerEventManager(host);
et.service.openClientFile("/hunter2/a.ts");
const et = new TestServerEventManager([tsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
extends: true,
files: true,
@@ -209,22 +189,20 @@ namespace ts.projectSystem {
};
it("sends telemetry for typeAcquisition settings", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a.js": ``,
"/jsconfig.json": JSON.stringify({
compilerOptions: {},
typeAcquisition: {
enable: true,
enableAutoDiscovery: false,
include: ["hunter2", "hunter3"],
exclude: [],
},
})
const file = makeFile("/a.js");
const jsconfig = makeFile("/jsconfig.json", {
compilerOptions: {},
typeAcquisition: {
enable: true,
enableAutoDiscovery: false,
include: ["hunter2", "hunter3"],
exclude: [],
},
});
const et = new TestServerEventManager(host);
et.service.openClientFile("/a.js");
const et = new TestServerEventManager([jsconfig, file]);
et.service.openClientFile(file.path);
et.assertProjectInfoTelemetryEvent({
projectId: core.sha1("/jsconfig.json"),
projectId: Harness.mockHash("/jsconfig.json"),
fileStats: fileStats({ js: 1 }),
compilerOptions: autoJsCompilerOptions,
typeAcquisition: {
@@ -237,17 +215,14 @@ namespace ts.projectSystem {
});
it("detects whether language service was disabled", () => {
const host = new fakes.FakeServerHost({}, /*files*/ {
"/a.js": ``,
"/jsconfig.json": `{}`,
});
const et = new TestServerEventManager(host);
const file = makeFile("/a.js");
const tsconfig = makeFile("/jsconfig.json", {});
const et = new TestServerEventManager([tsconfig, file]);
et.host.getFileSize = () => server.maxProgramSizeForNonTsFiles + 1;
et.service.openClientFile("/a.js");
et.service.openClientFile(file.path);
et.getEvent<server.ProjectLanguageServiceStateEvent>(server.ProjectLanguageServiceStateEvent);
et.assertProjectInfoTelemetryEvent({
projectId: core.sha1("/jsconfig.json"),
projectId: Harness.mockHash("/jsconfig.json"),
fileStats: fileStats({ js: 1 }),
compilerOptions: autoJsCompilerOptions,
configFileName: "jsconfig.json",
@@ -260,4 +235,8 @@ namespace ts.projectSystem {
});
});
});
function makeFile(path: string, content: {} = ""): projectSystem.FileOrFolder {
return { path, content: isString(content) ? "" : JSON.stringify(content) };
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+11 -3
View File
@@ -72,11 +72,17 @@ namespace utils {
let match: RegExpExecArray | null;
let lineStart = 0;
while (match = lineTerminatorRegExp.exec(text)) {
lines.push(text.slice(lineStart, match.index));
lineTerminators.push(match[0]);
if (lineStart !== match.index || lines.length > 0) {
lines.push(text.slice(lineStart, match.index));
lineTerminators.push(match[0]);
}
lineStart = match.index + match[0].length;
}
if (lineStart < text.length) {
lines.push(text.slice(lineStart));
}
const indentation = guessIndentation(lines);
let result = "";
@@ -84,7 +90,9 @@ namespace utils {
const lineText = lines[i];
const line = indentation ? lineText.slice(indentation) : lineText;
result += line;
result += lineTerminators[i];
if (i < lineTerminators.length) {
result += lineTerminators[i];
}
}
return result;
}
+29
View File
@@ -17,6 +17,9 @@ namespace vfsutils {
* Posix-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.)
*/
export const builtFolder = "/.ts";
export const tscPath = builtFolder + "/tsc.js";
export const libPath = builtFolder + "/lib.d.ts";
export const safelistPath = "/safelist.json";
/**
* Posix-style path to additional test libraries
@@ -32,6 +35,9 @@ namespace vfsutils {
* DOS-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.)
*/
export const dosBuiltFolder = "c:" + builtFolder;
export const dosTscPath = dosBuiltFolder + "/tsc.js";
export const dosLibPath = dosBuiltFolder + "/lib.d.ts";
export const dosSafelistPath = dosBuiltFolder + "/safelist.json";
/**
* DOS-style path to additional test libraries
@@ -43,6 +49,29 @@ namespace vfsutils {
*/
export const dosSrcFolder = "c:" + srcFolder;
/** Default safelist.json content used by a number of tests. */
export const safelistContent = utils.dedent`
{
"commander": "commander",
"express": "express",
"jquery": "jquery",
"lodash": "lodash",
"moment": "moment",
"chroma": "chroma-js"
}`;
/** A minimal lib.d.ts used by a number of tests. */
export const emptyLibContent = utils.dedent`
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> {}`;
export function createResolver(io: Harness.IO): vfs.FileSystemResolver {
return {
readdirSync(path: string): string[] {