exp-test-smell-detection

dotnet/skills

Глубокий аудит по академическому каталогу из 19 тестовых запахов testsmells.org для любого языка: каждый вывод привязан к именованному запаху из литературы.

Звёзды6 265
Авторdotnet
Установок3

Установка

SKILL.md

Test Smell Detection

Deep formal audit of test code in any supported language using an academic test smell taxonomy. Detects symptoms of bad design or implementation decisions that make tests harder to understand, more fragile, less effective at catching bugs, or more expensive to maintain. Produces a severity-ranked report with specific locations and actionable fixes.

Language-specific guidance: Call the test-analysis-extensions skill to discover available extension files, then read the file matching the target codebase. The extension file documents test markers, sleep / time / random APIs, skip annotations, setup/teardown, mystery-guest indicators (file/database/network/env), integration markers, and language-specific calibration notes that drive the smell detectors below.

Why Test Smells Matter

Test smells erode confidence in a test suite and inflate maintenance costs:

ProblemConsequence
Tests with conditional logicSome paths never execute — hidden testing gaps
Tests that depend on external resourcesFlaky failures, slow execution, environment coupling
Tests that sleep to wait for resultsNon-deterministic timing, slow suites, false failures
Tests without assertionsFalse confidence — coverage looks good but nothing is verified
Tests that call many production methodsHard to diagnose failures, unclear what's being tested
Tests with magic numbersUnreadable intent, unclear boundary conditions
Tests relying on ToString for comparisonBrittle to formatting changes, obscure failure messages
Tests with exception handling logicSwallowed failures, tests that pass when they shouldn't

When to Use

  • User asks for a comprehensive or formal test smell audit
  • User asks "are my tests well-written?" and wants a thorough analysis
  • User wants a test quality health check with academic rigor
  • User asks for a review of test design or structure using standard smell categories
  • User suspects tests are fragile, flaky, or giving false confidence and wants a deep investigation

When Not to Use

  • User wants a quick pragmatic test review (use test-anti-patterns — faster, covers the most common issues)
  • User wants to evaluate assertion diversity specifically (use assertion-quality)
  • User wants to find duplicated boilerplate across tests (use exp-test-maintainability)
  • User wants to write new tests from scratch (help them directly)
  • User wants to fix a specific failing test (diagnose and fix directly)

Inputs

InputRequiredDescription
Test codeYesOne or more test files or a test project directory to analyze
Production codeNoThe code under test, for context on whether patterns are justified

Workflow

Step 1: Detect language and load extension

Identify the target codebase's language and test framework. Call the test-analysis-extensions skill and read the matching extension file (e.g., extensions/dotnet.md, extensions/python.md, extensions/typescript.md, extensions/go.md). The extension file lists the framework-specific test markers, sleep / wait APIs, skip / ignore attributes, mystery-guest indicators, and integration-test markers that the smell detectors below need.

Step 2: Gather the test code

Read all test files the user provides. If the user points to a directory or project, scan for all test files using the markers in the loaded language extension file.

For a thorough audit, also consult the extended smell catalog which covers 9 additional smell types beyond the core 10 below.

Step 3: Scan for test smells

For each test method and class, check for the following smell categories. Examples reference .NET attributes but the patterns apply across all supported languages — use the loaded language extension file to map each pattern to the framework you are auditing.

Smell 1: Conditional Test Logic

Test methods containing if, else, switch, ternary (? :), for, foreach, while, or pattern-match arms that change assertion behavior. Control flow in tests means some paths may never execute, hiding gaps.

Severity: High Detection: Any control-flow statement inside a test method body that affects which assertions run. Exceptions (per-language idioms, do NOT flag):

  • Foreach-assert used solely to assert every item in a known collection (the assertion is the loop body).
  • Go / Rust table-driven tests: for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ... }) } (Go) or #[rstest] parametrized loops are idiomatic.
  • it.each(...) / test.each(...) / @pytest.mark.parametrize / [Theory] + [InlineData] / @ParameterizedTest parametrization driven by data tables.
  • Pester -ForEach / -TestCases and RSpec where blocks.
  • Catch2 SECTIONs and GENERATE(...), doctest SUBCASE, GoogleTest INSTANTIATE_TEST_SUITE_P.

Smell 2: Mystery Guest

Tests that depend on external resources — files on disk, databases, network endpoints, environment variables — without making the dependency explicit or using test doubles.

Severity: High Detection: Test methods that read files, open database connections, make HTTP requests (without a test handler), read environment variables, or use hard-coded file paths. Per language: File.ReadAllText / Directory.GetFiles / HttpClient / Environment.GetEnvironmentVariable (.NET); open() / pathlib.Path.read_text() / requests.get() / os.environ[...] (Python); fs.readFileSync / fetch(...) / process.env.X (JS/TS); Files.readAllBytes / Files.newInputStream / HttpClient.send / System.getenv (Java); os.ReadFile / http.Get / os.Getenv (Go); File.read / Net::HTTP.get / ENV[...] (Ruby); std::fs::read_to_string / reqwest::get / std::env::var (Rust); String(contentsOfFile:) / URLSession.shared.data / ProcessInfo.processInfo.environment (Swift); File(...).readText() / URL(...).openConnection() / System.getenv (Kotlin); Get-Content / Invoke-WebRequest / $env:X (Pester); std::ifstream / curl_easy_perform / std::getenv (C++). Exception: In-memory fakes, test-specific handlers, or hermetic test data factories are fine.

Smell 3: Sleepy Test

Tests that call sleep or delay functions to wait for a condition. These introduce non-deterministic timing and slow down the suite.

Severity: High Detection: Calls to sleep/delay functions inside test methods: Thread.Sleep / Task.Delay (.NET); time.sleep / asyncio.sleep (Python); setTimeout / await new Promise(r => setTimeout(...)) / jest.advanceTimersByTime not paired with a wait (JS/TS); Thread.sleep / TimeUnit.SECONDS.sleep (Java); time.Sleep (Go); sleep / Kernel#sleep (Ruby); std::thread::sleep / tokio::time::sleep (Rust); Thread.sleep / delay (Kotlin coroutines); sleep(_:) / Task.sleep (Swift); Start-Sleep (Pester); std::this_thread::sleep_for (C++). See the matching language extension file for the full list.

Smell 4: Assertion-Free Test (Unknown Test)

Tests that execute code but never assert anything. Test frameworks report these as passing even if the code is completely broken, as long as no exception is thrown.

Severity: High Detection: A test method with no assertion calls and no expected-exception annotation. Framework-specific: missing Assert.* (.NET); no assert / pytest.raises (Python); no expect(...) or assert.* (JS/TS); no assert* / assertThat (Java); no t.Error* / t.Fatal* / assert.* testify (Go); no expect/.to/.eq (RSpec) or assert*/refute* (Minitest); no assert*! / assert_eq! / panic! (Rust); no XCTAssert* / #expect (Swift); no assert* / should* / Kotest matchers (Kotlin); no Should -* (Pester); no EXPECT_* / ASSERT_* / REQUIRE / CHECK (C++). Calibration:

  • A method named *_DoesNotThrow / *_no_exception / should not throw is implicitly asserting no exception — still flag it but note it may be intentional.
  • Mock-call verifications count as assertions: mock.Verify(...) (Moq), Mock.AssertWasCalled (NSubstitute), mock.assert_called_with(...) (Python), expect(mock).toHaveBeenCalledWith(...) (Jest), verify(mock).method(...) (Mockito), Should -Invoke (Pester) — do NOT flag tests using these as assertion-free.
  • Bare assertion forms count: assert x == y (pytest), if got != want { t.Errorf(...) } (Go), assert!(cond) (Rust) are canonical.
  • Snapshot assertions count: .toMatchSnapshot() (Jest), syrupy (pytest), SnapshotTesting (Swift), approval-tests are real assertions.
  • Missing await on async assertions is its own critical smell: expect(promise).resolves.toBe(x) without await/return (Jest), un-awaited Assert.ThrowsAsync (xUnit), un-awaited coroutines in pytest-asyncio, Kotest tests without runTest, Swift Testing async cases without await. These tests have assertion calls but silently pass — flag with a dedicated note.

Smell 5: Eager Test

A test method that calls many different production methods, making it unclear what behavior is being tested. When it fails, diagnosis is difficult because the failure could stem from any of the calls.

Severity: Medium Detection: A test method that calls 4+ distinct methods on the production object (excluding setup/construction). Count unique method names, not call count. Calibration: Integration / end-to-end / workflow tests may legitimately call multiple methods. Check for integration markers in the loaded language extension file (e.g., [Trait("Category", "Integration")], @Tag("integration"), pytest.mark.integration, *_integration_test.go, Describe ... -Tag 'Integration') and downgrade.

Smell 6: Magic Number Test

Assertions that contain unexplained numeric literals. The intent of Assert.AreEqual(42, result) / assert result == 42 / expect(result).toBe(42) is unclear without context — what does 42 represent?

Severity: Medium Detection: Numeric literals (other than 0, 1, -1, and the literal used in the test name) appearing as expected parameters in assertion methods or comparison operands. Calibration: Small integers in context (like count checks Assert.AreEqual(3, list.Count) / assert len(items) == 3 / expect(arr.length).toBe(3) where 3 items were just added) are acceptable — only flag when the number's meaning is genuinely unclear.

Smell 7: Sensitive Equality

Tests that use string conversion for comparison or assertion. If the underlying string representation changes, the test breaks even though the actual behavior is correct.

Severity: Medium Detection: Assert.AreEqual(expected, obj.ToString()) (.NET); assert str(obj) == "..." or assert repr(obj) == "..." (Python); expect(obj.toString()).toBe("...") or expect(${obj}).toBe(...) (JS/TS); assertEquals(expected, obj.toString()) (Java); assert.Equal(t, "...", fmt.Sprint(obj)) or obj.String() chains (Go); expect(obj.to_s).to eq("...") (RSpec); assert_eq!(format!("{}", obj), "...") or assert_eq!(format!("{:?}", obj), "...") (Rust); XCTAssertEqual(obj.description, "...") or string-interpolation assertion (Swift); assertEquals("...", obj.toString()) (Kotlin); Should -Be "..." against a [string]$obj (Pester); EXPECT_EQ("...", std::to_string(obj)) (C++).

Smell 8: Exception Handling in Tests

Tests that contain try/catch/except/rescue blocks or throw/raise/panic/return err statements used to manage exception flow instead of asserting on it. This typically means the test is manually managing errors rather than using the framework's built-in exception assertion facilities.

Severity: Medium Detection: try/catch (.NET, Java, JS/TS, Kotlin, Swift, C++); try/except (Python); begin/rescue (Ruby); defer recover() (Go); manual if err != nil { t.Fatal(err) } in Go is canonical and NOT a smell. Exception: catch/except/rescue blocks that capture an exception for further assertion on its properties are a lesser concern — note but don't flag as high severity.

Smell 9: General Fixture (Over-broad Setup)

The test setup method, constructor, or fixture initializes fields that are not used by every test method. This means each test pays the cost of setting up objects it doesn't need.

Severity: Low Detection: Fields/properties initialized in [TestInitialize] / setUp / @BeforeEach / beforeEach / before(:each) / BeforeEach (Pester) / setUpWithError (XCTest) / pytest fixture(autouse=True) / xUnit constructor / Kotest beforeTest that are referenced by fewer than half the test methods in the class/module/file.

Smell 10: Ignored / Disabled / Skipped Test

Tests marked as skipped or disabled. These add overhead and clutter, and the underlying issue they were disabled for may never be addressed.

Severity: Low Detection: Skip / ignore / disable annotations or conditional compilation that disables a test. See the loaded language extension file for framework-specific skip attributes — e.g., [Ignore] (MSTest/NUnit), Skip = "..." (xUnit Fact), @Ignore (TUnit/JUnit 4), @Disabled (JUnit 5), @pytest.mark.skip / pytest.skip(...) / pytestmark, it.skip / xit / describe.skip / test.skip (Jest/Vitest/Mocha), t.Skip(...) (Go), pending / skip / xit (RSpec), #[ignore] (Rust), XCTSkip / @Test(.disabled) (Swift), @Ignored (Kotest), -Skip (Pester), GTEST_SKIP() / DISABLED_TestName (GoogleTest), [.] tag (Catch2), TEST_CASE("...", "[.]") skip.

Step 4: Apply calibration rules

Before reporting, calibrate findings to avoid false positives:

  • Integration tests have different norms. A test class clearly marked as integration (by name, annotation, category, or convention — see the loaded language extension file for markers) legitimately uses external resources, calls multiple methods, and may use delays for async coordination. Downgrade Mystery Guest, Eager Test, and Sleepy Test severity for integration tests — note them but don't flag as problems.
  • Simple loop-assert patterns are fine. Iterating a collection to assert on every item is readable and correct. Only flag loops with complex branching logic.
  • Idiomatic table-driven and parametrized patterns are NOT Conditional Test Logic. Go's for _, tt := range tests { t.Run(...) }, Rust's #[rstest], pytest's @parametrize, Jest/Vitest .each, JUnit @ParameterizedTest, RSpec where, Pester -ForEach, Catch2 SECTION/GENERATE, GoogleTest INSTANTIATE_TEST_SUITE_P are canonical and must NOT be flagged.
  • Context matters for magic numbers. A count assertion right after adding a known number of items is self-documenting. Only flag numbers whose meaning requires looking at production code to understand.
  • Bare assert (pytest) is canonical, not assertion-free framework use. Don't flag.
  • Go's if err != nil { t.Fatal(err) } is canonical, not Exception Handling in Tests. Don't flag.
  • Mock-call verifications and snapshot assertions are real assertions — do not flag tests using them as Assertion-Free.
  • Missing-await on async assertions is its own critical sub-smell of Assertion-Free — these tests silently pass even when the underlying assertion fails. Always flag when detected.
  • Inconclusive/pending markers are not assertion-free. Tests explicitly marked as incomplete should be flagged as Ignored Test, not Assertion-Free.
  • Capture-and-assert exception patterns are borderline. try { ... } catch (X x) { Assert.Equal(...) } шаблоны стиля некрасивы, но функциональны. Отметьте как запашок и предложите встроенную проверку исключений фреймворка (Assert.Throws<T>, pytest.raises, expect(fn).toThrow, assertThrows, assert.PanicsWithError, и т. д.) вместо того, чтобы называть это сломанным.
  • Если набор тестов чистый, так и скажите. Отчёт, в котором найдено мало запашков или они не найдены вовсе, вполне допустим.

Шаг 5: Сообщите о находках

Представьте анализ в следующей структуре:

  1. Сводная панель — Краткий обзор:

    | Severity | Smell Count | Affected Tests |
    |----------|-------------|----------------|
    | High     | 3           | 7              |
    | Medium   | 2           | 4              |
    | Low      | 1           | 2              |
    | Total    | 6           | 13             |
    
  2. Находки по степени серьёзности — Для каждого найденного запашка:

    • Название запашка и категория
    • Уровень серьёзности с обоснованием
    • Затронутые тестовые методы (файл и имя метода)
    • Фрагмент кода, показывающий запашок
    • Конкретное исправление: покажите, как должен выглядеть код после устранения
    • Риск, если оставить без исправления
  3. Шаблоны без запашков — Если какие-либо тестовые методы написаны хорошо, кратко отметьте это. Подчёркивание того, что хорошо, помогает пользователю понять контраст.

  4. Приоритизированный план устранения — Ранжируйте исправления по:

    • Влияние (сначала запашки высокой серьёзности, затрагивающие множество тестов)
    • Трудоёмкость (быстрые исправления перед рефакторингом)
    • Риск (исправления, предотвращающие ложные прохождения, перед косметическими улучшениями)

Валидация

  • <!-- -->Каждая находка включает конкретное имя тестового метода и местоположение файла
  • <!-- -->Каждая находка включает фрагмент кода, показывающий запашок в контексте
  • <!-- -->Каждая находка включает конкретный пример исправления (а не просто «исправьте это»)
  • <!-- -->Интеграционные тесты не штрафуются за шаблоны, уместные для их области охвата
  • <!-- -->Простые циклы foreach-assert не помечаются как условная логика теста
  • <!-- -->Контекстуально очевидные числа не помечаются как магические числа
  • <!-- -->Если набор тестов чистый, отчёт сообщает об этом в начале
  • <!-- -->Уровни серьёзности обоснованы, а не произвольны

Распространённые ошибки

ОшибкаРешение
Пометка интеграционных тестов за использование реальных ресурсовПроверьте маркеры интеграционных тестов (согласно загруженному расширению языка) и скорректируйте серьёзность соответствующим образом
Пометка цикла по коллекции с assert как условной логикиПомечайте только циклы с ветвлением или сложной логикой, а не итерации с проверками
Пометка табличных циклов Go/Rust как условной логики тестаfor _, tt := range tests { t.Run(...) } (Go) и #[rstest] циклы (Rust) каноничны и НЕ должны помечаться
Пометка параметризованных тестов как дублирующего assert@pytest.mark.parametrize, it.each, [Theory]+[InlineData], @ParameterizedTest, RSpec where, Pester -ForEach, Catch2 SECTION/GENERATE являются правильной дедупликацией, а не запашками
Пометка голого pytest assert как отсутствующего фреймворкаГолый assert — канонический assert pytest — учитывайте его
Пометка Go if err != nil { t.Fatal(err) } как обработки исключений в тестахЭто каноническая проверка ошибок Go — НЕ помечайте
Пометка очевидных проверок количества после добавления N элементовУчитывайте непосредственный контекст — самодокументируемые числа допустимы
Отсутствие синтаксиса assert, специфичного для фреймворкаВсегда сначала читайте соответствующий файл расширения языка; у каждого фреймворка свои API assert (xUnit Assert.Equal, MSTest Assert.AreEqual, NUnit Is.EqualTo, голый pytest assert, Jest expect().toBe(), и т. д.)
Рассмотрение проверок вызовов моков как тестов без assertmock.Verify(...), expect(mock).toHaveBeenCalledWith(...), Should -Invoke, verify(mock).method(...), mock.assert_called_with(...) являются настоящими проверками
Пропуск ловушки тихого прохождения асинхронных тестовВсегда помечайте expect(promise).resolves.toBe(x) без await/return, не ожидаемые Assert.ThrowsAsync (xUnit), не ожидаемые корутины в pytest-asyncio, отсутствующий runTest в Kotest, не ожидаемые асинхронные проверки Swift Testing
Избыточная пометка try/catch, который захватывает для проверкиРазличайте проглоченные исключения и шаблоны захвата с проверкой
Рассмотрение аннотаций пропуска с причинами так же, как голых пропусковОтметьте, что пропуски с причинами (Skip = "Tracked by #123", @pytest.mark.skip(reason="..."), t.Skip("not yet implemented")) менее тревожны, чем необъяснённые
Пометка тестов в стиле DoesNotThrowкак тестов без assertОни неявно проверяют отсутствие исключения — отметьте, но признайте намерение

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: exp-test-smell-detection](https://darkplay.ru/ai/skills/dotnet-skills-exp-test-smell-detection)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

E2e Runneraffaan-m · Специалист по E2E-тестам на Vercel Agent Browser и Playwright: генерация, запуск и…
225 587 ★
Fastapi Revieweraffaan-m · Проверяет FastAPI-приложения: async, DI, Pydantic, безопасность, OpenAPI и тесты.
225 587 ★
Gan Evaluatoraffaan-m · GAN Harness — агент-оценщик: тестирует приложение через Playwright и даёт обратную связь.
225 587 ★
Pr Test Analyzeraffaan-m · Оценивает качество и полноту покрытия тестами в pull request.
225 587 ★
Security Revieweraffaan-m · Ищет и устраняет уязвимости: секреты, SSRF, инъекции, крипто и OWASP Top 10.
225 587 ★
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
225 587 ★
Tdd Guideaffaan-m · Специалист по TDD: сначала тесты, покрытие 80%+.
225 587 ★
example-skillsanthropics · Набор примеров навыков, демонстрирующих разные возможности: создание навыков, разработку…
17 комп.
pr-review-toolkitanthropics · Комплексные агенты для ревью PR, специализирующиеся на комментариях, тестах, обработке…
34 комп.
impeccablepbakaus · Дизайнерская беглость для фронтенд-разработки. 1 навык с 23 командами (/impeccable…
3 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8