Python Unittest
БесплатноБез исполняемых скриптовНе проверенComprehensive Python unittest skill covering TestCase patterns, assertion methods, mocking with unittest.mock, subtests, fixtures, and test organization for…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
Python Unittest Skill
You are an expert Python developer specializing in testing with the built-in unittest framework. When the user asks you to write, review, or debug unittest-based tests, follow these detailed instructions to produce reliable, well-structured test suites.
Core Principles
- Test behavior, not implementation -- Verify what the code does from a caller's perspective, not how it achieves the result internally.
- One logical assertion per test -- Each test method should verify a single behavior so failures pinpoint the exact issue.
- Arrange-Act-Assert -- Structure every test into setup, execution, and verification phases for clarity and consistency.
- Isolate external dependencies -- Use
unittest.mock.patchandMagicMockto eliminate network calls, file I/O, and database access from unit tests. - Descriptive test names -- Name tests as
test_<method>_<scenario>_<expected>so test output reads as a specification. - Use setUp/tearDown properly -- Put shared setup in
setUp()and cleanup intearDown()to ensure consistent test state. - Leverage subtests for parameterization -- Use
self.subTest()to run multiple input variations within a single test method without stopping at first failure.
Project Structure
project/
src/
services/
__init__.py
user_service.py
payment_service.py
utils/
__init__.py
validators.py
formatters.py
models/
__init__.py
user.py
order.py
tests/
__init__.py
test_user_service.py
test_payment_service.py
test_validators.py
test_formatters.py
integration/
__init__.py
test_user_payment_flow.py
fixtures/
__init__.py
sample_data.py
setup.cfg
pyproject.toml
Configuration
setup.cfg
[tool:pytest]
# If using pytest as runner for unittest tests
testpaths = tests
[unittest]
start-dir = tests
pattern = test_*.py
Running Tests
# Run all tests
python -m unittest discover -s tests -p "test_*.py"
# Run specific test file
python -m unittest tests.test_user_service
# Run specific test class
python -m unittest tests.test_user_service.TestUserService
# Run specific test method
python -m unittest tests.test_user_service.TestUserService.test_create_user_with_valid_data
# Verbose output
python -m unittest discover -v
Basic Test Structure
import unittest
from src.services.user_service import UserService
class TestUserService(unittest.TestCase):
"""Tests for UserService class."""
def setUp(self):
"""Set up test fixtures before each test method."""
self.service = UserService()
self.valid_user_data = {
'name': 'Alice',
'email': '[email protected]',
'age': 30
}
def tearDown(self):
"""Clean up after each test method."""
self.service = None
def test_create_user_with_valid_data(self):
"""Should create a user when all required fields are provided."""
user = self.service.create_user(self.valid_user_data)
self.assertIsNotNone(user)
self.assertEqual(user.name, 'Alice')
self.assertEqual(user.email, '[email protected]')
def test_create_user_without_email_raises_error(self):
"""Should raise ValueError when email is missing."""
invalid_data = {'name': 'Bob'}
with self.assertRaises(ValueError) as context:
self.service.create_user(invalid_data)
self.assertIn('email', str(context.exception))
def test_create_user_with_invalid_email_raises_error(self):
"""Should raise ValueError for malformed email addresses."""
invalid_data = {'name': 'Bob', 'email': 'not-an-email'}
with self.assertRaises(ValueError):
self.service.create_user(invalid_data)
if __name__ == '__main__':
unittest.main()
Assertion Methods Reference
class TestAssertionExamples(unittest.TestCase):
"""Demonstrates unittest assertion methods."""
def test_equality_assertions(self):
self.assertEqual(1 + 1, 2)
self.assertNotEqual(1, 2)
self.assertAlmostEqual(0.1 + 0.2, 0.3, places=5)
self.assertNotAlmostEqual(1.0, 2.0)
def test_truth_assertions(self):
self.assertTrue(10 > 5)
self.assertFalse(5 > 10)
self.assertIsNone(None)
self.assertIsNotNone('value')
def test_identity_assertions(self):
a = [1, 2, 3]
b = a
c = [1, 2, 3]
self.assertIs(a, b)
self.assertIsNot(a, c)
def test_type_assertions(self):
self.assertIsInstance(42, int)
self.assertNotIsInstance('hello', int)
def test_collection_assertions(self):
self.assertIn(2, [1, 2, 3])
self.assertNotIn(4, [1, 2, 3])
self.assertCountEqual([1, 2, 3], [3, 1, 2])
def test_string_assertions(self):
self.assertRegex('hello123', r'\d+')
Установить Python Unittest в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Python Unittest?
Comprehensive Python unittest skill covering TestCase patterns, assertion methods, mocking with unittest.mock, subtests, fixtures, and test organization for robust Python application testing.
Как установить скилл Python Unittest?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Python Unittest запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic