Skip to content

Commit

Permalink
test: 增加部分集成测试
Browse files Browse the repository at this point in the history
Co-authored-by: ygqygq2 <ygqygq2@qq.com>
  • Loading branch information
ygqygq2 committed Apr 13, 2024
1 parent ace92b0 commit 2003567
Show file tree
Hide file tree
Showing 23 changed files with 177 additions and 79 deletions.
5 changes: 4 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 100
max_line_length = 120

[sampleWorkspace/**]
trim_trailing_whitespace = false
9 changes: 6 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"runtimeExecutable": "${execPath}",
"args": ["--disable-extensions", "--extensionDevelopmentPath=${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/out/**/*.js"],
"preLaunchTask": "${defaultBuildTask}"
"preLaunchTask": "${defaultBuildTask}",
"sourceMaps": true
},
{
"name": "Test: e2e",
Expand All @@ -22,7 +23,8 @@
"TS_NODE_PROJECT": "${workspaceFolder}/tsconfig.json"
},
"outFiles": ["${workspaceFolder}/out/**/*.js"],
"preLaunchTask": "npm: test-compile"
"preLaunchTask": "npm: test-compile",
"sourceMaps": true
},
{
"name": "Test: e2e use mocha",
Expand All @@ -40,7 +42,8 @@
"TS_NODE_PROJECT": "${workspaceFolder}/tsconfig.json"
},
"outFiles": ["${workspaceFolder}/out/test/**/*.js"],
"preLaunchTask": "npm: test-compile"
"preLaunchTask": "npm: test-compile",
"sourceMaps": true
},
{
"name": "Debug Current Unit Test File",
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ All notable changes to the "turbo-file-header" extension will be documented in t

## 新增功能 🌱

- feat: 增加 ts 文件函数注释功能
- feat: 增加 js/ts 文件函数注释功能

# [0.1.1]

Expand Down
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'warn',
'simple-import-sort/imports': 'warn',
'simple-import-sort/exports': 'warn',
'prettier/prettier': 'warn'
},
},
);
2 changes: 2 additions & 0 deletions sampleWorkspace/file-header/no-fileheader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const testString = 'this is a string';
console.log('🚀 ~ file: to-test-command-addFileheader.ts:2 ~ testString:', testString);
11 changes: 11 additions & 0 deletions sampleWorkspace/file-header/no-fileheader.result.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* @file sampleWorkspace/file-header/no-fileheader.ts
* @description test file header
* @author ygqygq2 <ygqygq2@qq.com>
* @createTime 2024-04-11 16:37:11
* @lastModified 2024-04-11 16:37:59
* Copyright ©ygqygq2 All rights reserved
*/

const testString = 'this is a string';
console.log('🚀 ~ file: to-test-command-addFileheader.ts:2 ~ testString:', testString);
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description test
* @return default {string}
* @param a {string}
* @param b {number}
*/
const func2 = (a: string, b: number): string => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description test
* @return default {string}
* @param a {string}
* @param b {string}
*/
const func2 = (a: string, b: number): string => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @param a {string}
* @param b {string}
*/
const func = (a: string, b: string): string => {
const func1 = (a: string, b: string): string => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const func = (a: string, b: string): string => {
const func1 = (a: string, b: string): string => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description
* @return default {void}
* @param a {any}
* @param b {any}
*/
const func = (a, b) => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description
* @return default {void}
* @param a {any}
* @param b {any}
*/
const func = (a, b) => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description
* @return default {void}
* @param a {any}
* @param b {any}
*/
const func = (a, b) => {
console.log(a + b);
return a + b;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @description
* @return default {void}
* @param a {any}
* @param b {any}
*/
const func = (a, b) => {
console.log(a + b);
return a + b;
};
8 changes: 5 additions & 3 deletions src/commands/addFileheader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ export const addFileheader = (): Command => {
return {
name: 'turboFileHeader.addFileheader',
handler: async (_context: vscode.ExtensionContext, args?: unknown[]) => {
const { activeEditor = vscode.window.activeTextEditor } = (args ?? [])[0] as {
activeEditor?: vscode.TextEditor;
};
let activeEditor: vscode.TextEditor | undefined;
if (args && args[0]) {
activeEditor = (args[0] as { activeEditor?: vscode.TextEditor }).activeEditor;
}
activeEditor = activeEditor ?? vscode.window.activeTextEditor;
// if no active window is open, return
if (!activeEditor) {
return;
Expand Down
8 changes: 5 additions & 3 deletions src/commands/addFunctionComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ export const addFunctionComment = (): Command => {
return {
name: 'turboFileHeader.addFunctionComment',
handler: async (_context: vscode.ExtensionContext, args?: unknown[]) => {
const { activeEditor = vscode.window.activeTextEditor } = (args ?? [])[0] as {
activeEditor?: vscode.TextEditor;
};
let activeEditor: vscode.TextEditor | undefined;
if (args && args[0]) {
activeEditor = (args[0] as { activeEditor?: vscode.TextEditor }).activeEditor;
}
activeEditor = activeEditor ?? vscode.window.activeTextEditor;

if (!activeEditor) {
return;
Expand Down
2 changes: 1 addition & 1 deletion src/configuration/ConfigReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import YAML from 'yaml';

import { CUSTOM_CONFIG_FILE_NAME } from '@/constants';
import { CustomError, ErrorCode } from '@/error';
import { ConfigYaml } from '@/typings/types';
import { logger } from '@/extension';
import { ConfigYaml } from '@/typings/types';

export class ConfigReader {
private static instance: ConfigReader;
Expand Down
23 changes: 5 additions & 18 deletions src/fileheader/FileheaderManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,7 @@ export class FileheaderManager {

public async updateFileheader(
document: vscode.TextDocument,
{
allowInsert = true,
addSelection = false,
newFile = false,
}: UpdateFileheaderManagerOptions = {},
{ allowInsert = true, addSelection = false, newFile = false }: UpdateFileheaderManagerOptions = {},
) {
const config = this.configManager.getConfiguration();
const provider = await findProvider(this.configManager, this.providers, document);
Expand All @@ -64,11 +60,7 @@ export class FileheaderManager {
return;
}

const originFileheaderInfo = getOriginFileheaderInfo(
document,
provider,
config.patternMultiline,
);
const originFileheaderInfo = getOriginFileheaderInfo(document, provider, config.patternMultiline);
let fileheaderVariable: IFileheaderVariables;
try {
fileheaderVariable = await this.fileheaderVariableBuilder?.build(
Expand Down Expand Up @@ -125,9 +117,7 @@ export class FileheaderManager {
updateProgress(progress, processedFiles, totalFiles);
} catch (error) {
reprocessedFiles.push(file);
logger.handleError(
new CustomError(ErrorCode.UpdateFileHeaderFail, file.fsPath, error),
);
logger.handleError(new CustomError(ErrorCode.UpdateFileHeaderFail, file.fsPath, error));
}
}

Expand Down Expand Up @@ -173,10 +163,7 @@ export class FileheaderManager {
const range = parser?.getOriginFunctionCommentRange(comments, document, insertPosition);
// 原来有函数注释
if (range) {
const originFunctionInfo: FunctionCommentInfo = parser?.parseFunctionComment(
document,
range,
) || {
const originFunctionInfo: FunctionCommentInfo = parser?.parseFunctionComment(document, range) || {
paramsInfo: {},
returnInfo: { default: { type: '', description: '' } },
descriptionInfo: '',
Expand All @@ -189,7 +176,7 @@ export class FileheaderManager {
if (functionCommentInfo) {
const originFunctionComment = generateFunctionComment(originFunctionInfo);
const functionComment = generateFunctionComment(functionCommentInfo);
// 函数注释有变化
// 函数注释没有变化
if (originFunctionComment === functionComment) {
logger.info('Not need update function comment:', document.uri.fsPath);
return false;
Expand Down
23 changes: 6 additions & 17 deletions src/function-params-parser/FunctionParamsParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,16 @@ export abstract class FunctionParamsParser {
const lineText = line.text;

// 更新块注释的开始和结束状态
isInsideBlockComment = updateBlockCommentState(
comments,
lineText,
isInsideBlockComment,
'up',
);
isInsideBlockComment = updateBlockCommentState(comments, lineText, isInsideBlockComment, 'up');
// 判断当前行是否是注释行
if (isCommentLine(comments, lineText, isInsideBlockComment)) {
startPosition = document.lineAt(i).range.start;
} else {
// 不在块注释中
if (!isInsideBlockComment) {
// 如果有多个空行,在往前最后一个空行 break
if (
line.isEmptyOrWhitespace &&
i - 1 >= 0 &&
!document.lineAt(i - 1).isEmptyOrWhitespace
) {
if (line.isEmptyOrWhitespace && i - 1 >= 0 && !document.lineAt(i - 1).isEmptyOrWhitespace) {
startPosition = document.lineAt(i + 1).range.start;
break;
}
// 如果当前行不是空行,结束循环
Expand All @@ -100,10 +92,7 @@ export abstract class FunctionParamsParser {
return range;
}

public parseFunctionComment(
document: vscode.TextDocument,
range: vscode.Range,
): FunctionCommentInfo {
public parseFunctionComment(document: vscode.TextDocument, range: vscode.Range): FunctionCommentInfo {
const descriptionPattern = /@description\s+(.*)/;
const paramPattern = /@param\s+(\w+)\s*\{(.+?)\}\s*(.*)/;
const returnPattern = /@return\s+(?:(\w+)\s*)?\{(.+?)\}\s*(.*)/;
Expand All @@ -116,10 +105,10 @@ export abstract class FunctionParamsParser {
for (const line of functionCommentLines) {
let match;
if ((match = paramPattern.exec(line)) !== null) {
const [_, name, type, description = ''] = match;
const [_, name, type = 'any', description = ''] = match;
paramsInfo[name] = { type, description };
} else if ((match = returnPattern.exec(line)) !== null) {
const [_, key = 'default', type, description = ''] = match;
const [_, key = 'default', type = 'any', description = ''] = match;
returnInfo[key] = { type, description };
} else if ((match = descriptionPattern.exec(line)) !== null) {
const [_, description] = match;
Expand Down
8 changes: 4 additions & 4 deletions src/function-params-parser/TypescriptProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ function splitParams(paramsStr: string): ParamsInfo {
} else if (char === ',' && bracketCount === 0) {
const paramStr = paramsStr.slice(paramStartIndex, i);
const colonIndex = paramStr.indexOf(':');
const name = paramStr.slice(0, colonIndex).trim();
const type = paramStr.slice(colonIndex + 1).trim();
const name = paramStr.slice(0, colonIndex !== -1 ? colonIndex : paramStr.length).trim();
const type = colonIndex !== -1 ? paramStr.slice(colonIndex + 1).trim() : 'any';
params[name] = { type, description: '' };
paramStartIndex = i + 1;
}
}
const paramStr = paramsStr.slice(paramStartIndex);
const colonIndex = paramStr.indexOf(':');
const name = paramStr.slice(0, colonIndex).trim();
const type = paramStr.slice(colonIndex + 1).trim();
const name = paramStr.slice(0, colonIndex !== -1 ? colonIndex : paramStr.length).trim();
const type = colonIndex !== -1 ? paramStr.slice(colonIndex + 1).trim() : 'any';
params[name] = { type, description: '' };
return params;
}
Expand Down
43 changes: 26 additions & 17 deletions src/test/suite/addFileheader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,34 @@ import { describe, it } from 'mocha';

import { executeCommandOnFile } from './common/executeCommandOnFile';

const testInfo = [
{
workspaceName: 'file-header',
files: [
{ fileName: 'no-fileheader.js', cursorLine: 0 },
{ fileName: 'no-fileheader.ts', cursorLine: 0 },
{ fileName: 'no-fileheader.go', cursorLine: 0 },
],
},
];

describe('Extension Integration Test: addFileheader', function () {
this.timeout(20000);
it('should add file header for [.ts]', async () => {
const commandName = 'turboFileHeader.addFileheader';
const workspaceName = 'file-header';
const fileName = 'no-fileheader.ts';
const { actual } = await executeCommandOnFile(commandName, workspaceName, fileName, false);
// 有 Copyright 字符串即可
assert.notEqual(actual.indexOf('Copyright'), -1);
// @description 后面有非空格字符
assert.match(actual, /@description\s+\S+/);
});

it('should add file header for [.go]', async () => {
const commandName = 'turboFileHeader.addFileheader';
const workspaceName = 'file-header';
const fileName = 'no-fileheader.go';
const { actual } = await executeCommandOnFile(commandName, workspaceName, fileName, false);
assert.notEqual(actual.indexOf('Copyright'), -1);
assert.match(actual, /@description\s+\S+/);
testInfo.forEach((item) => {
const workspaceName = item.workspaceName;
const files = item.files;
files.forEach((fileInfo) => {
const fileName = fileInfo.fileName;
const cursorLine = fileInfo.cursorLine;
it(`should add file header for [${fileName}]`, async () => {
const commandName = 'turboFileHeader.addFileheader';
const { actual } = await executeCommandOnFile(commandName, workspaceName, fileName, cursorLine, false);
// 有 Copyright 字符串即可
assert.notEqual(actual.indexOf('Copyright'), -1);
// @description 后面有非空格字符
assert.match(actual, /@description\s+\S+/);
});
});
});
});
Loading

0 comments on commit 2003567

Please sign in to comment.