Skip to content

Remove dependency on chai #20429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Jakefile.js
Original file line number Diff line number Diff line change
Expand Up @@ -795,7 +795,7 @@ compileFile(
/*prereqs*/[builtLocalDirectory, tscFile, tsserverLibraryFile].concat(libraryTargets).concat(servicesSources).concat(harnessSources),
/*prefixes*/[],
/*useBuiltCompiler:*/ true,
/*opts*/ { types: ["node", "mocha", "chai"], lib: "es6" });
/*opts*/ { types: ["node", "mocha"], lib: "es6" });

var internalTests = "internal/";

Expand Down
563 changes: 299 additions & 264 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
},
"devDependencies": {
"@types/browserify": "latest",
"@types/chai": "latest",
"@types/colors": "latest",
"@types/convert-source-map": "latest",
"@types/del": "latest",
Expand All @@ -53,7 +52,6 @@
"xml2js": "^0.4.19",
"browser-resolve": "^1.11.2",
"browserify": "latest",
"chai": "latest",
"convert-source-map": "latest",
"del": "latest",
"gulp": "3.X",
Expand Down
17 changes: 8 additions & 9 deletions src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ namespace FourSlash {
const host = new Utils.MockParseConfigHost(baseDir, /*ignoreCase*/ false, this.inputFiles);

const configJsonObj = ts.parseConfigFileTextToJson(configFileName, this.inputFiles.get(configFileName));
assert.isTrue(configJsonObj.config !== undefined);
assert(configJsonObj.config !== undefined);

const { options, errors } = ts.parseJsonConfigFileContent(configJsonObj.config, host, baseDir);

Expand Down Expand Up @@ -437,7 +437,7 @@ namespace FourSlash {

public goToEachMarker(action: () => void) {
const markers = this.getMarkers();
assert(markers.length);
assert(markers.length !== 0);
for (const marker of markers) {
this.goToMarker(marker);
action();
Expand All @@ -446,7 +446,7 @@ namespace FourSlash {

public goToEachRange(action: () => void) {
const ranges = this.getRanges();
assert(ranges.length);
assert(ranges.length !== 0);
for (const range of ranges) {
this.goToRangeStart(range);
action();
Expand Down Expand Up @@ -793,7 +793,7 @@ namespace FourSlash {
}

const entries = this.getCompletionListAtCaret().entries;
assert.isTrue(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`);
assert(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`);
ts.zipWith(entries, items, (entry, item) => {
assert.equal(entry.name, item, `Unexpected item in completion list`);
});
Expand Down Expand Up @@ -947,7 +947,7 @@ namespace FourSlash {
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) {
const details = this.getCompletionEntryDetails(entryName);

assert(details, "no completion entry available");
assert.isDefined(details, "no completion entry available");

assert.equal(ts.displayPartsToString(details.displayParts), expectedText, this.assertionMessageAtLastKnownMarker("completion entry details text"));

Expand Down Expand Up @@ -1082,7 +1082,7 @@ namespace FourSlash {

public verifyRangesReferenceEachOther(ranges?: Range[]) {
ranges = ranges || this.getRanges();
assert(ranges.length);
assert(ranges.length !== 0);
for (const range of ranges) {
this.verifyReferencesOf(range, ranges);
}
Expand Down Expand Up @@ -1368,7 +1368,6 @@ Actual: ${stringify(fullActual)}`);

public verifyCurrentParameterIsVariable(isVariable: boolean) {
const signature = this.getActiveSignatureHelpItem();
assert.isOk(signature);
assert.equal(isVariable, signature.isVariadic);
}

Expand Down Expand Up @@ -2019,7 +2018,7 @@ Actual: ${stringify(fullActual)}`);
const implementations = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition);

if (negative) {
assert.isTrue(implementations && implementations.length > 0, "Expected at least one implementation but got 0");
assert(implementations && implementations.length > 0, "Expected at least one implementation but got 0");
}
else {
assert.isUndefined(implementations, "Expected implementation list to be empty but implementations returned");
Expand Down Expand Up @@ -3110,7 +3109,7 @@ Actual: ${stringify(fullActual)}`);

if (spanIndex !== undefined) {
const span = this.getTextSpanForRangeAtIndex(spanIndex);
assert.isTrue(TestState.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + entryId));
assert(TestState.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + entryId));
}

assert.equal(item.hasAction, hasAction);
Expand Down
74 changes: 58 additions & 16 deletions src/harness/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,60 @@
/// <reference path="virtualFileSystem.ts" />
/// <reference types="node" />
/// <reference types="mocha" />
/// <reference types="chai" />


// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */

// this will work in the browser via browserify
var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
// chai's builtin `assert.isFalse` is featureful but slow - we don't use those features,
// so we'll just overwrite it as an alterative to migrating a bunch of code off of chai
assert.isFalse = (expr, msg) => { if (expr as any as boolean !== false) throw new Error(msg); };
function assert(expr: boolean, msg?: string | (() => string)): void {
if (!expr) {
throw new Error(typeof msg === "string" ? msg : msg());
}
}
namespace assert {
export function isFalse(expr: boolean, msg = "Expected value to be false."): void {
assert(!expr, msg);
}
export function equal<T>(a: T, b: T, msg = "Expected values to be equal."): void {
assert(a === b, msg);
}
export function notEqual<T>(a: T, b: T, msg = "Expected values to not be equal."): void {
assert(a !== b, msg);
}
export function isDefined(x: {} | null | undefined, msg = "Expected value to be defined."): void {
assert(x !== undefined && x !== null, msg);
}
export function isUndefined(x: {} | null | undefined, msg = "Expected value to be undefined."): void {
assert(x === undefined, msg);
}
export function deepEqual<T>(a: T, b: T, msg?: string): void {
assert(isDeepEqual(a, b), msg || (() => `Expected values to be deeply equal:\nExpected:\n${JSON.stringify(a, undefined, 4)}\nActual:\n${JSON.stringify(b, undefined, 4)}`));
}
export function lengthOf(a: ReadonlyArray<{}>, length: number, msg = "Expected length to match."): void {
assert(a.length === length, msg);
}
export function throws(cb: () => void, msg = "Expected callback to throw"): void {
let threw = false;
try {
cb();
}
catch {
threw = true;
}
assert(threw, msg);
}

function isDeepEqual<T>(a: T, b: T): boolean {
if (a === b) {
Copy link
Member

@weswigham weswigham Dec 8, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have no idea if we have any tests which could trigger this (probably not), but NaN === NaN is false, but I'd generally say one would expect { x: NaN } to deep equal { x: NaN }; ergo there should probably be a clause if (a !== a && b !== b) return true;. Probably a pointless remark unless we start testing more NaNy edgecases, though.

return true;
}
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
return false;
}
const aKeys = Object.keys(a).sort();
const bKeys = Object.keys(b).sort();
return aKeys.length === bKeys.length && aKeys.every((key, i) => bKeys[i] === key && isDeepEqual((a as any)[key], (b as any)[key]));
}
}
declare var __dirname: string; // Node-specific
var global: NodeJS.Global = <any>Function("return this").call(undefined);

Expand Down Expand Up @@ -347,8 +389,8 @@ namespace Utils {
return;
}

assert(array1, "array1");
assert(array2, "array2");
assert(!!array1, "array1");
assert(!!array2, "array2");

assert.equal(array1.length, array2.length, "array1.length !== array2.length");

Expand All @@ -371,8 +413,8 @@ namespace Utils {
return;
}

assert(node1, "node1");
assert(node2, "node2");
assert(!!node1, "node1");
assert(!!node2, "node2");
assert.equal(node1.pos, node2.pos, "node1.pos !== node2.pos");
assert.equal(node1.end, node2.end, "node1.end !== node2.end");
assert.equal(node1.kind, node2.kind, "node1.kind !== node2.kind");
Expand Down Expand Up @@ -402,8 +444,8 @@ namespace Utils {
return;
}

assert(array1, "array1");
assert(array2, "array2");
assert(!!array1, "array1");
assert(!!array2, "array2");
assert.equal(array1.pos, array2.pos, "array1.pos !== array2.pos");
assert.equal(array1.end, array2.end, "array1.end !== array2.end");
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
Expand Down Expand Up @@ -1259,7 +1301,7 @@ namespace Harness {

function findResultCodeFile(fileName: string) {
const sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
assert.isDefined(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
let sourceFileName: string;
const outFile = options.outFile || options.out;
Expand Down Expand Up @@ -1942,7 +1984,7 @@ namespace Harness {
const data = testUnitData[i];
if (ts.getBaseFileName(data.name).toLowerCase() === "tsconfig.json") {
const configJson = ts.parseJsonText(data.name, data.content);
assert.isTrue(configJson.endOfFileToken !== undefined);
assert(configJson.endOfFileToken !== undefined);
let baseDir = ts.normalizePath(ts.getDirectoryPath(data.name));
if (rootDir) {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
Expand Down
5 changes: 2 additions & 3 deletions src/harness/harnessLanguageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,7 @@ namespace Harness.LanguageService {
*/
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
const script: ScriptInfo = this.getScriptInfo(fileName);
assert.isOk(script);

assert(!!script);
return ts.computeLineAndCharacterOfPosition(script.getLineMap(), position);
}
}
Expand Down Expand Up @@ -360,7 +359,7 @@ namespace Harness.LanguageService {
classification: parseInt(result[i + 1])
};

assert.isTrue(t.length > 0, "Result length should be greater than 0, got :" + t.length);
assert(t.length > 0, "Result length should be greater than 0, got :" + t.length);
position += t.length;
}
const finalLexState = parseInt(result[result.length - 1]);
Expand Down
6 changes: 3 additions & 3 deletions src/harness/sourceMapRecorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,10 @@ namespace Harness.SourceMapRecorder {
}

export function recordNewSourceFileSpan(sourceMapSpan: ts.SourceMapSpan, newSourceFileCode: string) {
assert.isTrue(spansOnSingleLine.length === 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario");
assert(spansOnSingleLine.length === 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario");
recordSourceMapSpan(sourceMapSpan);

assert.isTrue(spansOnSingleLine.length === 1);
assert(spansOnSingleLine.length === 1);
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("emittedFile:" + jsFile.fileName);
sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]);
Expand Down Expand Up @@ -331,7 +331,7 @@ namespace Harness.SourceMapRecorder {
function getMarkerId(markerIndex: number) {
let markerId = "";
if (spanMarkerContinues) {
assert.isTrue(markerIndex === 0);
assert(markerIndex === 0);
markerId = "1->";
}
else {
Expand Down
2 changes: 1 addition & 1 deletion src/harness/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"outFile": "../../built/local/run.js",
"declaration": false,
"types": [
"node", "mocha", "chai"
"node", "mocha"
],
"lib": [
"es6",
Expand Down
4 changes: 2 additions & 2 deletions src/harness/unittests/commandLineParsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace ts {

const parsedErrors = parsed.errors;
const expectedErrors = expectedParsedCommandLine.errors;
assert.isTrue(parsedErrors.length === expectedErrors.length, `Expected error: ${JSON.stringify(expectedErrors)}. Actual error: ${JSON.stringify(parsedErrors)}.`);
assert(parsedErrors.length === expectedErrors.length, `Expected error: ${JSON.stringify(expectedErrors)}. Actual error: ${JSON.stringify(parsedErrors)}.`);
for (let i = 0; i < parsedErrors.length; i++) {
const parsedError = parsedErrors[i];
const expectedError = expectedErrors[i];
Expand All @@ -23,7 +23,7 @@ namespace ts {

const parsedFileNames = parsed.fileNames;
const expectedFileNames = expectedParsedCommandLine.fileNames;
assert.isTrue(parsedFileNames.length === expectedFileNames.length, `Expected fileNames: [${JSON.stringify(expectedFileNames)}]. Actual fileNames: [${JSON.stringify(parsedFileNames)}].`);
assert(parsedFileNames.length === expectedFileNames.length, `Expected fileNames: [${JSON.stringify(expectedFileNames)}]. Actual fileNames: [${JSON.stringify(parsedFileNames)}].`);
for (let i = 0; i < parsedFileNames.length; i++) {
const parsedFileName = parsedFileNames[i];
const expectedFileName = expectedFileNames[i];
Expand Down
18 changes: 9 additions & 9 deletions src/harness/unittests/compileOnSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace ts.projectSystem {

const actualResultSingleProjectFileNameList = actualResultSingleProject.fileNames.sort();
const expectedResultSingleProjectFileNameList = map(expectedResultSingleProject.files, f => f.path).sort();
assert.isTrue(
assert(
arrayIsEqualTo(actualResultSingleProjectFileNameList, expectedResultSingleProjectFileNameList),
`For project ${actualResultSingleProject.projectFileName}, the actual result is ${actualResultSingleProjectFileNameList}, while expected ${expectedResultSingleProjectFileNameList}`);
}
Expand Down Expand Up @@ -563,7 +563,7 @@ namespace ts.projectSystem {
session.executeCommand(compileFileRequest);

const expectedEmittedFileName = "/a/b/f1.js";
assert.isTrue(host.fileExists(expectedEmittedFileName));
assert(host.fileExists(expectedEmittedFileName));
assert.equal(host.readFile(expectedEmittedFileName), `"use strict";\r\nexports.__esModule = true;\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`);
});

Expand Down Expand Up @@ -600,11 +600,11 @@ namespace ts.projectSystem {
session.executeCommand(emitRequest);

const expectedOutFileName = "/a/b/dist.js";
assert.isTrue(host.fileExists(expectedOutFileName));
assert(host.fileExists(expectedOutFileName));
const outFileContent = host.readFile(expectedOutFileName);
assert.isTrue(outFileContent.indexOf(file1.content) !== -1);
assert.isTrue(outFileContent.indexOf(file2.content) === -1);
assert.isTrue(outFileContent.indexOf(file3.content) === -1);
assert(outFileContent.indexOf(file1.content) !== -1);
assert(outFileContent.indexOf(file2.content) === -1);
assert(outFileContent.indexOf(file3.content) === -1);
});

it("should use project root as current directory so that compile on save results in correct file mapping", () => {
Expand Down Expand Up @@ -634,19 +634,19 @@ namespace ts.projectSystem {

// Verify js file
const expectedOutFileName = "/root/TypeScriptProject3/TypeScriptProject3/" + outFileName;
assert.isTrue(host.fileExists(expectedOutFileName));
assert(host.fileExists(expectedOutFileName));
const outFileContent = host.readFile(expectedOutFileName);
verifyContentHasString(outFileContent, file1.content);
verifyContentHasString(outFileContent, `//# ${"sourceMappingURL"}=${outFileName}.map`); // Sometimes tools can sometimes see this line as a source mapping url comment, so we obfuscate it a little

// Verify map file
const expectedMapFileName = expectedOutFileName + ".map";
assert.isTrue(host.fileExists(expectedMapFileName));
assert(host.fileExists(expectedMapFileName));
const mapFileContent = host.readFile(expectedMapFileName);
verifyContentHasString(mapFileContent, `"sources":["${inputFileName}"]`);

function verifyContentHasString(content: string, str: string) {
assert.isTrue(stringContains(content, str), `Expected "${content}" to have "${str}"`);
assert(stringContains(content, str), `Expected "${content}" to have "${str}"`);
}
});
});
Expand Down
2 changes: 1 addition & 1 deletion src/harness/unittests/configurationExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ namespace ts {
const caseSensitiveHost = new Utils.MockParseConfigHost(caseSensitiveBasePath, /*useCaseSensitiveFileNames*/ true, testContents);

function verifyDiagnostics(actual: Diagnostic[], expected: {code: number, category: DiagnosticCategory, messageText: string}[]) {
assert.isTrue(expected.length === actual.length, `Expected error: ${JSON.stringify(expected)}. Actual error: ${JSON.stringify(actual)}.`);
assert(expected.length === actual.length, `Expected error: ${JSON.stringify(expected)}. Actual error: ${JSON.stringify(actual)}.`);
for (let i = 0; i < actual.length; i++) {
const actualError = actual[i];
const expectedError = expected[i];
Expand Down
Loading