Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
95 changes: 95 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Документация по плагину

## Общее описание решения

- Реализован плагин (расширение) для Visual Studio Code, позволяющий **автоматически** генерировать тестовый файл (`unittest`) на основе выделенной функции в Python-коде.
- При выполнении команды `autotestsplagin.createFile`:

1: Проверяется, **открыта ли рабочая область** (Workspace) в VS Code.

2: Проверяется, **есть ли активный редактор** с выделенным фрагментом кода.

3: Извлекается из выделенного кода **имя функции** (через регулярное выражение `def имя(...)`), либо подставляется «function» по умолчанию.

4: Формируется шаблон теста с помощью **unittest**, в который:
- Подставляется выделенный код функции.
- Создаётся класс теста `Test<ИмяФункции>`.
- Генерируются базовые проверки (`assertEqual`, `assertNotEqual`, `assertTrue`, `assertFalse`).

5: **Создаётся** новый файл с префиксом `test_` (например, `test_example.py`) и **открывается** в редакторе.

## История изменений

После добавления комментариев и базового функционала плагина были выполнены команды:

```bash
git add .
git commit -m "Добавлены комментарии ко всем функциям и общий функционал плагина"
git checkout -b vs_extension_documentation
git push origin vs_extension_documentation
```

И был создан pull request для слияния изменений.

---

## Описание функций

### `activate(context: vscode.ExtensionContext)`

**Описание:** Точка входа для расширения. Регистрирует команду `autotestsplagin.createFile`, которая запускает процесс генерации тестов.

**Пример вызова:**

```ts
export async function activate(context: vscode.ExtensionContext) {
// Автоматически вызывается при запуске плагина VS Code
}
```

### `deactivate()`

**Описание:** Функция, вызываемая при деактивации (выключении) расширения. Часто оставляется пустой, если нет логики освобождения ресурсов.

**Пример вызова:**

```ts
export function deactivate() {
// Обычно не требуется в простых плагинах
}
```

### Вспомогательные функции

#### `extractFunctionName(code: string): string | null`

**Описание:** Ищет в переданной строке Python-кода определение функции вида `def имя_функции(...)`. Возвращает найденное имя или `null`, если не найдено.

**Пример вызова:**

```ts
const codeSample = "def my_func(x):\n return x";
const name = extractFunctionName(codeSample);
// name будет "my_func"
```

#### `generateTestTemplate(functionName: string, functionCode: string): string`

**Описание:** Создаёт строку-шаблон, встраивая в неё Python-функцию (`functionCode`) и тестовый класс `Test<ИмяФункции>`. Используется для записи в новый файл `test_<имя>.py`.

**Пример вызова:**

```ts
const template = generateTestTemplate("my_func", "def my_func():\n return 42");
// template будет содержать готовый код теста в формате unittest
```

---

## История изменения проекта с хешами коммитов
- commit [a94a15c4b99692c7c4c4e883a9f49b9a104e690f](https://github.com/KulEDmitr/geometric_lib/commit/a94a15c4b99692c7c4c4e883a9f49b9a104e690f) "```lab_3_plagin```
- commit [02a79887e2cebb9f607ca612d5c72bebece5d822](https://github.com/KulEDmitr/geometric_lib/commit/02a79887e2cebb9f607ca612d5c72bebece5d822) "изменены названия" в ветке ```lab_3_plagin```
- commit [9e365d435a0c2901344b0e76f37ea46dcfd23a7d](https://github.com/KulEDmitr/geometric_lib/commit/9e365d435a0c2901344b0e76f37ea46dcfd23a7d) "удалены лишние файлы" в ветке ```lab_3_plagin```
- commit [cdb21374674ca9ab9ad613bc8cfc56e07ee4a14d](https://github.com/takuya-q/geometric_lib/commit/2948d3e67c535af4d544e379057a159ad3d38e10) "Возвращены работающие функции" в ветке ```lab_3_plagin```
- commit [07c91bffd07998103d244a6f237840d4e5a2822b](https://github.com/takuya-q/geometric_lib/commit/e9eba38bb06e9f494dccf4d8f2e3d929cd929a81) "удалены лишние файлы" в ветке ```lab_3_plagin```
- commit [[1016ac4401a02d1c1b8f45a1ce934c6b1f1a5abf](https://github.com/KulEDmitr/geometric_lib/commit/1016ac4401a02d1c1b8f45a1ce934c6b1f1a5abf)](1016ac4401a02d1c1b8f45a1ce934c6b1f1a5abf) "Add plagin" в ветке ```lab_3_plagin```
37 changes: 37 additions & 0 deletions autotestplagin/autoPLtest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def add(a: int, b: int) -> int:
return a + b

def reverse_string(s: str) -> str:
return s[::-1]

def is_even(n: int) -> bool:
return n % 2 == 0

def find_max(lst: list[int]) -> int:
if not lst:
raise ValueError("Список не должен быть пустым")
return max(lst)

def factorial(n: int) -> int:
if n < 0:
raise ValueError("Факториал отрицательного числа не определён")
return 1 if n == 0 else n * factorial(n - 1)

def fibonacci(n: int) -> int:
if n < 0:
raise ValueError("Число должно быть неотрицательным")
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a

def sieve_of_eratosthenes(n: int) -> list[int]:
if n < 2:
return []
primes = [True] * (n + 1)
primes[0] = primes[1] = False
for i in range(2, int(n**0.5) + 1):
if primes[i]:
for j in range(i * i, n + 1, i):
primes[j] = False
return [i for i, is_prime in enumerate(primes) if is_prime]
5 changes: 5 additions & 0 deletions autotestsplagin/.vscode-test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineConfig } from '@vscode/test-cli';

export default defineConfig({
files: 'out/test/**/*.test.js',
});
8 changes: 8 additions & 0 deletions autotestsplagin/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"ms-vscode.extension-test-runner"
]
}
21 changes: 21 additions & 0 deletions autotestsplagin/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
11 changes: 11 additions & 0 deletions autotestsplagin/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}
20 changes: 20 additions & 0 deletions autotestsplagin/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
11 changes: 11 additions & 0 deletions autotestsplagin/.vscodeignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.vscode/**
.vscode-test/**
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/eslint.config.mjs
**/*.map
**/*.ts
**/.vscode-test.*
9 changes: 9 additions & 0 deletions autotestsplagin/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Change Log

All notable changes to the "autotestsplagin" extension will be documented in this file.

Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.

## [Unreleased]

- Initial release
71 changes: 71 additions & 0 deletions autotestsplagin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# autotestsplagin README

This is the README for your extension "autotestsplagin". After writing up a brief description, we recommend including the following sections.

## Features

Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.

For example if there is an image subfolder under your extension project workspace:

\!\[feature X\]\(images/feature-x.png\)

> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.

## Requirements

If you have any requirements or dependencies, add a section describing those and how to install and configure them.

## Extension Settings

Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.

For example:

This extension contributes the following settings:

* `myExtension.enable`: Enable/disable this extension.
* `myExtension.thing`: Set to `blah` to do something.

## Known Issues

Calling out known issues can help limit users opening duplicate issues against your extension.

## Release Notes

Users appreciate release notes as you update your extension.

### 1.0.0

Initial release of ...

### 1.0.1

Fixed issue #.

### 1.1.0

Added features X, Y, and Z.

---

## Following extension guidelines

Ensure that you've read through the extensions guidelines and follow the best practices for creating your extension.

* [Extension Guidelines](https://code.visualstudio.com/api/references/extension-guidelines)

## Working with Markdown

You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:

* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.

## For more information

* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)

**Enjoy!**
28 changes: 28 additions & 0 deletions autotestsplagin/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import typescriptEslint from "@typescript-eslint/eslint-plugin";
import tsParser from "@typescript-eslint/parser";

export default [{
files: ["**/*.ts"],
}, {
plugins: {
"@typescript-eslint": typescriptEslint,
},

languageOptions: {
parser: tsParser,
ecmaVersion: 2022,
sourceType: "module",
},

rules: {
"@typescript-eslint/naming-convention": ["warn", {
selector: "import",
format: ["camelCase", "PascalCase"],
}],

curly: "warn",
eqeqeq: "warn",
"no-throw-literal": "warn",
semi: "warn",
},
}];
16 changes: 16 additions & 0 deletions autotestsplagin/node_modules/.bin/_mocha

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

17 changes: 17 additions & 0 deletions autotestsplagin/node_modules/.bin/_mocha.cmd

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

28 changes: 28 additions & 0 deletions autotestsplagin/node_modules/.bin/_mocha.ps1

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

Loading