Skip to content

Commit

Permalink
Added first unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
dpar39 authored and Darien Pardinas Diaz committed May 13, 2024
1 parent 6afd490 commit e858bcf
Show file tree
Hide file tree
Showing 12 changed files with 151 additions and 39 deletions.
13 changes: 6 additions & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ jobs:
registry-url: https://registry.npmjs.org/

- name: Install the dependencies
run: npm i

# - name: Clone the toolkit
# run: |
# git clone https://github.com/microsoftgraph/microsoft-graph-toolkit
# npm run snippets
run: npm install

- name: Build and run automation tests
run: xvfb-run -a npm run test

- name: Publish
- name: Publish to VSCode Marketplace
if: ${{ github.ref == 'refs/heads/main' }}
run: npx @vscode/vsce publish -p ${{ secrets.VSCE_PAT }}
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
]
},
{
"name": "Extension Tests",
"name": "Test Extension",
"type": "extensionHost",
"request": "launch",
"args": [
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.
File renamed without changes.
9 changes: 5 additions & 4 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import * as vscode from "vscode";
import * as tcpPorts from "tcp-port-used";
import { Logger } from "./services/logger";
import http, { IncomingMessage, ServerResponse } from "http";
import { IncomingMessage, ServerResponse } from "http";
import * as http from "http";
import { AddressInfo } from "net";
import { ControlRequest } from "./models/controlRequest";
import { processRemoteControlRequest } from "./services/requestProcessor";

let server: http.Server;
let statusbar: vscode.StatusBarItem;

const EXTENSION_ID: string = "dpar39.vscode-rest-control";
export const EXTENSION_ID: string = "dpar39.vscode-rest-control";
const SETTINGS_NAME: string = "restRemoteControl";

const startHttpServer = async (
Expand Down Expand Up @@ -47,6 +48,7 @@ const startHttpServer = async (
const reqData = JSON.parse(body);
processRemoteControlRequest(reqData as ControlRequest)
.then((data) => {
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(data || {}));
res.end();
})
Expand All @@ -72,7 +74,6 @@ const startHttpServer = async (
context.environmentVariableCollection.replace("REMOTE_CONTROL_PORT", `${verifiedPort}`);
statusbar.text = `$(plug) RC Port: ${verifiedPort}`;
statusbar.tooltip = listeningMessage;

});
};

Expand All @@ -92,7 +93,7 @@ function setupRestControl(context: vscode.ExtensionContext) {
Logger.info("VSCode REST Control is now active!");
} else {
statusbar.tooltip = `REST remote control has been disabled via setting "${SETTINGS_NAME}.enabled": false`;
statusbar.text = '$(debug-disconnect) RC Disabled';
statusbar.text = "$(debug-disconnect) RC Disabled";
server?.close();
Logger.info("VSCode REST Control has been disabled via settings!");
}
Expand Down
16 changes: 8 additions & 8 deletions src/services/requestProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import { ControlRequest } from "../models/controlRequest";
function createObject(arg: any): any {
if (typeof arg === "object" && arg.hasOwnProperty("__type__")) {
const type = arg.__type__;
if (type == "Uri") {
if (type === "Uri") {
return vscode.Uri.parse(arg.args[0]);
} else if (type == "Position") {
} else if (type === "Position") {
return new vscode.Position(arg.args[0], arg.args[1]);
} else if (type == "Range") {
} else if (type === "Range") {
return new vscode.Range(arg.args[0], arg.args[1], arg.args[2], arg.args[3]);
} else if (type == "Location") {
} else if (type === "Location") {
return new vscode.Location(createObject(arg.args[0]), createObject(arg.args[1]));
}
}
Expand Down Expand Up @@ -50,7 +50,7 @@ export async function processRemoteControlRequest(requestObject: ControlRequest)
throw new Error("No active terminal available");
}

if (command == "custom.startDebugSession") {
if (command === "custom.startDebugSession") {
const folder = args[0];
const debugConfig = args[1];
const success = await vscode.debug.startDebugging(folder, debugConfig);
Expand Down Expand Up @@ -85,18 +85,18 @@ export async function processRemoteControlRequest(requestObject: ControlRequest)
return await quickPick(args[0]);
}

if (command == "custom.goToFileLineCharacter") {
if (command === "custom.goToFileLineCharacter") {
const filePath = args[0];
let uri = null;
if (!path.isAbsolute(filePath)) {
let candidates = await vscode.workspace.findFiles(args[0]);
if (candidates.length == 1) {
if (candidates.length === 1) {
uri = candidates[0];
}
} else {
uri = vscode.Uri.file(filePath);
}
if (uri == null) {
if (uri === null) {
throw new Error(`Unable to locate file: ${filePath}`);
}
const position = new vscode.Position(args[1] || 0, args[2] || 0);
Expand Down
23 changes: 23 additions & 0 deletions src/test/runTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as path from "path";

import { runTests } from "@vscode/test-electron";

async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, "../../");

// The path to the extension test script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, "./suite/index");

// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath});
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}

main();
27 changes: 27 additions & 0 deletions src/test/suite/extension.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as assert from "assert";
import * as path from "path";
import { EXTENSION_ID } from "../../extension";

// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from "vscode";
import { makeRequest } from "./sendPostRequest";
// import * as myExtension from '../extension';

suite("Extension Test Suite", () => {
suiteSetup(async () => {
const sampleWorkspace = path.resolve(__dirname, "../../../sampleWorkspace");
let uri = vscode.Uri.file(sampleWorkspace);
await vscode.commands.executeCommand("vscode.openFolder", uri);
});

suiteTeardown(() => {});

test("check can list extensions", async () => {
const extensionIds: string[] = (await makeRequest(
"custom.listInstalledExtensions",
[]
)) as string[];
assert(extensionIds.includes(EXTENSION_ID));
});
});
37 changes: 37 additions & 0 deletions src/test/suite/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as path from "path";
import * as Mocha from "mocha";
import * as glob from "glob";

export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: "tdd",
});

const testsRoot = path.resolve(__dirname, "..");

return new Promise((c, e) => {
glob("**/**.test.js", { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}

// Add files to the test suite
files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)));

try {
// Run the mocha test
mocha.run((failures) => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
});
}
26 changes: 26 additions & 0 deletions src/test/suite/sendPostRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as http from "http";

export async function makeRequest(command: string, args: any[], port: number = 37100) {
return new Promise((resolve, reject) => {
const req = http.request(
{
method: "POST",
hostname: "localhost",
port: port,
path: "/",
},
(res) => {
const chunks: any[] = [];
res.on("data", (data) => chunks.push(data));
res.on("end", () => {
const resBody = Buffer.concat(chunks);
resolve(JSON.parse(resBody.toString()));
});
}
);
req.on("error", reject);
const body = JSON.stringify({ command: command, args: args });
req.write(body);
req.end();
});
}
33 changes: 16 additions & 17 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": [
"es6"
],
"sourceMap": true,
"rootDir": "src",
"strict": true,
"esModuleInterop": true
},
"exclude": [
"node_modules",
".vscode-test"
]
}
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"lib": [
"es2020"
],
"outDir": "out",
"sourceMap": true,
"rootDir": "src",
"strict": true,
},
"exclude": [
"node_modules",
".vscode-test"
]
}

0 comments on commit e858bcf

Please sign in to comment.