Skip to content

feat: Расширена валидация входных параметров бенчмарка#24

Merged
Stivo182 merged 1 commit intomainfrom
refactor/validate-params
Aug 31, 2025
Merged

feat: Расширена валидация входных параметров бенчмарка#24
Stivo182 merged 1 commit intomainfrom
refactor/validate-params

Conversation

@Stivo182
Copy link
Owner

@Stivo182 Stivo182 commented Aug 31, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Stricter validation of benchmark parameters: verifies declared parameters exist and counts match.
    • Prevents passing parameters to methods without parameters and single values to methods expecting multiple.
    • Clearer error messages showing actual vs. expected parameter counts and method name.
  • Tests

    • Added comprehensive tests covering parameter mismatches and edge cases.
    • Renamed tests for clearer intent and consistency.

@coderabbitai
Copy link

coderabbitai bot commented Aug 31, 2025

Walkthrough

Updates centralize and strengthen benchmark parameter validation in the descriptor and launcher, relax count checks in the annotation extractor, and expand tests. Error messages now include actual/expected counts and method names. New tests cover mismatched counts, zero-parameter cases, and single-parameter vs multi-parameter scenarios.

Changes

Cohort / File(s) Summary
Parameter validation in core
src/BenchmarkOneScript/core/Классы/ДескрипторБенчмарка.os, src/BenchmarkOneScript/core/Классы/ЗапускательБенчмарков.os
Added explicit checks for declared parameters, exact count matching, and single-value vs multi-parameter mismatch; updated error messages to include actual/expected counts and method name; switched to deriving required count from parameter names.
Annotation extraction adjustments
src/BenchmarkOneScript/core/Модули/ИзвлекательДескрипторовБенчмарков.os
Removed strict validation comparing annotated parameter count with method parameter count; continues extracting/adding parameters without enforcing count parity.
Tests: renames and new parameter cases
tests/ТестыБенчмарков.os
Renamed several exported tests to “Проверяет…”. Added new exported tests covering fewer/more parameters, no declared parameters, and single vs multiple. Updated expected error texts and added a helper for valid single-parameter values.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant E as ИзвлекательАннотаций
  participant D as ДескрипторБенчмарка
  participant R as ЗапускательБенчмарков
  participant M as МетодБенчмарка

  Note over E,D: Чтение аннотаций параметров (ослаблена проверка количества)
  E->>D: ДобавитьПараметры(из аннотаций)
  D-->>E: OK (без проверки паритета количества)

  R->>D: ДобавитьПараметры(входные параметры)
  alt Нет объявленных параметров у метода
    D-->>R: Исключение: метод не имеет параметров
  else Неверное количество
    D-->>R: Исключение: передано N, ожидается K, метод <имя>
  else Одиночное значение при нескольких параметрах
    D-->>R: Исключение: одиночный параметр при множественных
  else Валидные параметры
    D-->>R: OK
    R->>M: Вызов с параметрами
    M-->>R: Результат
  end

  Note over R: Сообщения об ошибках содержат N, K, имя метода
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I whisk my ears at params bright,
Counted neatly, left and right—
One is one, and two means two,
Benchmarks hop when checks are true.
If numbers stray, I thump the ground,
Then happily race another round. 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/validate-params

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonar-openbsl-ru-qa-bot
Copy link

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/BenchmarkOneScript/core/Классы/ДескрипторБенчмарка.os (1)

51-57: НаборыПараметров: вернуть глубже-иммутабельное представление

Сейчас возвращается неглубокая копия — внутренние массивы можно изменить снаружи. Предлагаю обернуть и вложенные массивы во ФиксированныйМассив.

Пример правки:

 Функция НаборыПараметров() Экспорт
-	Возврат Новый Массив(Новый ФиксированныйМассив(_НаборыПараметров));
+	ЛокальныеНаборы = Новый Массив();
+	Для Каждого Набор Из _НаборыПараметров Цикл
+		ЛокальныеНаборы.Добавить(Новый Массив(Новый ФиксированныйМассив(Набор)));
+	КонецЦикла;
+	Возврат Новый Массив(Новый ФиксированныйМассив(ЛокальныеНаборы));
 КонецФункции
tests/ТестыБенчмарков.os (4)

216-241: Переизбыток параметров — проверка корректна; уменьшить хрупкость проверок текста

Сейчас матчится полный текст исключения — это хрупко к мелким правкам сообщений. Рассмотрите проверку по подстрокам (например, содержит имя метода и оба числа).


244-268: Недостаток параметров — аналогичное замечание

Проверять ключевые части сообщения вместо полного текста.


270-291: Передача параметров для метода без параметров — ок; та же рекомендация по сообщению

Логика верна, лучше матчить существенные фрагменты.


293-314: Одиночное значение при множественных параметрах — ок; снизить хрупкость проверки текста

См. рекомендации выше.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 181e621 and a1a08b9.

📒 Files selected for processing (4)
  • src/BenchmarkOneScript/core/Классы/ДескрипторБенчмарка.os (1 hunks)
  • src/BenchmarkOneScript/core/Классы/ЗапускательБенчмарков.os (1 hunks)
  • src/BenchmarkOneScript/core/Модули/ИзвлекательДескрипторовБенчмарков.os (0 hunks)
  • tests/ТестыБенчмарков.os (6 hunks)
💤 Files with no reviewable changes (1)
  • src/BenchmarkOneScript/core/Модули/ИзвлекательДескрипторовБенчмарков.os
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: test (dev) / build (macos-latest, dev)
  • GitHub Check: test (dev) / build (ubuntu-latest, dev)
  • GitHub Check: test (stable) / build (windows-latest, stable)
  • GitHub Check: test (dev) / build (windows-latest, dev)
  • GitHub Check: sonar / test
  • GitHub Check: test (stable) / build (ubuntu-latest, stable)
  • GitHub Check: test (stable) / build (macos-latest, stable)
  • GitHub Check: test (stable) / build (windows-latest, stable)
  • GitHub Check: test (stable) / build (ubuntu-latest, stable)
  • GitHub Check: test (stable) / build (macos-latest, stable)
  • GitHub Check: sonar / test
🔇 Additional comments (11)
src/BenchmarkOneScript/core/Классы/ЗапускательБенчмарков.os (1)

723-731: Чёткая валидация числа параметров — 👍

Перенос сравнения на локальную переменную и расширенное сообщение об ошибке выглядят корректно и согласованы с Дескриптором.

src/BenchmarkOneScript/core/Классы/ДескрипторБенчмарка.os (4)

59-65: Докстринг стал яснее

Формулировки по форматам входа и ограничениям читаются лучше.


71-79: Запрет параметров для методов без объявленных параметров — корректно

Ранний фейл с информативным сообщением уместен.


82-90: Проверка точного совпадения количества — уместно

Сообщение включает фактическое и ожидаемое значения, а также имя метода.


98-105: Одиночное значение при множественных параметрах — корректная ошибка

Логика и текст сообщения соответствуют ожиданиям.

tests/ТестыБенчмарков.os (6)

142-146: Группировка тестов в область “Параметры” — удачно

Навигацию по набору сценариев заметно упрощает.


145-158: Аннотации параметров: проверка отчёта и дескриптора — ок

Покрытие ключевых значений и флага ЭтоПараметрМетода достаточное.


161-185: Комбинация параметров метода и поля — ок

Матрица параметров и ожидания согласованы.


187-213: Установка параметров через Дескриптор — ок

Оба набора параметров корректно отображаются в отчёте.


660-666: Переименование теста на сериализуемость — ок

Именование унифицировано со стилем “Проверяет…”.


1215-1216: Актуализирован ожидаемый текст ошибки из источника параметров — ок

Тест отражает новое сообщение валидатора количества.

@Stivo182 Stivo182 merged commit 1bb6ac3 into main Aug 31, 2025
14 of 20 checks passed
@Stivo182 Stivo182 deleted the refactor/validate-params branch August 31, 2025 19:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant