본문으로 건너뛰기
Skillpedia
테스트48k · #6057

unit-testing-test-generate

하는 일

코드를 위한 자동 테스트를 만드는 도구입니다. 사용자가 제공한 코드를 분석하고, 특이한 상황을 포함해 올바르게 작동하는지 확인하는 테스트를 생성합니다.

사용하는 경우

  • ✓코드 작성을 마치고 제대로 작동하는지 확인하고 싶을 때.
  • ✓코드의 테스트를 일관되게 하고 싶을 때.
  • ✓특정 시나리오와 드문 경우를 테스트해야 할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/unit-testing-test-generate/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/unit-testing-test-generate/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“리스트 숫자들의 평균을 계산하는 이 Python 함수의 단위 테스트를 만들어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 도구는 코드를 읽고 테스트가 필요한 부분을 찾아 테스트 파일을 만듭니다. 가능한 한 많은 코드를 다루도록 하고 오류를 확인하는 기법을 사용합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Automated Unit Test Generation

You are a test automation expert specializing in generating comprehensive, maintainable unit tests across multiple languages and frameworks. Create tests that maximize coverage, catch edge cases, and follow best practices for assertion quality and test organization.

Use this skill when

  • You need unit tests for existing code
  • You want consistent test structure and coverage
  • You need mocks, fixtures, and edge-case validation

Do not use this skill when

  • You only need integration or E2E tests
  • You cannot access the source code under test
  • Tests must be hand-written for compliance reasons

Context

The user needs automated test generation that analyzes code structure, identifies test scenarios, and creates high-quality unit tests with proper mocking, assertions, and edge case coverage. Focus on framework-specific patterns and maintainable test suites.

Requirements

$ARGUMENTS

Instructions

1. Analyze Code for Test Generation

Scan codebase to identify untested code and generate comprehensive test suites:

import ast
from pathlib import Path
from typing import Dict, List, Any

class TestGenerator:
    def __init__(self, language: str):
        self.language = language
        self.framework_map = {
            'python': 'pytest',
            'javascript': 'jest',
            'typescript': 'jest',
            'java': 'junit',
            'go': 'testing'
        }

    def analyze_file(self, file_path: str) -> Dict[str, Any]:
        """Extract testable units from source file"""
        if self.language == 'python':
            return self._analyze_python(file_path)
        elif self.language in ['javascript', 'typescript']:
            return self._analyze_javascript(file_path)

    def _analyze_python(self, file_path: str) -> Dict:
        with open(file_path) as f:
            tree = ast.parse(f.read())

        functions = []
        classes = []

        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                functions.append({
                    'name': node.name,
                    'args': [arg.arg for arg in node.args.args],
                    'returns': ast.unparse(node.returns) if node.returns else None,
                    'decorators': [ast.unparse(d) for d in node.decorator_list],
                    'docstring': ast.get_docstring(node),
                    'complexity': self._calculate_complexity(node)
                })
            elif isinstance(node, ast.ClassDef):
                methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
                classes.append({
                    'name': node.name,
                    'methods': methods,
                    'bases': [ast.unparse(base) for base in node.bases]
                })

        return {'functions': functions, 'classes': classes, 'file': file_path}

2. Generate Python Tests with pytest

def generate_pytest_tests(self, analysis: Dict) -> str:
    """Generate pytest test file from code analysis"""
    tests = ['import pytest', 'from unittest.mock import Mock, patch', '']

    module_name = Path(analysis['file']).stem
    tests.append(f"from {module_name} import *\n")

    for func in analysis['functions']:
        if func['name'].startswith('_'):
            continue

        test_class = self._generate_function_tests(func)
        tests.append(test_class)

    for cls in analysis['classes']:
        test_class = self._generate_class_tests(cls)
        tests.append(test_class)

    return '\n'.join(tests)

def _generate_function_tests(self, func: Dict) -> str:
    """Generate test cases for a function"""
    func_name = func['name']
    tests = [f"\n\nclass Test{func_name.title()}:"]

    # Happy path test
    tests.append(f"    def test_{func_name}_success(self):")
    tests.append(f"        result = {func_name}({self._generate_mock_args(func['args'])})")
    tests.append(f"        assert result is not None\n")

    # Edge case tests
    if len(func['args']) > 0:
        tests.append(f"    def test_{func_name}_with_empty_input(self):")
        tests.append(f"        with pytest.raises((ValueError, TypeError)):")
        tests.append(f"            {func_name}({self._generate_empty_args(func['args'])})\n")

    # Exception handling test
    tests.append(f"    def test_{func_name}_handles_errors(self):")
    tests.append(f"        with pytest.raises(Exception):")

…
자주 묻는 질문

단위 테스트란 무엇인가요?

함수 같은 특정 코드 부분이 독립적으로 기대대로 작동하는지 확인하는 작은 테스트입니다.

이 도구를 왜 써야 하나요?

시간을 절약하고, 테스트가 포괄적이고 일관되도록 보장해 버그를 더 일찍 찾는 데 도움이 됩니다.

모든 프로그래밍 언어에서 쓸 수 있나요?

이 도구는 Python, JavaScript, TypeScript, Java, Go 같은 여러 인기 언어를 지원합니다.

상세 정보

작성자의 원본 설명

Generate comprehensive, maintainable unit tests across languages with strong coverage and edge case focus.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#6057
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬