{"id":"c70ebdee-d08c-4b0c-8bba-35b5134c2772","shortId":"vJS5g5","kind":"skill","title":"unit-testing-test-generate","tagline":"Generate comprehensive, maintainable unit tests across languages with strong coverage and edge case focus.","description":"# Automated Unit Test Generation\n\nYou 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.\n\n## Use this skill when\n\n- You need unit tests for existing code\n- You want consistent test structure and coverage\n- You need mocks, fixtures, and edge-case validation\n\n## Do not use this skill when\n\n- You only need integration or E2E tests\n- You cannot access the source code under test\n- Tests must be hand-written for compliance reasons\n\n## Context\n\nThe 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.\n\n## Requirements\n\n$ARGUMENTS\n\n## Instructions\n\n### 1. Analyze Code for Test Generation\n\nScan codebase to identify untested code and generate comprehensive test suites:\n\n```python\nimport ast\nfrom pathlib import Path\nfrom typing import Dict, List, Any\n\nclass TestGenerator:\n    def __init__(self, language: str):\n        self.language = language\n        self.framework_map = {\n            'python': 'pytest',\n            'javascript': 'jest',\n            'typescript': 'jest',\n            'java': 'junit',\n            'go': 'testing'\n        }\n\n    def analyze_file(self, file_path: str) -> Dict[str, Any]:\n        \"\"\"Extract testable units from source file\"\"\"\n        if self.language == 'python':\n            return self._analyze_python(file_path)\n        elif self.language in ['javascript', 'typescript']:\n            return self._analyze_javascript(file_path)\n\n    def _analyze_python(self, file_path: str) -> Dict:\n        with open(file_path) as f:\n            tree = ast.parse(f.read())\n\n        functions = []\n        classes = []\n\n        for node in ast.walk(tree):\n            if isinstance(node, ast.FunctionDef):\n                functions.append({\n                    'name': node.name,\n                    'args': [arg.arg for arg in node.args.args],\n                    'returns': ast.unparse(node.returns) if node.returns else None,\n                    'decorators': [ast.unparse(d) for d in node.decorator_list],\n                    'docstring': ast.get_docstring(node),\n                    'complexity': self._calculate_complexity(node)\n                })\n            elif isinstance(node, ast.ClassDef):\n                methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]\n                classes.append({\n                    'name': node.name,\n                    'methods': methods,\n                    'bases': [ast.unparse(base) for base in node.bases]\n                })\n\n        return {'functions': functions, 'classes': classes, 'file': file_path}\n```\n\n### 2. Generate Python Tests with pytest\n\n```python\ndef generate_pytest_tests(self, analysis: Dict) -> str:\n    \"\"\"Generate pytest test file from code analysis\"\"\"\n    tests = ['import pytest', 'from unittest.mock import Mock, patch', '']\n\n    module_name = Path(analysis['file']).stem\n    tests.append(f\"from {module_name} import *\\n\")\n\n    for func in analysis['functions']:\n        if func['name'].startswith('_'):\n            continue\n\n        test_class = self._generate_function_tests(func)\n        tests.append(test_class)\n\n    for cls in analysis['classes']:\n        test_class = self._generate_class_tests(cls)\n        tests.append(test_class)\n\n    return '\\n'.join(tests)\n\ndef _generate_function_tests(self, func: Dict) -> str:\n    \"\"\"Generate test cases for a function\"\"\"\n    func_name = func['name']\n    tests = [f\"\\n\\nclass Test{func_name.title()}:\"]\n\n    # Happy path test\n    tests.append(f\"    def test_{func_name}_success(self):\")\n    tests.append(f\"        result = {func_name}({self._generate_mock_args(func['args'])})\")\n    tests.append(f\"        assert result is not None\\n\")\n\n    # Edge case tests\n    if len(func['args']) > 0:\n        tests.append(f\"    def test_{func_name}_with_empty_input(self):\")\n        tests.append(f\"        with pytest.raises((ValueError, TypeError)):\")\n        tests.append(f\"            {func_name}({self._generate_empty_args(func['args'])})\\n\")\n\n    # Exception handling test\n    tests.append(f\"    def test_{func_name}_handles_errors(self):\")\n    tests.append(f\"        with pytest.raises(Exception):\")\n    tests.append(f\"            {func_name}({self._generate_invalid_args(func['args'])})\\n\")\n\n    return '\\n'.join(tests)\n\ndef _generate_class_tests(self, cls: Dict) -> str:\n    \"\"\"Generate test cases for a class\"\"\"\n    tests = [f\"\\n\\nclass Test{cls['name']}:\"]\n    tests.append(f\"    @pytest.fixture\")\n    tests.append(f\"    def instance(self):\")\n    tests.append(f\"        return {cls['name']}()\\n\")\n\n    for method in cls['methods']:\n        if method.startswith('_') and method != '__init__':\n            continue\n\n        tests.append(f\"    def test_{method}(self, instance):\")\n        tests.append(f\"        result = instance.{method}()\")\n        tests.append(f\"        assert result is not None\\n\")\n\n    return '\\n'.join(tests)\n```\n\n### 3. Generate JavaScript/TypeScript Tests with Jest\n\n```typescript\ninterface TestCase {\n  name: string;\n  setup?: string;\n  execution: string;\n  assertions: string[];\n}\n\nclass JestTestGenerator {\n  generateTests(functionName: string, params: string[]): string {\n    const tests: TestCase[] = [\n      {\n        name: `${functionName} returns expected result with valid input`,\n        execution: `const result = ${functionName}(${this.generateMockParams(params)})`,\n        assertions: ['expect(result).toBeDefined()', 'expect(result).not.toBeNull()']\n      },\n      {\n        name: `${functionName} handles null input gracefully`,\n        execution: `const result = ${functionName}(null)`,\n        assertions: ['expect(result).toBeDefined()']\n      },\n      {\n        name: `${functionName} throws error for invalid input`,\n        execution: `() => ${functionName}(undefined)`,\n        assertions: ['expect(execution).toThrow()']\n      }\n    ];\n\n    return this.formatJestSuite(functionName, tests);\n  }\n\n  formatJestSuite(name: string, cases: TestCase[]): string {\n    let output = `describe('${name}', () => {\\n`;\n\n    for (const testCase of cases) {\n      output += `  it('${testCase.name}', () => {\\n`;\n      if (testCase.setup) {\n        output += `    ${testCase.setup}\\n`;\n      }\n      output += `    const execution = ${testCase.execution};\\n`;\n      for (const assertion of testCase.assertions) {\n        output += `    ${assertion};\\n`;\n      }\n      output += `  });\\n\\n`;\n    }\n\n    output += '});\\n';\n    return output;\n  }\n\n  generateMockParams(params: string[]): string {\n    return params.map(p => `mock${p.charAt(0).toUpperCase() + p.slice(1)}`).join(', ');\n  }\n}\n```\n\n### 4. Generate React Component Tests\n\n```typescript\nfunction generateReactComponentTest(componentName: string): string {\n  return `\nimport { render, screen, fireEvent } from '@testing-library/react';\nimport { ${componentName} } from './${componentName}';\n\ndescribe('${componentName}', () => {\n  it('renders without crashing', () => {\n    render(<${componentName} />);\n    expect(screen.getByRole('main')).toBeInTheDocument();\n  });\n\n  it('displays correct initial state', () => {\n    render(<${componentName} />);\n    const element = screen.getByTestId('${componentName.toLowerCase()}');\n    expect(element).toBeVisible();\n  });\n\n  it('handles user interaction', () => {\n    render(<${componentName} />);\n    const button = screen.getByRole('button');\n    fireEvent.click(button);\n    expect(screen.getByText(/clicked/i)).toBeInTheDocument();\n  });\n\n  it('updates props correctly', () => {\n    const { rerender } = render(<${componentName} value=\"initial\" />);\n    expect(screen.getByText('initial')).toBeInTheDocument();\n\n    rerender(<${componentName} value=\"updated\" />);\n    expect(screen.getByText('updated')).toBeInTheDocument();\n  });\n});\n`;\n}\n```\n\n### 5. Coverage Analysis and Gap Detection\n\n```python\nimport subprocess\nimport json\n\nclass CoverageAnalyzer:\n    def analyze_coverage(self, test_command: str) -> Dict:\n        \"\"\"Run tests with coverage and identify gaps\"\"\"\n        result = subprocess.run(\n            [test_command, '--coverage', '--json'],\n            capture_output=True,\n            text=True\n        )\n\n        coverage_data = json.loads(result.stdout)\n        gaps = self.identify_coverage_gaps(coverage_data)\n\n        return {\n            'overall_coverage': coverage_data.get('totals', {}).get('percent_covered', 0),\n            'uncovered_lines': gaps,\n            'files_below_threshold': self.find_low_coverage_files(coverage_data, 80)\n        }\n\n    def identify_coverage_gaps(self, coverage: Dict) -> List[Dict]:\n        \"\"\"Find specific lines/functions without test coverage\"\"\"\n        gaps = []\n        for file_path, data in coverage.get('files', {}).items():\n            missing_lines = data.get('missing_lines', [])\n            if missing_lines:\n                gaps.append({\n                    'file': file_path,\n                    'lines': missing_lines,\n                    'functions': data.get('excluded_lines', [])\n                })\n        return gaps\n\n    def generate_tests_for_gaps(self, gaps: List[Dict]) -> str:\n        \"\"\"Generate tests specifically for uncovered code\"\"\"\n        tests = []\n        for gap in gaps:\n            test_code = self.create_targeted_test(gap)\n            tests.append(test_code)\n        return '\\n\\n'.join(tests)\n```\n\n### 6. Mock Generation\n\n```python\ndef generate_mock_objects(self, dependencies: List[str]) -> str:\n    \"\"\"Generate mock objects for external dependencies\"\"\"\n    mocks = ['from unittest.mock import Mock, MagicMock, patch\\n']\n\n    for dep in dependencies:\n        mocks.append(f\"@pytest.fixture\")\n        mocks.append(f\"def mock_{dep}():\")\n        mocks.append(f\"    mock = Mock(spec={dep})\")\n        mocks.append(f\"    mock.method.return_value = 'mocked_result'\")\n        mocks.append(f\"    return mock\\n\")\n\n    return '\\n'.join(mocks)\n```\n\n## Output Format\n\n1. **Test Files**: Complete test suites ready to run\n2. **Coverage Report**: Current coverage with gaps identified\n3. **Mock Objects**: Fixtures for external dependencies\n4. **Test Documentation**: Explanation of test scenarios\n5. **CI Integration**: Commands to run tests in pipeline\n\nFocus on generating maintainable, comprehensive tests that catch bugs early and provide confidence in code changes.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.","tags":["unit","testing","test","generate","antigravity","awesome","skills","sickn33","agent-skills","agentic-skills","ai-agent-skills","ai-agents"],"capabilities":["skill","source-sickn33","skill-unit-testing-test-generate","topic-agent-skills","topic-agentic-skills","topic-ai-agent-skills","topic-ai-agents","topic-ai-coding","topic-ai-workflows","topic-antigravity","topic-antigravity-skills","topic-claude-code","topic-claude-code-skills","topic-codex-cli","topic-codex-skills"],"categories":["antigravity-awesome-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/sickn33/antigravity-awesome-skills/unit-testing-test-generate","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add sickn33/antigravity-awesome-skills","source_repo":"https://github.com/sickn33/antigravity-awesome-skills","install_from":"skills.sh"}},"qualityScore":"0.700","qualityRationale":"deterministic score 0.70 from registry signals: · indexed on github topic:agent-skills · 34460 github stars · SKILL.md body (10,875 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-04-22T06:52:05.110Z","embedding":null,"createdAt":"2026-04-18T21:46:50.307Z","updatedAt":"2026-04-22T06:52:05.110Z","lastSeenAt":"2026-04-22T06:52:05.110Z","tsv":"'/clicked/i':799 '/react':754 '0':469,729,880 '1':159,732,1036 '2':335,1045 '3':593,1053 '4':734,1060 '5':823,1067 '6':974 '80':893 'access':102 'across':11,37 'analysi':347,356,368,381,398,825 'analyz':125,160,211,243,837 'arg':273,276,453,468,492,517 'arg.arg':274 'argument':157 'ask':1125 'assert':55,141,456,583,608,635,653,667,707,711 'ast':178 'ast.classdef':304 'ast.functiondef':269,314 'ast.get':295 'ast.parse':257 'ast.unparse':280,287,321 'ast.walk':264 'autom':20,28,121 'base':320,322,324 'best':52 'boundari':1133 'bug':1084 'button':792,794,796 'cannot':101 'captur':857 'case':18,49,85,144,421,463,533,678,690 'catch':47,1083 'chang':1091 'ci':1068 'clarif':1127 'class':189,260,330,331,389,394,399,401,406,525,536,610,834 'classes.append':315 'clear':1100 'cls':396,403,528,542,555,561 'code':70,105,126,161,170,355,954,961,968,1090 'codebas':166 'command':841,854,1070 'complet':1039 'complex':298 'complianc':115 'compon':737 'componentnam':742,756,758,760,766,777,790,808,816 'componentname.tolowercase':781 'comprehens':7,33,173,1080 'confid':1088 'consist':73 'const':618,630,649,687,701,706,778,791,805 'context':117 'continu':387,568 'correct':773,804 'cover':879 'coverag':15,46,77,145,824,838,847,855,862,868,870,874,889,891,896,899,908,1046,1049 'coverage.get':915 'coverage_data.get':875 'coverageanalyz':835 'crash':764 'creat':42,132 'criteria':1136 'current':1048 'd':288,290 'data':863,871,892,913 'data.get':920,934 'decor':286 'def':191,210,242,342,411,440,472,499,523,549,571,836,894,939,978,1010 'dep':1002,1012,1018 'depend':983,992,1004,1059 'describ':683,759,1104 'detect':828 'dict':186,217,249,348,417,529,843,900,902,947 'display':772 'docstr':294,296 'document':1062 'e2e':98 'earli':1085 'edg':17,48,84,143,462 'edge-cas':83 'element':779,783 'elif':233,301 'els':284 'empti':477 'environ':1116 'environment-specif':1115 'error':504,660 'except':494,510 'exclud':935 'execut':606,629,648,664,669,702 'exist':69 'expect':624,636,639,654,668,767,782,797,811,819 'expert':29,1121 'explan':1063 'extern':991,1058 'extract':220 'f':255,372,430,439,447,455,471,481,487,498,507,512,538,545,548,553,570,577,582,1006,1009,1014,1020,1026 'f.read':258 'file':212,214,225,231,240,246,252,332,333,353,369,884,890,911,916,927,928,1038 'find':903 'fireev':749 'fireevent.click':795 'fixtur':81,1056 'focus':19,146,1076 'follow':51 'format':1035 'formatjestsuit':675 'framework':41,149 'framework-specif':148 'func':379,384,391,416,425,427,442,449,452,467,474,488,491,501,513,516 'func_name.title':434 'function':259,328,329,382,413,424,740,933 'functionnam':613,622,632,643,651,658,665,673 'functions.append':270 'gap':827,850,866,869,883,897,909,938,943,945,957,959,965,1051 'gaps.append':926 'generat':5,6,23,32,123,164,172,336,343,350,412,419,524,531,594,735,940,949,976,979,987,1078 'generatemockparam':720 'generatereactcomponenttest':741 'generatetest':612 'get':877 'go':208 'grace':647 'hand':112 'hand-written':111 'handl':495,503,644,786 'happi':435 'high':134 'high-qual':133 'identifi':128,168,849,895,1052 'import':177,181,185,358,362,376,746,755,830,832,996 'init':192,567 'initi':774,810,813 'input':478,628,646,663,1130 'instanc':550,575,579 'instruct':158 'integr':96,1069 'interact':788 'interfac':600 'invalid':662 'isinst':267,302,312 'item':917 'java':206 'javascript':202,236 'javascript/typescript':595 'jest':203,205,598 'jesttestgener':611 'join':409,521,591,733,972,1032 'json':833,856 'json.loads':864 'junit':207 'languag':12,39,194,197 'len':466 'let':681 'librari':753 'limit':1092 'line':882,919,922,925,930,932,936 'lines/functions':905 'list':187,293,901,946,984 'low':888 'magicmock':998 'main':769 'maintain':8,34,153,1079 'map':199 'match':1101 'maxim':45 'method':305,318,319,559,562,566,573,580 'method.startswith':564 'miss':918,921,924,931,1138 'mock':80,140,363,727,975,980,988,993,997,1011,1015,1016,1023,1028,1033,1054 'mock.method.return':1021 'mocks.append':1005,1008,1013,1019,1025 'modul':365,374 'multipl':38 'must':109 'n':308,313,377,408,431,461,493,518,520,539,557,588,590,685,694,699,704,712,714,715,717,970,971,1000,1029,1031 'n.name':306 'name':271,316,366,375,385,426,428,443,450,475,489,502,514,543,556,602,621,642,657,676,684 'nclass':432,540 'need':65,79,95,120 'node':262,268,297,300,303 'node.args.args':278 'node.bases':326 'node.body':310 'node.decorator':292 'node.name':272,317 'node.returns':281,283 'none':285,460,587 'not.tobenull':641 'null':645,652 'object':981,989,1055 'open':251 'organ':59 'output':682,691,697,700,710,713,716,719,858,1034,1110 'overal':873 'p':726 'p.charat':728 'p.slice':731 'param':615,634,721 'params.map':725 'patch':364,999 'path':182,215,232,241,247,253,334,367,436,912,929 'pathlib':180 'pattern':151 'percent':878 'permiss':1131 'pipelin':1075 'practic':53 'prop':803 'proper':139 'provid':1087 'pytest':201,340,344,351,359 'pytest.fixture':546,1007 'pytest.raises':483,509 'python':176,200,228,244,337,341,829,977 'qualiti':56,135 'react':736 'readi':1042 'reason':116 'render':747,762,765,776,789,807 'report':1047 'requir':156,1129 'rerend':806,815 'result':448,457,578,584,625,631,637,640,650,655,851,1024 'result.stdout':865 'return':229,238,279,327,407,519,554,589,623,671,718,724,745,872,937,969,1027,1030 'review':1122 'run':844,1044,1072 'safeti':1132 'scan':165 'scenario':130,1066 'scope':1103 'screen':748 'screen.getbyrole':768,793 'screen.getbytestid':780 'screen.getbytext':798,812,820 'self':193,213,245,346,415,445,479,505,527,551,574,839,898,944,982 'self._analyze_javascript':239 'self._analyze_python':230 'self._calculate_complexity':299 'self._generate_class_tests':402 'self._generate_empty_args':490 'self._generate_function_tests':390 'self._generate_invalid_args':515 'self._generate_mock_args':451 'self.create':962 'self.find':887 'self.framework':198 'self.identify':867 'self.language':196,227,234 'setup':604 'skill':62,91,1095 'skill-unit-testing-test-generate' 'sourc':104,224 'source-sickn33' 'spec':1017 'special':30 'specif':150,904,951,1117 'startswith':386 'state':775 'stem':370 'stop':1123 'str':195,216,218,248,349,418,530,842,948,985,986 'string':603,605,607,609,614,616,617,677,680,722,723,743,744 'strong':14 'structur':75,127 'subprocess':831 'subprocess.run':852 'substitut':1113 'success':444,1135 'suit':155,175,1041 'target':963 'task':1099 'test':3,4,10,22,27,36,43,58,67,74,99,107,108,122,129,137,154,163,174,209,338,345,352,357,388,393,400,405,410,414,420,429,433,437,441,464,473,496,500,522,526,532,537,541,572,592,596,619,674,738,752,840,845,853,907,941,950,955,960,964,967,973,1037,1040,1061,1065,1073,1081,1119 'testabl':221 'testcas':601,620,679,688 'testcase.assertions':709 'testcase.execution':703 'testcase.name':693 'testcase.setup':696,698 'testgener':190 'testing-librari':751 'tests.append':371,392,404,438,446,454,470,480,486,497,506,511,544,547,552,569,576,581,966 'text':860 'this.formatjestsuite':672 'this.generatemockparams':633 'threshold':886 'throw':659 'tobedefin':638,656 'tobeinthedocu':770,800,814,822 'tobevis':784 'topic-agent-skills' 'topic-agentic-skills' 'topic-ai-agent-skills' 'topic-ai-agents' 'topic-ai-coding' 'topic-ai-workflows' 'topic-antigravity' 'topic-antigravity-skills' 'topic-claude-code' 'topic-claude-code-skills' 'topic-codex-cli' 'topic-codex-skills' 'total':876 'tothrow':670 'touppercas':730 'treat':1108 'tree':256,265 'true':859,861 'type':184 'typeerror':485 'typescript':204,237,599,739 'uncov':881,953 'undefin':666 'unit':2,9,21,35,66,136,222 'unit-testing-test-gener':1 'unittest.mock':361,995 'untest':169 'updat':802,818,821 'use':60,89,1093 'user':119,787 'valid':86,627,1118 'valu':809,817,1022 'valueerror':484 'want':72 'without':763,906 'written':113","prices":[{"id":"d5ab2a0f-b612-4a8c-82f3-9ecae2028881","listingId":"c70ebdee-d08c-4b0c-8bba-35b5134c2772","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"sickn33","category":"antigravity-awesome-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T21:46:50.307Z"}],"sources":[{"listingId":"c70ebdee-d08c-4b0c-8bba-35b5134c2772","source":"github","sourceId":"sickn33/antigravity-awesome-skills/unit-testing-test-generate","sourceUrl":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/unit-testing-test-generate","isPrimary":false,"firstSeenAt":"2026-04-18T21:46:50.307Z","lastSeenAt":"2026-04-22T06:52:05.110Z"}],"details":{"listingId":"c70ebdee-d08c-4b0c-8bba-35b5134c2772","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"sickn33","slug":"unit-testing-test-generate","github":{"repo":"sickn33/antigravity-awesome-skills","stars":34460,"topics":["agent-skills","agentic-skills","ai-agent-skills","ai-agents","ai-coding","ai-workflows","antigravity","antigravity-skills","claude-code","claude-code-skills","codex-cli","codex-skills","cursor","cursor-skills","developer-tools","gemini-cli","gemini-skills","kiro","mcp","skill-library"],"license":"mit","html_url":"https://github.com/sickn33/antigravity-awesome-skills","pushed_at":"2026-04-22T06:40:00Z","description":"Installable GitHub library of 1,400+ agentic skills for Claude Code, Cursor, Codex CLI, Gemini CLI, Antigravity, and more. Includes installer CLI, bundles, workflows, and official/community skill collections.","skill_md_sha":"0f3205d2587690a93574a164ae1bcff573920270","skill_md_path":"skills/unit-testing-test-generate/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/unit-testing-test-generate"},"layout":"multi","source":"github","category":"antigravity-awesome-skills","frontmatter":{"name":"unit-testing-test-generate","description":"Generate comprehensive, maintainable unit tests across languages with strong coverage and edge case focus."},"skills_sh_url":"https://skills.sh/sickn33/antigravity-awesome-skills/unit-testing-test-generate"},"updatedAt":"2026-04-22T06:52:05.110Z"}}