Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
test(vscode-plugin): improve tests + some refactoring
Matthew Espinocf68af249e6c
diff --git a/packages/vscode-plugin/src/extension.ts b/packages/vscode-plugin/src/extension.tsindex d3d0afec3..bd9beed4b 100644--- a/packages/vscode-plugin/src/extension.ts+++ b/packages/vscode-plugin/src/extension.ts@@ -4,7 +4,7 @@ import type { Executable, LanguageClientOptions } from 'vscode-languageclient/noimport { Uri, commands, window, workspace } from 'vscode';import { LanguageClient, ResponseError, TransportKind } from 'vscode-languageclient/node';-// There's no publicly available extension manifest type except for the internal one from VSCode's+// There's no publicly available extension manifest type except for the internal one from VS Code's// codebase. So, we declare our own with only the fields we need and have. See:// https://stackoverflow.com/a/78536803type ExtensionManifest = {@@ -14,7 +14,42 @@ type ExtensionManifest = {let client: LanguageClient | undefined;const serverOptions: Executable = { command: '', transport: TransportKind.stdio };-const clientOptions: LanguageClientOptions = {};+const clientOptions: LanguageClientOptions = {+ middleware: {+ workspace: {+ async configuration(params, token, next) {+ const response = await next(params, token);++ if (response instanceof ResponseError) {+ return response;+ }++ return [{ 'harper-ls': response[0].harper }];+ },+ },+ executeCommand(command, args, next) {+ if (+ command === 'HarperAddToFileDict' &&+ args.find((a) => typeof a === 'string' && a.startsWith('untitled:'))+ ) {+ window+ .showInformationMessage(+ 'Save the file to add words to its file dictionary.',+ 'Save File',+ 'Dismiss',+ )+ .then((selected) => {+ if (selected === 'Save File') {+ commands.executeCommand('workbench.action.files.save');+ }+ });+ return;+ }++ next(command, args);+ },+ },+};export async function activate(context: ExtensionContext): Promise<void> {serverOptions.command = getExecutablePath(context);@@ -96,41 +131,6 @@ async function startLanguageServer(): Promise<void> {try {client = new LanguageClient('harper', 'Harper', serverOptions, clientOptions);-- client.middleware.workspace = {- async configuration(params, token, next) {- const response = await next(params, token);-- if (response instanceof ResponseError) {- return response;- }-- return [{ 'harper-ls': response[0].harper }];- },- };-- client.middleware.executeCommand = (command, args, next) => {- if (- command === 'HarperAddToFileDict' &&- args.find((a) => typeof a === 'string' && a.startsWith('untitled:'))- ) {- window- .showInformationMessage(- 'Save the file to add words to its file dictionary.',- 'Save File',- 'Dismiss',- )- .then((selected) => {- if (selected === 'Save File') {- commands.executeCommand('workbench.action.files.save');- }- });- return;- }-- next(command, args);- };-await client.start();} catch (error) {showError('Failed to start harper-ls', error);diff --git a/packages/vscode-plugin/src/tests/fixtures/integration.md b/packages/vscode-plugin/src/tests/fixtures/integration.mdindex caf13dac0..187c8293f 100644--- a/packages/vscode-plugin/src/tests/fixtures/integration.md+++ b/packages/vscode-plugin/src/tests/fixtures/integration.md@@ -1,3 +1,5 @@# IntegrationThis sentence has grammar errorz, like this this one.++On the other hand, you'll realise that this sentence doesn't have an error if you're using British English.diff --git a/packages/vscode-plugin/src/tests/fixtures/integrationBritish.md b/packages/vscode-plugin/src/tests/fixtures/integrationBritish.mddeleted file mode 100644index e9f927e2a..000000000--- a/packages/vscode-plugin/src/tests/fixtures/integrationBritish.md+++ /dev/null@@ -1 +0,0 @@-This document uses British words, unlike color.diff --git a/packages/vscode-plugin/src/tests/suite/helper.ts b/packages/vscode-plugin/src/tests/suite/helper.tsindex 85a24ce88..d1209482a 100644--- a/packages/vscode-plugin/src/tests/suite/helper.ts+++ b/packages/vscode-plugin/src/tests/suite/helper.ts@@ -69,6 +69,19 @@ export function createRange(return new Range(new Position(startRow, startColumn), new Position(endRow, endColumn));}-export function sleep(duration: number): Promise<void> {+// The numbers used in these functions are what works when running tests in GitHub CI.+export async function waitForHarperToActivate() {+ await sleep(500);+}+export async function waitForUpdatesFromOpenedFile() {+ await sleep(75);+}+export async function waitForUpdatesFromConfigChange() {+ await sleep(300);+}+export async function waitForUpdatesFromDeletedFile() {+ await sleep(450);+}+function sleep(duration: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, duration));}diff --git a/packages/vscode-plugin/src/tests/suite/integration.test.ts b/packages/vscode-plugin/src/tests/suite/integration.test.tsindex 0b10648dc..9c718a4d6 100644--- a/packages/vscode-plugin/src/tests/suite/integration.test.ts+++ b/packages/vscode-plugin/src/tests/suite/integration.test.ts@@ -1,6 +1,6 @@-import type { Extension } from 'vscode';+import type { Extension, Uri } from 'vscode';-import { ConfigurationTarget, type Uri, commands, workspace } from 'vscode';+import { ConfigurationTarget, commands, workspace } from 'vscode';import {activateHarper,@@ -10,7 +10,10 @@ import {getActualDiagnostics,openFile,openUntitled,- sleep,+ waitForHarperToActivate,+ waitForUpdatesFromConfigChange,+ waitForUpdatesFromDeletedFile,+ waitForUpdatesFromOpenedFile,} from './helper';describe('Integration >', () => {@@ -19,10 +22,8 @@ describe('Integration >', () => {beforeAll(async () => {harper = await activateHarper();- // Open test file so diagnostics can occurmarkdownUri = await openFile('integration.md');- // Wait for `harper-ls` to start- await sleep(500);+ await waitForHarperToActivate();});it('runs', () => {@@ -41,15 +42,17 @@ describe('Integration >', () => {message: 'Did you mean to spell “errorz” this way?',range: createRange(2, 26, 2, 32),},+ {+ message: 'Did you mean to spell “realise” this way?',+ range: createRange(4, 26, 4, 33),+ },),);});it('gives correct diagnostics for untitled', async () => {const untitledUri = await openUntitled('Errorz');-- // Wait for `harper-ls` to send diagnostics- await sleep(500);+ await waitForUpdatesFromOpenedFile();compareActualVsExpectedDiagnostics(getActualDiagnostics(untitledUri),@@ -63,29 +66,56 @@ describe('Integration >', () => {it('updates diagnostics on configuration change', async () => {const config = workspace.getConfiguration('harper.linters');await config.update('RepeatedWords', false, ConfigurationTarget.Workspace);- // Wait for `harper-ls` to update diagnostics- await sleep(300);+ await waitForUpdatesFromConfigChange();compareActualVsExpectedDiagnostics(getActualDiagnostics(markdownUri),- createExpectedDiagnostics({- message: 'Did you mean to spell “errorz” this way?',- range: createRange(2, 26, 2, 32),- }),+ createExpectedDiagnostics(+ {+ message: 'Did you mean to spell “errorz” this way?',+ range: createRange(2, 26, 2, 32),+ },+ {+ message: 'Did you mean to spell “realise” this way?',+ range: createRange(4, 26, 4, 33),+ },+ ),);// Set config back to default valueawait config.update('RepeatedWords', true, ConfigurationTarget.Workspace);});+ it('accepts British spellings when dialect is set to British', async () => {+ const config = workspace.getConfiguration('harper');+ await config.update('dialect', 'British', ConfigurationTarget.Workspace);+ await waitForUpdatesFromConfigChange();++ compareActualVsExpectedDiagnostics(+ getActualDiagnostics(markdownUri),+ createExpectedDiagnostics(+ {+ message: 'Did you mean to repeat this word?',+ range: createRange(2, 39, 2, 48),+ },+ {+ message: 'Did you mean to spell “errorz” this way?',+ range: createRange(2, 26, 2, 32),+ },+ ),+ );++ // Set config back to default value+ await config.update('dialect', 'American', ConfigurationTarget.Workspace);+ });+it('updates diagnostics when files are deleted', async () => {const markdownContent = await workspace.fs.readFile(markdownUri);- // Delete file through VSCode+ // Delete file through VS Codeawait commands.executeCommand('workbench.files.action.showActiveFileInExplorer');await commands.executeCommand('deleteFile');- // Wait for `harper-ls` to update diagnostics- await sleep(450);+ await waitForUpdatesFromDeletedFile();compareActualVsExpectedDiagnostics(getActualDiagnostics(markdownUri),@@ -95,13 +125,11 @@ describe('Integration >', () => {// Restore and reopen deleted fileawait workspace.fs.writeFile(markdownUri, markdownContent);await openFile('integration.md');- // Wait for `harper-ls` to update diagnostics- await sleep(75);+ await waitForUpdatesFromOpenedFile();// Delete file directlyawait workspace.fs.delete(markdownUri);- // Wait for `harper-ls` to update diagnostics- await sleep(450);+ await waitForUpdatesFromDeletedFile();compareActualVsExpectedDiagnostics(getActualDiagnostics(markdownUri),diff --git a/packages/vscode-plugin/src/tests/suite/integrationBritish.test.ts b/packages/vscode-plugin/src/tests/suite/integrationBritish.test.tsdeleted file mode 100644index a523d2f68..000000000--- a/packages/vscode-plugin/src/tests/suite/integrationBritish.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import type { Extension } from 'vscode';--import { ConfigurationTarget, type Uri, commands, workspace } from 'vscode';--import {- activateHarper,- compareActualVsExpectedDiagnostics,- createExpectedDiagnostics,- createRange,- getActualDiagnostics,- openFile,- sleep,-} from './helper';--describe('IntegrationDialect >', () => {- let harper: Extension<void>;- let markdownUri: Uri;-- beforeAll(async () => {- harper = await activateHarper();- // Open test file so diagnostics can occur- markdownUri = await openFile('integrationBritish.md');- // Wait for `harper-ls` to start- await sleep(500);- });-- it('runs', () => {- expect(harper.isActive).toBe(true);- });-- it('gives correct diagnostics for default config', () => {- compareActualVsExpectedDiagnostics(- getActualDiagnostics(markdownUri),- createExpectedDiagnostics(),- );- });-- it('marks error when set to British English', async () => {- const config = workspace.getConfiguration('harper');- await config.update('dialect', 'British', ConfigurationTarget.Workspace);- // Wait for `harper-ls` to update diagnostics- await sleep(300);-- compareActualVsExpectedDiagnostics(- getActualDiagnostics(markdownUri),- createExpectedDiagnostics({- message: 'Did you mean to spell “color” this way?',- range: createRange(0, 41, 0, 46),- }),- );-- // Set config back to default value- await config.update('dialect', 'American', ConfigurationTarget.Workspace);- });-});diff --git a/packages/vscode-plugin/src/tests/suite/languages.test.ts b/packages/vscode-plugin/src/tests/suite/languages.test.tsindex 8a49801d5..9796b9a52 100644--- a/packages/vscode-plugin/src/tests/suite/languages.test.ts+++ b/packages/vscode-plugin/src/tests/suite/languages.test.ts@@ -1,19 +1,15 @@import {- activateHarper,compareActualVsExpectedDiagnostics,createExpectedDiagnostics,createRange,getActualDiagnostics,openFile,- sleep,+ waitForUpdatesFromOpenedFile,} from './helper';describe('Languages >', () => {- beforeAll(async () => {- await activateHarper();- // Wait for `harper-ls` to start- await sleep(500);- });+ // NOTE: There's no need to activate Harper here since it was already activated in+ // `integration.test.ts`, which runs first.[// Uncomment when #265 is fixed.@@ -21,7 +17,7 @@ describe('Languages >', () => {// Uncomment when #65 is fixed.// { type: 'Shellscript without extension', file: 'shellscript', row: 2, column: 2 },- // VSCode doesn't support CMake, Haskell, Literate Haskell, Nix, TOML, and Typst files out of+ // VS Code doesn't support CMake, Haskell, Literate Haskell, Nix, TOML, and Typst files out of// the box. Uncomment when you figure out how to support them during testing.// { type: 'CMake', file: 'CMakeLists.txt', row: 2, column: 30 },// { type: 'Haskell', file: 'haskell.hs', row: 1, column: 3 },@@ -55,9 +51,7 @@ describe('Languages >', () => {].forEach((testCase) => {it(`gives correct diagnostics for ${testCase.type} files`, async () => {const uri = await openFile('languages', testCase.file);-- // Wait for `harper-ls` to send diagnostics- await sleep(75);+ await waitForUpdatesFromOpenedFile();compareActualVsExpectedDiagnostics(getActualDiagnostics(uri),