python-testing-patterns
ما الذي تفعله
يعلّمك هذا الدليل كيفية اختبار كود Python بدقة. يشرح استخدام أدوات مثل pytest، وإنشاء اختبارات لأجزاء مختلفة من التطبيق، ومحاكاة المكونات الخارجية لتعمل اختباراتك بشكل أفضل.
متى تستخدمها
- ✓عندما تكتب اختبارات لكود Python الخاص بك.
- ✓عندما تنظم مجموعة الاختبارات أو البنية التي تشغّلها.
- ✓عندما تريد التأكد من أن الكود يعمل كما هو متوقع قبل إطلاقه.
رابط المهارة
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-testing-patterns/SKILL.mdانسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.
طريقة الاستخدام
أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.
رسالة جاهزة للصق
لـ Claude Code أو Codex أو Cursor: شغّله داخل مجلد مشروعك وستُثبَّت المهارة.
نزّل ملف SKILL.md وضعه في مجلد مهارات وكيلك.
مثال على ما تطلبه من الذكاء الاصطناعي
“كيف أكتب اختبارا بسيطا لدالة تجمع عددين في Python؟”
5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.
كيف تعمل
يشرح الدليل أنواع الاختبارات المختلفة وكيفية تنظيمها. ويعرض أمثلة على تسمية الاختبارات بوضوح، وعلى استخدام الأدوات لمحاكاة الاعتماديات الخارجية أو التحكم في الوقت.
المحتوى التقني (ملف SKILL.md الأصلي)
النص الأصلي من المؤلف، مباشرة من GitHub.
Python Testing Patterns
Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices.
When to Use This Skill
- Writing unit tests for Python code
- Setting up test suites and test infrastructure
- Implementing test-driven development (TDD)
- Creating integration tests for APIs and services
- Mocking external dependencies and services
- Testing async code and concurrent operations
- Setting up continuous testing in CI/CD
- Implementing property-based testing
- Testing database operations
- Debugging failing tests
Core Concepts
1. Test Types
- Unit Tests: Test individual functions/classes in isolation
- Integration Tests: Test interaction between components
- Functional Tests: Test complete features end-to-end
- Performance Tests: Measure speed and resource usage
2. Test Structure (AAA Pattern)
- Arrange: Set up test data and preconditions
- Act: Execute the code under test
- Assert: Verify the results
3. Test Coverage
- Measure what code is exercised by tests
- Identify untested code paths
- Aim for meaningful coverage, not just high percentages
4. Test Isolation
- Tests should be independent
- No shared state between tests
- Each test should clean up after itself
Quick Start
# test_example.py
def add(a, b):
return a + b
def test_add():
"""Basic test example."""
result = add(2, 3)
assert result == 5
def test_add_negative():
"""Test with negative numbers."""
assert add(-1, 1) == 0
# Run with: pytest test_example.py
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Testing Best Practices
Test Organization
# tests/
# __init__.py
# conftest.py # Shared fixtures
# test_unit/ # Unit tests
# test_models.py
# test_utils.py
# test_integration/ # Integration tests
# test_api.py
# test_database.py
# test_e2e/ # End-to-end tests
# test_workflows.py
Test Naming Convention
A common pattern: test_<unit>_<scenario>_<expected_outcome>. Adapt to your team's preferences.
# Pattern: test_<unit>_<scenario>_<expected>
def test_create_user_with_valid_data_returns_user():
...
def test_create_user_with_duplicate_email_raises_conflict():
...
def test_get_user_with_unknown_id_returns_none():
...
# Good test names - clear and descriptive
def test_user_creation_with_valid_data():
"""Clear name describes what is being tested."""
pass
def test_login_fails_with_invalid_password():
"""Name describes expected behavior."""
pass
def test_api_returns_404_for_missing_resource():
"""Specific about inputs and expected outcomes."""
pass
# Bad test names - avoid these
def test_1(): # Not descriptive
pass
def test_user(): # Too vague
pass
def test_function(): # Doesn't explain what's tested
pass
Testing Retry Behavior
Verify that retry logic works correctly using mock side effects.
from unittest.mock import Mock
def test_retries_on_transient_error():
"""Test that service retries on transient failures."""
client = Mock()
# Fail twice, then succeed
client.request.side_effect = [
ConnectionError("Failed"),
ConnectionError("Failed"),
{"status": "ok"},
]
service = ServiceWithRetry(client, max_retries=3)
result = service.fetch()
assert result == {"status": "ok"}
assert client.request.call_count == 3
def test_gives_up_after_max_retries():
"""Test that service stops retrying after max attempts."""
client = Mock()
client.request.side_effect = ConnectionError("Failed")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ConnectionError):
service.fetch()
assert client.request.call_count == 3
def test_does_not_retry_on_permanent_error():
"""Test that permanent errors are not retried."""
client = Mock()
client.request.side_effect = ValueError("Invalid input")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ValueError):
service.fetch()
# Only called once - no retry for ValueError
assert client.request.call_count == 1
Mocking Time with Freezegun
…
الأسئلة الشائعة
ما هي اختبارات الوحدة (unit tests) واختبارات التكامل (integration tests)؟
اختبارات الوحدة تفحص أجزاء صغيرة من الكود بمعزل عن غيرها، أما اختبارات التكامل فتفحص كيف تعمل أجزاء الكود المختلفة معا.
ما هو «المحاكاة» (mocking)؟
هي إنشاء نسخ وهمية من أجزاء الكود، مثل استدعاءات الشبكة أو قواعد البيانات، لتختبر الكود الرئيسي دون الاعتماد على تلك الأجزاء الخارجية.
ما هو TDD، أي التطوير المدفوع بالاختبارات؟
هو أسلوب تكتب فيه الاختبارات قبل كتابة الكود الفعلي، فيتأكد الكود من تلبية المتطلبات التي تحددها الاختبارات.
التفاصيل
الوصف الأصلي من المؤلف
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
repo: wshobson/agents
الشعبية
- نجوم GitHub
- 41k
- الترتيب
- #6768
- الترخيص
- MIT
- آخر تحديث
- 15/10/2026
التعليقات
- …
المزيد من المهارات من هذا المستودع
screen-reader-testing
41kيجعل وكيلك يختبر مواقع الويب باستخدام قارئات الشاشة للتأكد من أنها سهلة الوصول.
wcag-audit-patterns
41kيساعد وكيلك على تدقيق مواقع الويب من حيث إمكانية الوصول، وإصلاح المشكلات وفق إرشادات WCAG.
multi-reviewer-patterns
41kيمكّن وكيلك من تنسيق مراجعات الشيفرة المتوازية، مع إزالة التكرار في الملاحظات ودمج التقارير.
parallel-debugging
41kيتيح للوكيل تصحيح الأخطاء المعقدة عبر تحقيقات متوازية وتحليل السبب الجذري.
مهارات مشابهة
test-driven-development
311kيعلّم وكيلك كتابة اختبار فاشل أولًا، ثم رؤيته يفشل، ثم كتابة أصغر شيفرة تنجحه، قبل بناء أي ميزة أو إصلاح.
verification-before-completion
311kيعلّم وكيلك تشغيل فحوصات حقيقية وقراءة نتائجها قبل أن يقول إن المهمة أو الإصلاح أو البناء مكتمل أو ناجح.
migrate-to-shoehorn
310kيستبدل تأكيدات النوع الخطرة في ملفات الاختبار بمكتبة shoehorn، حتى تتمكن الاختبارات من استخدام بيانات جزئية وتجتاز فحوص الأنواع.