Skip to content
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

Add client tests #29

Merged
merged 11 commits into from
Oct 20, 2023
20 changes: 17 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ module.exports = {
browser: true,
es2021: true
},
extends: 'standard-with-typescript',
extends: [
'standard-with-typescript',
'plugin:deprecation/recommended'
],
overrides: [
{
env: {
Expand All @@ -21,6 +24,17 @@ module.exports = {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {},
ignorePatterns: ['out']
plugins: ['header'],
rules: {
"header/header": [2, "block", [
" --------------------------------------------------------------------------------------------",
{"pattern": " \\* Copyright \\(c\\) .*\\. All rights reserved\\.", "template": " * Copyright (c) 2023 Savoir-faire Linux. All rights reserved."},
" * Licensed under the MIT License. See License.txt in the project root for license information.",
" * ------------------------------------------------------------------------------------------ ",
], 2]
},
ignorePatterns: [
'out',
'__mocks__/vscode.ts'
],
}
5 changes: 4 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,7 @@ jobs:
run: npm run lint

- name: Build Project
run: npm run compile
run: npm run compile

- name: Test Project
run: npm run test
13 changes: 13 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@
"${workspaceRoot}/server/out/**/*.js"
],
"preLaunchTask": "watch:server"
},
{
"name": "Jest tests",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/jest/bin/jest",
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/*/out/**/*.js"
],
"preLaunchTask": "compile",
"console": "integratedTerminal"

}
],
"compounds": [
Expand Down
5 changes: 3 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
"typescript.tsc.autoDetect": "off",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
},
"jest.jestCommandLine": "node_modules/.bin/jest"
}
134 changes: 134 additions & 0 deletions __mocks__/vscode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Jtest Mock from https://github.com/jest-community/vscode-jest/blob/1867bde9ebf8c21d45409e7ad8a95a743ac4390d/__mocks__/vscode.ts
// under MIT License

const languages = {
createDiagnosticCollection: jest.fn(),
Copy link
Member

Choose a reason for hiding this comment

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

indentation is weird here

Copy link
Member Author

Choose a reason for hiding this comment

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

As discussed in another comment, I suggest keeping the original file and not changing it's linting rules.

registerCodeLensProvider: jest.fn(),
};

const StatusBarAlignment = { Left: 1, Right: 2 };

const window = {
createStatusBarItem: jest.fn(() => ({
show: jest.fn(),
hide: jest.fn(),
tooltip: jest.fn(),
})),
showErrorMessage: jest.fn(),
showWarningMessage: jest.fn(),
createTextEditorDecorationType: jest.fn(),
createOutputChannel: jest.fn(),
showWorkspaceFolderPick: jest.fn(),
showQuickPick: jest.fn(),
onDidChangeActiveTextEditor: jest.fn(),
showInformationMessage: jest.fn(),
createWebviewPanel: jest.fn(),
};

const workspace = {
getConfiguration: jest.fn(),
workspaceFolders: [],
getWorkspaceFolder: jest.fn(),

onDidChangeConfiguration: jest.fn(),
onDidChangeTextDocument: jest.fn(),
onDidChangeWorkspaceFolders: jest.fn(),
onDidCreateFiles: jest.fn(),
onDidDeleteFiles: jest.fn(),
onDidRenameFiles: jest.fn(),
onDidSaveTextDocument: jest.fn(),
onWillSaveTextDocument: jest.fn(),
};

const OverviewRulerLane = {
Left: null,
};

const Uri = {
file: (f: any) => f,
parse: jest.fn(),
joinPath: jest.fn(),
};
const Range = jest.fn();
const Location = jest.fn();
const Position = jest.fn();
const Diagnostic = jest.fn();
const ThemeIcon = jest.fn();
const DiagnosticSeverity = { Error: 0, Warning: 1, Information: 2, Hint: 3 };
const ConfigurationTarget = { Global: 1, Workspace: 2, WorkspaceFolder: 3 };

const debug = {
onDidTerminateDebugSession: jest.fn(),
startDebugging: jest.fn(),
registerDebugConfigurationProvider: jest.fn(),
};

const commands = {
executeCommand: jest.fn(),
registerCommand: jest.fn(),
registerTextEditorCommand: jest.fn(),
};

// eslint-disable-next-line @typescript-eslint/no-empty-function
const CodeLens = function CodeLens() {};

const QuickInputButtons = {
Back: {},
};

const tests = {
createTestController: jest.fn(),
};

const TestRunProfileKind = {
Run: 1,
Debug: 2,
Coverage: 3,
};
const ViewColumn = {
One: 1,
Tow: 2,
};

const TestMessage = jest.fn();
const TestRunRequest = jest.fn();
const ThemeColor = jest.fn();

const EventEmitter = jest.fn().mockImplementation(() => {
return {
fire: jest.fn(),
};
});

const QuickPickItemKind = {
Separator: -1,
Default: 0,
};

export = {
Copy link
Member

Choose a reason for hiding this comment

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

On my side typescript complains it is using the CommonJS syntax, while the EcmaScript syntaxt should be used (export default). Yet it won't compile if I make that change.

I am not sure where is exactly the problem, but I noticed .eslintrc.js is also using a commonjs export. I also noticed you put this file into "ignorePatterns". I am thinking this was an attempt to solve that problem.

Copy link
Member Author

Choose a reason for hiding this comment

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

This file comes from another repo and works fine. As long as we don't change it, it makes no sense to me to test it's linting, which follows a different standard in another project. Also it makes it easy to update this file in the future when the vscode API changes/adds new features. I suggest to ignore linting this file and keep it as original. A comment at the top clearly indicates where it comes from.

Copy link
Member

Choose a reason for hiding this comment

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

Makes sense. However I am surprised it works. Both syntaxes are not supposed to be interchangeable within a project. As a proof, this file does not compile if you use the ecmascript syntax. It makes me think the "root project" is not configured properly.

ThemeColor,
CodeLens,
languages,
StatusBarAlignment,
window,
workspace,
OverviewRulerLane,
Uri,
Range,
Location,
Position,
Diagnostic,
ThemeIcon,
DiagnosticSeverity,
ConfigurationTarget,
debug,
commands,
QuickInputButtons,
tests,
TestRunProfileKind,
EventEmitter,
TestMessage,
TestRunRequest,
ViewColumn,
QuickPickItemKind,
};
8 changes: 8 additions & 0 deletions client/src/__tests__/test.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2023 Savoir-faire Linux. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */

test('two plus three is five', () => {
expect(2 + 3).toBe(5)
})
56 changes: 56 additions & 0 deletions client/src/__tests__/unit-tests/output-logger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2023 Savoir-faire Linux. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */

import * as vscode from 'vscode'
import { logger } from '../../ui/OutputLogger'

jest.mock('vscode')

const mockLoggerConfiguration = (loggingLevel: string): void => {
vscode.workspace.getConfiguration = jest.fn().mockImplementation(() => ({
get: () => loggingLevel
}))
}

const mockChannel = (): jest.Mocked<any> => {
const mockOutputChannel = {
appendLine: jest.fn(),
show: jest.fn(),
clear: jest.fn()
}

vscode.window.createOutputChannel = jest.fn().mockImplementation(() => mockOutputChannel)

return mockOutputChannel
}

describe('OutputLogger Tests', () => {
beforeEach(() => {
jest.clearAllMocks()
})

it('should define a singleton logger instance', () => {
expect(logger).toBeDefined()
})

it('should correctly log messages with appropriate log level', () => {
const mockOutputChannel = mockChannel()
mockLoggerConfiguration('warning')

logger.setOutputChannel(vscode.window.createOutputChannel('Bitbake'))
logger.loadSettings()

const logSpy = jest.spyOn(mockOutputChannel, 'appendLine')

logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')

expect(logSpy).toHaveBeenCalledTimes(2)
expect(logSpy).toHaveBeenCalledWith('Warning message')
expect(logSpy).toHaveBeenCalledWith('Error message')
})
})
2 changes: 2 additions & 0 deletions client/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const bitbakeWorkspace: BitbakeWorkspace = new BitbakeWorkspace()
export let bitbakeExtensionContext: vscode.ExtensionContext

export async function activate (context: vscode.ExtensionContext): Promise<void> {
logger.setOutputChannel(vscode.window.createOutputChannel('BitBake'))
logger.loadSettings()
bitbakeExtensionContext = context
bitbakeDriver.loadSettings()
bitbakeWorkspace.loadBitbakeWorkspace(context.workspaceState)
Expand Down
15 changes: 9 additions & 6 deletions client/src/ui/BitbakeCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ async function buildRecipeCommand (bitbakeWorkspace: BitbakeWorkspace, taskProvi
logger.debug(`Command: build-recipe: ${chosenRecipe}`)
const task = new vscode.Task(
{ type: 'bitbake', recipes: [chosenRecipe] },
`Run bitbake ${chosenRecipe}`,
'bitbake'
vscode.TaskScope.Workspace,
`Run bitbake ${chosenRecipe}`,
'bitbake'
)
await runBitbakeTask(task, taskProvider)
}
Expand All @@ -39,8 +40,9 @@ async function cleanRecipeCommand (bitbakeWorkspace: BitbakeWorkspace, taskProvi
logger.debug(`Command: clean-recipe: ${chosenRecipe}`)
const task = new vscode.Task(
{ type: 'bitbake', recipes: [chosenRecipe], task: 'clean' },
`Run bitbake ${chosenRecipe}`,
'bitbake'
vscode.TaskScope.Workspace,
`Run bitbake ${chosenRecipe}`,
'bitbake'
)
await runBitbakeTask(task, taskProvider)
}
Expand All @@ -54,8 +56,9 @@ async function runTaskCommand (bitbakeWorkspace: BitbakeWorkspace, taskProvider:
logger.debug(`Command: run-task: ${chosenRecipe} -c ${chosenTask}`)
const task = new vscode.Task(
{ type: 'bitbake', recipes: [chosenRecipe], task: chosenTask },
`Run bitbake ${chosenRecipe} -c ${chosenTask}`,
'bitbake'
vscode.TaskScope.Workspace,
`Run bitbake ${chosenRecipe} -c ${chosenTask}`,
'bitbake'
)
await runBitbakeTask(task, taskProvider)
}
Expand Down
22 changes: 11 additions & 11 deletions client/src/ui/OutputLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@
import * as vscode from 'vscode'

export class OutputLogger {
private static instance: OutputLogger | undefined
private static readonly outputChannelName = 'BitBake'
private static instance: OutputLogger

private readonly outputChannel: vscode.OutputChannel
private outputChannel: vscode.OutputChannel | undefined
// default value in package.json
private loggingLevel: string = ''

private constructor () {
this.outputChannel = vscode.window.createOutputChannel(OutputLogger.outputChannelName)
this.loadSettings()
}
private constructor () { }

public loadSettings (): void {
this.loggingLevel = vscode.workspace.getConfiguration('bitbake').get('loggingLevel') ?? 'info'
this.info('Bitbake logging level: ' + this.loggingLevel)
}

public setOutputChannel (outputChannel: vscode.OutputChannel): void {
this.outputChannel = outputChannel
}

public static getInstance (): OutputLogger {
if (OutputLogger.instance === undefined) {
OutputLogger.instance = new OutputLogger()
Expand All @@ -32,8 +32,8 @@ export class OutputLogger {

public log (message: string, level: string = 'info'): void {
if (this.shouldLog(level)) {
this.outputChannel.appendLine(message)
this.outputChannel.show()
this.outputChannel?.appendLine(message)
this.outputChannel?.show()

// Also log to the console (debug view)
console.log(message)
Expand All @@ -57,7 +57,7 @@ export class OutputLogger {
}

public clear (): void {
this.outputChannel.clear()
this.outputChannel?.clear()
}

private shouldLog (level: string): boolean {
Expand All @@ -71,4 +71,4 @@ export class OutputLogger {
}

// Create and export the singleton logger instance
export const logger = OutputLogger.getInstance()
export const logger: OutputLogger = OutputLogger.getInstance()
6 changes: 3 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ module.exports = {
]
},
testMatch: [
"<rootDir>/**/__tests__/*.ts"
"<rootDir>/**/__tests__/**/*.test.ts"
],
collectCoverageFrom: [
"**/*.ts",
"!**/__test__/*",
"!**/__test__/**/*.ts",
deribaucourt marked this conversation as resolved.
Show resolved Hide resolved
"!testing/*"
],
};
};
Loading
Loading