확장 프로그램 테스트
Visual Studio Code는 확장 프로그램에 대한 테스트 실행 및 디버깅을 지원합니다. 이러한 테스트는 확장 개발 호스트라는 VS Code의 특수 인스턴스 내에서 실행되며 VS Code API에 완전히 액세스할 수 있습니다. VS Code 인스턴스 없이 실행할 수 있는 단위 테스트를 넘어서는 테스트이므로 이러한 테스트를 통합 테스트라고 합니다. 이 설명서는 VS Code 통합 테스트에 중점을 둡니다.
개요
확장 프로그램의 스캐폴딩에 Yeoman Generator를 사용하는 경우 통합 테스트가 이미 생성되어 있습니다.
생성된 확장 프로그램에서 npm run test 또는 yarn test를 사용하여 통합 테스트를 실행할 수 있습니다. 이 테스트는
- VS Code 최신 버전을 다운로드하고 압축을 풉니다.
- 확장 테스트 실행기 스크립트에서 지정한 Mocha 테스트를 실행합니다.
빠른 설정: 테스트 CLI
VS Code 팀은 확장 테스트 실행을 위한 명령줄 도구를 게시합니다. 확장 샘플 리포지토리에서 예를 찾을 수 있습니다.
테스트 CLI는 빠른 설정을 제공하며 확장 테스트 실행기를 사용하여 VS Code UI 테스트를 쉽게 실행하고 디버깅할 수 있습니다. CLI는 내부적으로 Mocha만을 사용합니다.
시작하려면 먼저 @vscode/test-cli 모듈과 VS Code 데스크톱에서 테스트를 실행할 수 있도록 하는 @vscode/test-electron 모듈을 설치해야 합니다.
npm install --save-dev @vscode/test-cli @vscode/test-electron
모듈을 설치한 후에는 vscode-test 명령줄을 사용할 수 있으며, 이를 package.json의 scripts 섹션에 추가할 수 있습니다.
{
"name": "my-cool-extension",
"scripts": {
+ "test": "vscode-test"
vscode-test는 현재 작업 디렉터리에 상대적인 .vscode-test.js/mjs/cjs 파일을 찾습니다. 이 파일은 테스트 실행기에 대한 구성을 제공하며 전체 정의는 여기에서 찾을 수 있습니다.
일반적인 옵션은 다음과 같습니다.
- (필수)
files- 실행할 테스트가 포함된 패턴, 패턴 목록 또는 절대 경로입니다. version- 테스트 실행에 사용할 VS Code 버전입니다(기본값:stable).workspaceFolder- 테스트 중에 열 작업 공간의 경로입니다.extensionDevelopmentPath- 확장 폴더의 경로입니다(기본값: 구성 파일의 디렉터리).mocha- Mocha에 전달할 추가 옵션을 포함하는 객체입니다.
구성의 단순한 예는 다음과 같습니다.
// .vscode-test.js
const { defineConfig } = require('@vscode/test-cli');
module.exports = defineConfig({ files: 'out/test/**/*.test.js' });
더 발전된 구성
// .vscode-test.js
const { defineConfig } = require('@vscode/test-cli');
module.exports = defineConfig([
{
label: 'unitTests',
files: 'out/test/**/*.test.js',
version: 'insiders',
workspaceFolder: './sampleWorkspace',
mocha: {
ui: 'tdd',
timeout: 20000
}
}
// you can specify additional test configurations, too
]);
배열을 전달하여 여러 구성을 정의하면 vscode-test를 실행할 때 순차적으로 실행됩니다. label로 필터링하고 --label 플래그를 사용하여 개별적으로 실행할 수 있습니다. 예를 들어 vscode-test --label unitTests입니다. 전체 명령줄 옵션은 vscode-test --help에서 확인하십시오.
테스트 스크립트
CLI가 설정되면 테스트를 작성하고 실행할 수 있습니다. 테스트 스크립트는 VS Code API에 액세스할 수 있으며 Mocha에서 실행됩니다. 다음은 예시입니다(src/test/suite/extension.test.ts).
import * as assert from 'assert';
// 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 * as myExtension from '../extension';
suite('Extension Test Suite', () => {
suiteTeardown(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
npm test 명령으로 이 테스트를 실행하거나 확장 테스트 실행기를 설치한 후 VS Code의 Test: Run All Tests 명령을 사용하여 실행할 수 있습니다. Test: Debug All Tests 명령을 사용하여 테스트를 디버깅할 수도 있습니다.
고급 설정: 자체 실행기
helloworld-test-sample에서 이 가이드의 구성을 찾을 수 있습니다. 이 문서의 나머지 부분에서는 샘플 컨텍스트에서 이러한 파일을 설명합니다.
- 테스트 스크립트(
src/test/runTest.ts) - 테스트 실행기 스크립트(
src/test/suite/index.ts)
VS Code는 확장 테스트 실행을 위해 --extensionDevelopmentPath 및 --extensionTestsPath라는 두 가지 CLI 매개변수를 제공합니다.
예를 들어,
# - Launches VS Code Extension Host
# - Loads the extension at <EXTENSION-ROOT-PATH>
# - Executes the test runner script at <TEST-RUNNER-SCRIPT-PATH>
code \
--extensionDevelopmentPath=<EXTENSION-ROOT-PATH> \
--extensionTestsPath=<TEST-RUNNER-SCRIPT-PATH>
테스트 스크립트(src/test/runTest.ts)는 @vscode/test-electron API를 사용하여 VS Code를 다운로드, 압축 해제 및 확장 테스트 매개변수와 함께 실행하는 프로세스를 단순화합니다.
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 runner 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(err);
console.error('Failed to run tests');
process.exit(1);
}
}
main();
@vscode/test-electron API는 또한 다음을 허용합니다.
- 특정 작업 공간으로 VS Code 실행.
- 최신 안정 버전이 아닌 다른 VS Code 버전 다운로드.
- 추가 CLI 매개변수로 VS Code 실행.
microsoft/vscode-test에서 더 많은 API 사용 예제를 찾을 수 있습니다.
테스트 실행기 스크립트
확장 통합 테스트를 실행할 때 --extensionTestsPath는 테스트 제품군을 프로그래밍 방식으로 실행하는 테스트 실행기 스크립트(src/test/suite/index.ts)를 가리킵니다. 다음은 테스트 제품군을 실행하기 위해 Mocha를 사용하는 helloworld-test-sample의 테스트 실행기 스크립트입니다. 이를 시작점으로 사용하여 Mocha API로 설정을 사용자 지정할 수 있습니다. 프로그래밍 방식으로 실행할 수 있는 다른 테스트 프레임워크로 Mocha를 대체할 수도 있습니다.
import * as path from 'path';
import * as Mocha from 'mocha';
import { glob } from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
color: true
});
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot })
.then(files => {
// 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) {
e(err);
}
})
.catch(err => {
return e(err);
});
});
}
테스트 실행기 스크립트와 *.test.js 파일 모두 VS Code API에 액세스할 수 있습니다.
다음은 샘플 테스트입니다(src/test/suite/extension.test.ts).
import * as assert from 'assert';
import { after } from 'mocha';
// 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 * as myExtension from '../extension';
suite('Extension Test Suite', () => {
after(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
테스트 디버깅
테스트 디버깅은 확장 디버깅과 유사합니다.
다음은 샘플 launch.json 디버거 구성입니다.
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": ["${workspaceFolder}/out/test/**/*.js"]
}
]
}
팁
확장 개발을 위해 Insiders 버전 사용
VS Code의 제한으로 인해 VS Code 안정 버전을 사용하고 CLI에서 통합 테스트를 실행하려고 하면 오류가 발생합니다.
Running extension tests from the command line is currently only supported if no other instance of Code is running.
일반적으로 CLI에서 확장 테스트를 실행하는 경우 테스트가 실행되는 버전이 이미 실행 중이지 않아야 합니다. 해결 방법으로 VS Code 안정 버전에서 테스트를 실행하고 개발을 위해 VS Code Insiders를 사용할 수 있습니다. VS Code Insiders에서 CLI에서 테스트를 실행하지 않고 VS Code 안정 버전에서 실행하는 한 이 설정은 제대로 작동합니다.
또 다른 방법은 VS Code 자체 내에서 디버그 시작 구성에서 확장 테스트를 실행하는 것입니다. 이 방법은 테스트를 디버깅할 수 있다는 추가적인 이점이 있습니다.
디버깅 중 다른 확장 프로그램 비활성화
VS Code에서 확장 테스트를 디버깅할 때 VS Code는 전역적으로 설치된 VS Code 인스턴스를 사용하며 설치된 모든 확장을 로드합니다. launch.json 또는 @vscode/test-electron의 runTests API의 launchArgs 옵션에 --disable-extensions 구성을 추가할 수 있습니다.
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": ["${workspaceFolder}/out/test/**/*.js"]
}
]
}
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
/**
* A list of launch arguments passed to VS Code executable, in addition to `--extensionDevelopmentPath`
* and `--extensionTestsPath` which are provided by `extensionDevelopmentPath` and `extensionTestsPath`
* options.
*
* If the first argument is a path to a file/folder/workspace, the launched VS Code instance
* will open it.
*
* See `code --help` for possible arguments.
*/
launchArgs: ['--disable-extensions']
});
@vscode/test-electron을 사용한 사용자 지정 설정
때로는 테스트를 시작하기 전에 다른 확장을 설치하기 위해 code --install-extension과 같은 사용자 지정 설정을 실행해야 할 수도 있습니다. @vscode/test-electron은 해당 경우를 수용하기 위해 더 세분화된 API를 제공합니다.
import * as cp from 'child_process';
import * as path from 'path';
import {
downloadAndUnzipVSCode,
resolveCliArgsFromVSCodeExecutablePath,
runTests
} from '@vscode/test-electron';
async function main() {
try {
const extensionDevelopmentPath = path.resolve(__dirname, '../../../');
const extensionTestsPath = path.resolve(__dirname, './suite/index');
const vscodeExecutablePath = await downloadAndUnzipVSCode('1.40.1');
const [cliPath, ...args] = resolveCliArgsFromVSCodeExecutablePath(vscodeExecutablePath);
// Use cp.spawn / cp.exec for custom setup
cp.spawnSync(
cliPath,
[...args, '--install-extension', '<EXTENSION-ID-OR-PATH-TO-VSIX>'],
{
encoding: 'utf-8',
stdio: 'inherit'
}
);
// Run the extension test
await runTests({
// Use the specified `code` executable
vscodeExecutablePath,
extensionDevelopmentPath,
extensionTestsPath
});
} catch (err) {
console.error('Failed to run tests');
process.exit(1);
}
}
main();
다음 단계
- 지속적 통합 - Azure DevOps와 같은 지속적 통합 서비스에서 확장 테스트를 실행합니다.