Langsung ke konten
Skillpedia
Testing48k · #6057

unit-testing-test-generate

Fungsinya

Alat ini membuat tes otomatis untuk kode Anda. Alat menganalisis kode yang Anda berikan lalu membuat tes yang memeriksa apakah kode tersebut bekerja dengan benar, termasuk pada situasi yang tidak biasa.

Kapan dipakai

  • ✓Saat kode Anda sudah selesai dan ingin memastikan kode tersebut berfungsi.
  • ✓Saat Anda ingin pembuatan tes untuk kode Anda dilakukan secara konsisten.
  • ✓Saat Anda perlu menguji skenario tertentu dan kasus-kasus langka.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/unit-testing-test-generate/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Buatkan unit test untuk fungsi Python ini yang menghitung rata-rata dari sebuah daftar angka.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Alat membaca kode Anda, mengidentifikasi bagian-bagian yang perlu diuji, lalu membuat file tes. Alat menggunakan berbagai teknik agar tes mencakup sebanyak mungkin kode dan memeriksa kesalahan.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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):")

…
Pertanyaan umum

Apa itu unit test?

Unit test adalah tes kecil yang memeriksa apakah bagian tertentu dari kode (seperti sebuah fungsi) bekerja sesuai harapan, secara terpisah dari bagian lainnya.

Mengapa menggunakan alat ini?

Alat ini menghemat waktu dan memastikan tes yang dibuat menyeluruh serta konsisten, sehingga membantu menemukan bug lebih awal.

Apakah alat ini bisa dipakai untuk bahasa pemrograman apa pun?

Alat ini mendukung beberapa bahasa populer seperti Python, JavaScript, TypeScript, Java, dan Go.

Detail

Deskripsi asli dari pembuat

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

repo: sickn33/agentic-awesome-skills

Popularitas

Bintang GitHub
48k
Peringkat
#6057
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa