assert#fail TypeScript Examples
The following examples show how to use
assert#fail.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: file_level_definitions_parser.spec.ts From solc-typed-ast with Apache License 2.0 | 6 votes |
describe("File-level definitions parser samples test", () => {
for (const fileName of searchRecursive(SAMPLES_DIR, (name) => name.endsWith(".sol"))) {
it(fileName, () => {
const contents = fse.readFileSync(fileName).toString();
let tlds;
try {
tlds = parseFileLevelDefinitions(contents);
} catch (e: any) {
fail(
`Failed compiling ${fileName}: msg: ${e.message} loc: ${JSON.stringify(
e.location,
undefined,
2
)}`
);
}
expect(tlds.length).toBeGreaterThan(0);
});
}
});
Example #2
Source File: folderSelector.test.ts From google-drive-vscode with MIT License | 6 votes |
provideFiles(parentFolderId: string): Promise<DriveFile[]> {
return new Promise((resolve) => {
const files: DriveFile[] = [];
switch (parentFolderId) {
case 'root':
files.push({ iconLink: 'http://www.mylink.com/folder', id: 'sub-folder-id', name: 'My Nice subfolder', type: FileType.DIRECTORY, size: 0, createdTime: 1341393000000, modifiedTime: 1341393000000 });
files.push({ iconLink: 'http://www.mylink.com/folder', id: '1C7udIKXCkxsvXO37gCBpfzrHihn7777z', name: 'Other folder', type: FileType.DIRECTORY, size: 0, createdTime: 1341393000000, modifiedTime: 1341393000000 });
files.push({ iconLink: 'http://www.mylink.com/csv', id: '1C7udIKXLkxsvXO37gCBpfzrHihn9wocz', name: 'myTable.csv', type: FileType.FILE, size: 1226, createdTime: 1341393000000, modifiedTime: 1341393000000 });
break;
case 'sub-folder-id':
files.push({ iconLink: 'http://www.mylink.com/jpg', id: '1C7udIKXCkxsvjO37gCBpfzrHihn9wocz', name: 'myPicture.jpg', type: FileType.FILE, size: 17864, createdTime: 1341393000000, modifiedTime: 1341393000000 });
files.push({ iconLink: 'http://www.mylink.com/png', id: '1C7udIKXCkxsvXO47gCBpfzrHihn9wocz', name: 'myOtherPicture.png', type: FileType.FILE, size: 2145, createdTime: 1341393000000, modifiedTime: 1341393000000 });
files.push({ iconLink: 'http://www.mylink.com/bmp', id: '1C7udIKXCkxsvXO37gCBpfzDHihn9wocz', name: 'myThirdPicture.bmp', type: FileType.FILE, size: 8912674, createdTime: 1341393000000, modifiedTime: 1341393000000 });
break;
default:
fail('Invalid parent folder');
}
resolve(files);
});
}
Example #3
Source File: il.test.ts From UsTaxes with GNU Affero General Public License v3.0 | 6 votes |
withStateReturn = (
info: Information,
logContext: fc.ContextValue,
test: (f1040Forms: [F1040, Form[]], stateForms: StateForm[]) => void
): void => {
const f1040Result = create1040(info, [])
if (isLeft(f1040Result)) {
// ignore error infos with no 1040
logContext.log(f1040Result.left.join(';'))
return
}
const [f1040] = f1040Result.right
const stateReturn = createStateReturn(f1040)
if (isLeft(stateReturn)) {
fail(stateReturn.left.join(';'))
}
test(f1040Result.right, stateReturn.right)
}
Example #4
Source File: entity.test.ts From jmix-frontend with Apache License 2.0 | 5 votes |
function findTestEntity(name: string) {
const entity = projectModel.entities.find((e: any) => e.name === name);
if (entity == null) {
fail('Cannot find test entity');
}
return entity;
}
Example #5
Source File: create.ts From bedrock-cli with MIT License | 5 votes |
validateGitUrl = async (
gitUrl: string,
exitFn: (status: number) => void
): Promise<void> => {
if (gitUrl === "") {
return;
}
let isHelmConfigHttp = true;
try {
new URL(gitUrl);
} catch (err) {
logger.warn(
`Provided helm git URL is an invalid http/https URL: ${gitUrl}`
);
isHelmConfigHttp = false;
}
// We might be looking at a git+ssh URL ie: [email protected]:/path/to/git
if (!isHelmConfigHttp) {
try {
const parsedSshUrl = sshUrl.parse(gitUrl);
// Git url parsed by node-ssh-url will have a `user` field if it resembles
// [email protected]:v3/bhnook/test/hld
if (parsedSshUrl.user === null) {
fail("Not a valid git+ssh url");
}
} catch (err) {
logError(
buildError(
errorStatusCode.VALIDATION_ERR,
{
errorKey: "service-create-cmd-invalid-helm-url-err",
values: [gitUrl],
},
err
)
);
await exitFn(1);
return;
}
}
}
Example #6
Source File: search-contracts.test.ts From ib with MIT License | 5 votes |
describe("RxJS Wrapper: searchContracts()", () => {
test("Error Event", (done) => {
const apiNext = new IBApiNext();
const api = (apiNext as unknown as Record<string, unknown>).api as IBApi;
// emit a error event and verify RxJS result
const testValue = "We want this error";
apiNext
.searchContracts("AAPL")
.then(() => {
fail();
})
.catch((e: IBApiNextError) => {
expect(e.error.message).toEqual(testValue);
done();
});
api.emit(EventName.error, new Error(testValue), -1, 1);
});
test("Result Event", (done) => {
const apiNext = new IBApiNext();
const api = (apiNext as unknown as Record<string, unknown>).api as IBApi;
// emit a result event and verify RxJS result
const testValues: ContractDetails[] = [
{
contract: {
conId: Math.random(),
},
},
{
contract: {
conId: Math.random(),
},
},
];
apiNext
.searchContracts("AAPL")
.then((result) => {
expect(result).toEqual(testValues);
done();
})
.catch((e: IBApiNextError) => {
fail(e.error.message);
});
api.emit(EventName.symbolSamples, 1, testValues);
});
});
Example #7
Source File: driveModel.test.ts From google-drive-vscode with MIT License | 4 votes |
describe('Drive model operations', () => {
it('List all files and folders from existing parent', async () => {
const model = new DriveModel(new MockFileProvider());
const files = await model.listFiles('abcdefghi');
const names: string[] = ['VSCode', 'TCC.pdf', 'myFile.txt', 'Other folder', 'myTable.csv', 'myPicture.jpg', 'myOtherPicture.png', 'myThirdPicture.bmp'];
compareFileNames(files, names);
compareParent(files, undefined);
// Lists the subfolder 'VSCode'
const vscodeFiles = await model.listFiles('1C7udIKXCkxsvXO37gCBpfzrHihn9wocz');
const vscodeNames: string[] = ['Subfolder', 'A.pdf', 'B.txt'];
const vscodeFolderItself = model.getDriveFile('1C7udIKXCkxsvXO37gCBpfzrHihn9wocz');
compareFileNames(vscodeFiles, vscodeNames);
compareParent(vscodeFiles, vscodeFolderItself);
});
it('List only folders from existing parent', async () => {
const model = new DriveModel(new MockFileProvider());
const files = await model.listOnlyFolders('abcdefghi');
const names: string[] = ['VSCode', 'Other folder'];
compareFileNames(files, names);
});
it('List all files and folders from inexisting parent', async () => {
const model = new DriveModel(new MockFileProvider());
const files = await model.listFiles('xxxxxx');
expect(files.length).to.equal(0);
});
it('List only folders from inexisting parent', async () => {
const model = new DriveModel(new MockFileProvider());
const files = await model.listOnlyFolders('xxxxxx');
expect(files.length).to.equal(0);
});
it('Create folder', async () => {
const model = new DriveModel(new MockFileProvider());
await model.createFolder('abcdefghi', 'Nice folder');
const fileNames: string[] = ['VSCode', 'TCC.pdf', 'myFile.txt', 'Other folder', 'myTable.csv', 'myPicture.jpg', 'myOtherPicture.png', 'myThirdPicture.bmp', 'Nice folder'];
const files = await model.listFiles('abcdefghi');
compareFileNames(files, fileNames);
const folderNames: string[] = ['VSCode', 'Other folder', 'Nice folder'];
const folders = await model.listOnlyFolders('abcdefghi');
compareFileNames(folders, folderNames);
});
it('Upload file', async () => {
const model = new DriveModel(new MockFileProvider());
let baseName = await model.uploadFile('abcdefghi', path.join(__dirname, 'mockFile.txt'));
expect(baseName).to.equal('mockFile.txt');
baseName = await model.uploadFile('abcdefghi', path.join(__dirname, 'mockPdf.pdf'));
expect(baseName).to.equal('mockPdf.pdf');
baseName = await model.uploadFile('abcdefghi', path.join(__dirname, 'mockImage.jpg'));
expect(baseName).to.equal('mockImage.jpg');
baseName = await model.uploadFile('abcdefghi', path.join(__dirname, 'mockImage.png'));
expect(baseName).to.equal('mockImage.png');
baseName = await model.uploadFile('abcdefghi', path.join(__dirname, 'mockWithoutExt'));
expect(baseName).to.equal('mockWithoutExt');
});
it('Download file', async () => {
const model = new DriveModel(new MockFileProvider());
const destination = path.join(__dirname, 'dummyDownloadedFile' + getRandomInt(0, 100) + '.txt');
await model.downloadFile('1C7udIKXCkxsvjO37gCBpfzrHihn9wocz', destination);
fs.readFile(destination, (err, data) => {
if (err) fail(err);
expect(data.toString()).to.equal('done writing data');
fs.unlinkSync(destination);
});
});
it('Download file on invalid location', async () => {
const model = new DriveModel(new MockFileProvider());
const destination = '/???????///\\\\////invalid-destination/file.txt'
try {
await model.downloadFile('1C7udIKXCkxsvjO37gCBpfzrHihn9wocz', destination);
fail('Should have rejected');
} catch (error) {
expect(error).to.equal(`ENOENT: no such file or directory, open '/???????///\\\\////invalid-destination/file.txt'`);
}
});
it('Rename file', async () => {
const model = new DriveModel(new MockFileProvider());
await model.listFiles('abcdefghi');
await model.renameFile('1C7udIKXCkxsvjO37gCBpfzrHihn9wocz', 'novoNome.png');
const driveFile = model.getDriveFile('1C7udIKXCkxsvjO37gCBpfzrHihn9wocz');
expect(driveFile?.name).to.equal('novoNome.png');
});
});
Example #8
Source File: code-snippet.spec.ts From code-snippet with Apache License 2.0 | 4 votes |
describe("codeSnippet unit test", () => {
let sandbox: sinon.SinonSandbox;
let datauriMock: SinonMock;
let loggerMock: SinonMock;
let rpcMock: SinonMock;
let appEventsMock: SinonMock;
let swaTrackerWrapperMock: SinonMock;
let panelPromiseFuncsMock: SinonMock;
class TestEvents implements AppEvents {
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- must match interface
public async doApply(we: any): Promise<any> {
return;
}
public doSnippeDone(
/* eslint-disable @typescript-eslint/no-unused-vars -- must match interface */
success: boolean,
message: string,
targetPath?: string
/* eslint-enable @typescript-eslint/no-unused-vars -- must match interface */
): void {
return;
}
public doClose(): void {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- must match interface
public executeCommand(command: string, ...rest: any[]): Thenable<any> {
return;
}
}
class TestRpc implements IRpc {
public timeout: number;
public promiseCallbacks: Map<number, IPromiseCallbacks>;
public methods: Map<string, IMethod>;
public sendRequest(): void {
return;
}
public sendResponse(): void {
return;
}
public setResponseTimeout(): void {
return;
}
public registerMethod(): void {
return;
}
public unregisterMethod(): void {
return;
}
public listLocalMethods(): string[] {
return [];
}
public handleResponse(): void {
return;
}
public listRemoteMethods(): Promise<string[]> {
return Promise.resolve([]);
}
public invoke(): Promise<any> {
return Promise.resolve();
}
public handleRequest(): Promise<void> {
return Promise.resolve();
}
}
class TestOutputChannel implements AppLog {
public log(): void {
return;
}
public writeln(): void {
return;
}
public create(): void {
return;
}
public force(): void {
return;
}
public conflict(): void {
return;
}
public identical(): void {
return;
}
public skip(): void {
return;
}
public showOutput(): boolean {
return false;
}
}
const testLogger = {
debug: () => "",
error: () => "",
fatal: () => "",
warn: () => "",
info: () => "",
trace: () => "",
getChildLogger: () => ({} as IChildLogger),
};
const snippet: any = {
getMessages() {
return "getMessages";
},
async getQuestions() {
return "createCodeSnippetQuestions";
},
async getWorkspaceEdit() {
return "getWorkspaceEdit";
},
};
const rpc = new TestRpc();
const outputChannel = new TestOutputChannel();
const appEvents = new TestEvents();
const snippetTitle = "snippet title";
const uiOptions = { messages: { title: snippetTitle }, snippet: snippet };
const flowPromise: FlowPromise<void> = createFlowPromise<void>();
const codeSnippet: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
uiOptions
);
before(() => {
sandbox = sinon.createSandbox();
});
after(() => {
sandbox.restore();
});
beforeEach(() => {
datauriMock = sandbox.mock(datauri);
rpcMock = sandbox.mock(rpc);
loggerMock = sandbox.mock(testLogger);
appEventsMock = sandbox.mock(appEvents);
swaTrackerWrapperMock = sandbox.mock(SWA);
panelPromiseFuncsMock = sandbox.mock(flowPromise.state);
});
afterEach(() => {
datauriMock.verify();
rpcMock.verify();
loggerMock.verify();
appEventsMock.verify();
swaTrackerWrapperMock.verify();
panelPromiseFuncsMock.verify();
});
it("constructor", () => {
expect(
() =>
new CodeSnippet(
undefined,
undefined,
undefined,
undefined,
undefined,
undefined
)
).to.throw("rpc must be set");
});
describe("getState", () => {
it("valid uiOptions", async () => {
const state = await codeSnippet["getState"]();
expect(state.messages).to.be.not.empty;
});
it("invalid uiOptions", async () => {
codeSnippet["uiOptions"].test = codeSnippet["uiOptions"];
const state = await codeSnippet["getState"]();
expect(state.stateError).to.be.true;
});
});
describe("receiveIsWebviewReady", () => {
it("flow is successfull", async () => {
swaTrackerWrapperMock
.expects("updateSnippetStarted")
.withArgs(snippetTitle);
rpcMock
.expects("invoke")
.withArgs("showPrompt")
.resolves([
{ actionName: "actionName" },
{ actionTemplate: "OData action" },
{ actionType: "Create entity" },
]);
appEventsMock.expects("doApply");
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs(snippetTitle, true);
await codeSnippet["receiveIsWebviewReady"]();
});
it("no prompt ---> an error is thrown", async () => {
swaTrackerWrapperMock
.expects("updateSnippetStarted")
.withArgs(snippetTitle);
panelPromiseFuncsMock.expects("reject");
await codeSnippet["receiveIsWebviewReady"]();
});
it("prompt throws exception ---> an error is thrown", async () => {
swaTrackerWrapperMock
.expects("updateSnippetStarted")
.withArgs(snippetTitle);
rpcMock
.expects("invoke")
.withArgs("showPrompt")
.rejects(new Error("receiveIsWebviewReady error"));
appEventsMock.expects("doApply").never();
panelPromiseFuncsMock.expects("reject");
await codeSnippet["receiveIsWebviewReady"]();
});
});
describe("showPrompt", () => {
it("prompt without questions", async () => {
const answers = await codeSnippet.showPrompt([]);
expect(answers).to.be.empty;
});
});
describe("funcReplacer", () => {
it("with function", () => {
const res = CodeSnippet["funcReplacer"]("key", () => {
return;
});
expect(res).to.be.equal("__Function");
});
it("without function", () => {
const res = CodeSnippet["funcReplacer"]("key", "value");
expect(res).to.be.equal("value");
});
});
it("toggleOutput", () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
const res = codeSnippetInstance["toggleOutput"]();
expect(res).to.be.false;
});
it("getErrorInfo with error message", () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
const errorInfo = "Error Info";
const res = codeSnippetInstance["getErrorInfo"](errorInfo);
expect(res).to.be.equal(errorInfo);
});
it("getErrorInfo without error message", () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
const res = codeSnippetInstance["getErrorInfo"]();
expect(res).to.be.equal("");
});
describe("answersUtils", () => {
it("setDefaults", () => {
const questions = [
{ name: "q1", default: "a" },
{
name: "q2",
default: () => {
return "b";
},
},
{ name: "q3" },
];
for (const question of questions) {
switch (question.name) {
case "a":
expect((question as any)["answer"]).to.equal("x");
break;
case "b":
expect((question as any)["answer"]).to.equal("y");
break;
case "c":
expect((question as any)["answer"]).to.equal("z");
break;
}
}
});
});
describe("showPrompt", () => {
it("returns answers", async () => {
const firstName = "john";
rpc.invoke = async () => {
return {
firstName,
lastName: "doe",
};
};
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
const questions = [{ name: "q1" }];
const response = await codeSnippetInstance.showPrompt(questions);
expect(response.firstName).to.equal(firstName);
});
});
describe("onSuccess - onFailure", () => {
let doSnippeDoneSpy: any;
beforeEach(() => {
doSnippeDoneSpy = sandbox.spy(appEvents, "doSnippeDone");
});
afterEach(() => {
doSnippeDoneSpy.restore();
});
it("onSuccess", () => {
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs("testSnippetName", true);
codeSnippet["onSuccess"](true, "testSnippetName");
expect(
doSnippeDoneSpy.calledWith(
true,
"'testSnippetName' snippet has been created."
)
).to.be.true;
});
it("onFailure", async () => {
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs("testSnippetName", false);
await codeSnippet["onFailure"](true, "testSnippetName", "testError");
expect(
doSnippeDoneSpy.calledWith(
false,
"testSnippetName snippet failed.\ntestError"
)
).to.be.true;
});
});
describe("executeCommand", () => {
it("called with command id & args", async () => {
const commandId = "vscode.open";
const commandArgs = [{ fsPath: "https://en.wikipedia.org" }];
appEventsMock
.expects("executeCommand")
.withExactArgs(commandId, commandArgs);
await codeSnippet["executeCommand"](commandId, commandArgs);
});
});
describe("Custom Question Event Handlers", () => {
it("addCustomQuestionEventHandlers()", async () => {
const testEventFunction = () => {
return true;
};
const questions = [
{
name: "q1",
guiType: "questionType",
},
];
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance["addCustomQuestionEventHandlers"](questions);
expect(questions[0]).to.not.have.property("testEvent");
codeSnippetInstance.registerCustomQuestionEventHandler(
"questionType",
"testEvent",
testEventFunction
);
codeSnippetInstance["addCustomQuestionEventHandlers"](questions);
expect(questions[0]).to.have.property("testEvent");
expect((questions[0] as any)["testEvent"]).to.equal(testEventFunction);
});
});
describe("evaluateMethod()", () => {
it("custom question events", async () => {
const testEventFunction = () => {
return true;
};
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance.registerCustomQuestionEventHandler(
"questionType",
"testEvent",
testEventFunction
);
codeSnippetInstance["currentQuestions"] = [
{ name: "question1", guiType: "questionType" },
];
const response = await codeSnippetInstance["evaluateMethod"](
null,
"question1",
"testEvent"
);
expect(response).to.be.true;
});
it("question method is called", async () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance["currentQuestions"] = [
{
name: "question1",
method1: () => {
return true;
},
},
];
const response = await codeSnippetInstance["evaluateMethod"](
null,
"question1",
"method1"
);
expect(response).to.be.true;
});
it("no relevant question", async () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance["currentQuestions"] = [
{
name: "question1",
method1: () => {
return true;
},
},
];
const response = await codeSnippetInstance["evaluateMethod"](
null,
"question2",
"method2"
);
expect(response).to.be.undefined;
});
it("no questions", async () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
const response = await codeSnippetInstance["evaluateMethod"](
null,
"question1",
"method1"
);
expect(response).to.be.undefined;
});
it("method throws exception", async () => {
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance["gen"] = Object.create({});
codeSnippetInstance["gen"].options = {};
codeSnippetInstance["currentQuestions"] = [
{
name: "question1",
method1: () => {
throw new Error("Error");
},
},
];
try {
await codeSnippetInstance["evaluateMethod"](
null,
"question1",
"method1"
);
} catch (e) {
expect(e.stack).to.contain("method1");
}
});
});
describe("applyCode", () => {
let codeSnippetInstanceMock: any;
let codeSnippetInstance: CodeSnippet;
beforeEach(() => {
codeSnippetInstance = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{ messages: { title: snippetTitle } }
);
codeSnippetInstanceMock = sandbox.mock(codeSnippetInstance);
});
afterEach(() => {
codeSnippetInstanceMock.verify();
});
it("createCodeSnippetWorkspaceEdit succeeds ---> onSuccess is called with showDoneMessage=true", async () => {
panelPromiseFuncsMock.expects("resolve");
codeSnippetInstanceMock
.expects("createCodeSnippetWorkspaceEdit")
.resolves({});
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs(snippetTitle, true);
await codeSnippetInstance["applyCode"]({});
});
it("createCodeSnippetWorkspaceEdit fails (we is undefined) ---> onSuccess is called with showDoneMessage=false", async () => {
panelPromiseFuncsMock.expects("resolve");
codeSnippetInstanceMock
.expects("createCodeSnippetWorkspaceEdit")
.resolves(undefined);
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs(snippetTitle, true);
appEventsMock.expects("doApply").never();
appEventsMock.expects("doClose");
await codeSnippetInstance["applyCode"]({});
});
it("createCodeSnippetWorkspaceEdit fails ---> onFailure is called", async () => {
panelPromiseFuncsMock.expects("reject");
const error = new Error("error");
codeSnippetInstanceMock
.expects("createCodeSnippetWorkspaceEdit")
.rejects(error);
swaTrackerWrapperMock
.expects("updateSnippetEnded")
.withArgs(snippetTitle, false);
await codeSnippetInstance["applyCode"]({});
});
});
describe("createCodeSnippetWorkspaceEdit", () => {
it("snippet has getWorkspaceEdit ---> call getWorkspaceEdit", async () => {
const myCodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{ snippet: snippet }
);
const we = await myCodeSnippet["createCodeSnippetWorkspaceEdit"]({});
expect(we).to.be.equal("getWorkspaceEdit");
});
it("snippet is undefined", async () => {
const myCodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
loggerMock.expects("debug");
const we = await myCodeSnippet["createCodeSnippetWorkspaceEdit"]({});
expect(we).to.be.equal(undefined);
});
});
describe("createCodeSnippetQuestions", () => {
it("snippet has getQuestions ---> call getQuestions", async () => {
const myCodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{ snippet: snippet }
);
const we = await myCodeSnippet["createCodeSnippetQuestions"]();
expect(we).to.be.equal("createCodeSnippetQuestions");
});
it("no snippet provided ---> call getQuestions", async () => {
const myCodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{ snippet: null }
);
const we = await myCodeSnippet["createCodeSnippetQuestions"]();
expect(we).to.be.empty;
});
});
describe("registerCustomQuestionEventHandler", () => {
it("all the events handlers for the same question type are in the same entry", () => {
const testEventFunction = () => {
return true;
};
const codeSnippetInstance: CodeSnippet = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{}
);
codeSnippetInstance.registerCustomQuestionEventHandler(
"questionType",
"testEvent1",
testEventFunction
);
expect(
codeSnippetInstance["customQuestionEventHandlers"].size
).to.be.equal(1);
codeSnippetInstance.registerCustomQuestionEventHandler(
"questionType",
"testEvent2",
testEventFunction
);
expect(
codeSnippetInstance["customQuestionEventHandlers"].size
).to.be.equal(1);
});
});
describe("executeCodeSnippet", () => {
let codeSnippetInstanceMock: SinonMock;
let codeSnippetInstance: CodeSnippet;
beforeEach(() => {
codeSnippetInstance = new CodeSnippet(
rpc,
appEvents,
outputChannel,
testLogger,
flowPromise.state,
{
messages: {
title: snippetTitle.length,
noResponse: "No response received.",
},
snippet: snippet,
contributorInfo: { snippetArgs: {} },
}
);
codeSnippetInstanceMock = sandbox.mock(codeSnippetInstance);
});
afterEach(() => {
codeSnippetInstanceMock.verify();
});
it("interactive mode - answers param exists", async () => {
codeSnippetInstanceMock
.expects("createCodeSnippetWorkspaceEdit")
.resolves({ name: "test" });
await codeSnippetInstance["executeCodeSnippet"]({ name: "test" });
});
it("interactive mode - answers param is empty", async () => {
codeSnippetInstanceMock.expects("createCodeSnippetWorkspaceEdit").never();
swaTrackerWrapperMock.expects("updateSnippetEnded").never();
try {
await codeSnippetInstance["executeCodeSnippet"]({});
fail("test should fail");
} catch (error) {
expect(error).to.be.equal("No response received.");
}
});
it("nonInteractive mode - answers param doesn't exist", async () => {
snippet["getQuestions"] = () => {
return [
{ name: "q1", default: "a" },
{ name: "q2", default: () => "b" },
];
};
codeSnippetInstanceMock
.expects("createCodeSnippetWorkspaceEdit")
.resolves({ q1: "a", q2: "b" });
await codeSnippetInstance["executeCodeSnippet"]();
});
});
});